Compare commits
71 Commits
v0.8.0
..
6f29731679
| Author | SHA1 | Date | |
|---|---|---|---|
| 6f29731679 | |||
| d7a9bd4ab2 | |||
| ab5489a080 | |||
| f4567a2e82 | |||
| 4b298ffc1c | |||
| 0f986cbf80 | |||
| 582bd0ee30 | |||
| 2e4030c2f2 | |||
| a9b662840b | |||
| 30bbb37bff | |||
| 2f6d6c405f | |||
| 068f42782b | |||
| 472c543c7b | |||
| 4e67a67ace | |||
| 1e63d3ae9d | |||
| b363efd1f0 | |||
| 0abbaa09f8 | |||
| 455b7a6893 | |||
| 92f76d091d | |||
| c1956e0028 | |||
| 491992a4d7 | |||
| e5b727216c | |||
| f03e337b9a | |||
| 99e99e7e08 | |||
| b93761eb1e | |||
| 4f5421191d | |||
| 71ed9dc24f | |||
| 1a0cc504c4 | |||
| 86775d4642 | |||
| b936f410ce | |||
| ddcd2076a1 | |||
| 9345facaed | |||
| 885caa6bc3 | |||
| a77bbe4420 | |||
| 61a4886e62 | |||
| 164f58c883 | |||
| fbfacb825b | |||
| 5e4d2cf993 | |||
| 97d3749269 | |||
| 0dcecf9a3c | |||
| c75e6406cd | |||
| 0254b44369 | |||
| ff11567471 | |||
| 06e383fe2c | |||
| dc5b31087a | |||
| 9e745dc3fc | |||
| 14b10c663e | |||
| f64c72f9a6 | |||
| 610eaf257e | |||
| b511740d93 | |||
| b0643b6f62 | |||
| 7e8d79222c | |||
| 14295ce859 | |||
| 5ad433e63a | |||
| 61e40e88f4 | |||
| 410955de3c | |||
| 9c0502eefb | |||
| 9b3da3a6e7 | |||
| bc41169176 | |||
| b3a1afce06 | |||
| 4b6dc8a47a | |||
| 3dadd5fc1a | |||
| bea844d51e | |||
| 5fb6c68df4 | |||
| 866a057704 | |||
| da8eab330d | |||
| 39bda0775e | |||
| ed4d3a3915 | |||
| 6447932212 | |||
| 9f278772bb | |||
| 2d073b6055 |
@@ -9,6 +9,9 @@ Checks:
|
||||
- -bugprone-easily-swappable-parameters
|
||||
- -bugprone-narrowing-conversions
|
||||
- -modernize-avoid-c-arrays
|
||||
# No forçar reemplaç de bucles "normals" per std::any_of/std::all_of.
|
||||
# Equivalent a `--suppress=useStlAlgorithm` que ja tenim a cppcheck.
|
||||
- -readability-use-anyofallof
|
||||
# performance-noexcept-move-constructor crashea clang-tidy (LLVM 19.1)
|
||||
# con recursión infinita en ExceptionSpecAnalyzer::analyzeRecord cuando
|
||||
# analiza ciertas instanciaciones de std::set. No es un falso positivo
|
||||
|
||||
+5
-2
@@ -1,5 +1,5 @@
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
project(orni VERSION 0.8.0 LANGUAGES CXX)
|
||||
project(orni VERSION 0.8.1 LANGUAGES CXX)
|
||||
|
||||
# Info del projecte (font de veritat per a project.h)
|
||||
set(PROJECT_LONG_NAME "Orni Attack")
|
||||
@@ -110,7 +110,10 @@ add_executable(pack_resources EXCLUDE_FROM_ALL
|
||||
tools/pack_resources/pack_resources.cpp
|
||||
source/core/resources/resource_pack.cpp
|
||||
)
|
||||
target_include_directories(pack_resources PRIVATE "${CMAKE_SOURCE_DIR}/source")
|
||||
target_include_directories(pack_resources PRIVATE
|
||||
"${CMAKE_SOURCE_DIR}/source"
|
||||
"${CMAKE_BINARY_DIR}"
|
||||
)
|
||||
target_compile_options(pack_resources PRIVATE -Wall -Wextra -Wpedantic)
|
||||
|
||||
# --- REGENERACIÓ AUTOMÀTICA DE build/resources.pack ---
|
||||
|
||||
@@ -0,0 +1,838 @@
|
||||
# Arquitectura de Orni Attack
|
||||
|
||||
> Documento de orientación para alguien que llega nuevo al proyecto. Cada
|
||||
> afirmación está anclada a código real (fichero/clase/función con su ruta).
|
||||
> Cuando algo no se ha podido verificar o no existe, se indica explícitamente.
|
||||
> El objetivo no es vender una arquitectura ideal, sino describir lo que **este**
|
||||
> proyecto hace, incluso donde es poco convencional.
|
||||
|
||||
## Índice
|
||||
|
||||
1. [Visión general](#1-visión-general)
|
||||
2. [Punto de entrada y el Director](#2-punto-de-entrada-y-el-director)
|
||||
3. [Bucle principal](#3-bucle-principal)
|
||||
4. [Sistema de escenas](#4-sistema-de-escenas)
|
||||
5. [Renderizado: de la lógica al píxel](#5-renderizado-de-la-lógica-al-píxel)
|
||||
6. [Entrada](#6-entrada)
|
||||
7. [Audio](#7-audio)
|
||||
8. [Recursos](#8-recursos)
|
||||
9. [Comunicación entre módulos](#9-comunicación-entre-módulos)
|
||||
10. [Lógica del juego](#10-lógica-del-juego)
|
||||
11. [IA del modo demo (attract)](#11-ia-del-modo-demo-attract)
|
||||
12. [Efectos visuales](#12-efectos-visuales)
|
||||
13. [Configuración, constantes y convenciones](#13-configuración-constantes-y-convenciones)
|
||||
14. [Guía de navegación](#14-guía-de-navegación)
|
||||
|
||||
---
|
||||
|
||||
## 1. Visión general
|
||||
|
||||
Orni Attack es un arcade vectorial (estética CRT de líneas con bloom) construido
|
||||
sobre **SDL3**, usando la **GPU API de SDL3** (`SDL_gpu`) para el render — **no**
|
||||
`SDL_Renderer`. El código está partido en dos grandes mundos:
|
||||
|
||||
- **`source/core/`** — el "motor": ventana, GPU, audio, input, recursos, i18n,
|
||||
overlays de sistema. No conoce nada del juego concreto. Por ejemplo,
|
||||
[audio.hpp](source/core/audio/audio.hpp) recibe un struct de configuración y no
|
||||
lee YAML, e [input.hpp](source/core/input/input.hpp) no incluye nada de `game/`.
|
||||
- **`source/game/`** — la lógica concreta de Orni Attack: escenas, entidades
|
||||
(naves, enemigos, balas), sistemas (colisiones, IA), stages/oleadas y efectos.
|
||||
|
||||
El punto de indirección entre ambos mundos para el render es
|
||||
[render_context.hpp](source/core/rendering/render_context.hpp): el juego habla con
|
||||
un `Rendering::Renderer*` opaco que es un alias de `GPU::GpuFrameRenderer`. Esto
|
||||
permite cambiar de backend sin tocar las firmas del juego.
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
subgraph entry["Punto de entrada"]
|
||||
MAIN["main.cpp<br/>SDL_MAIN_USE_CALLBACKS"]
|
||||
end
|
||||
MAIN -->|posee| DIR["Director<br/>(es el programa)"]
|
||||
|
||||
subgraph core["source/core (motor)"]
|
||||
SDLM["SDLManager<br/>ventana + GPU"]
|
||||
GE["GlobalEvents<br/>F1-F7/F12/ESC/hotplug"]
|
||||
INPUT["Input (singleton)"]
|
||||
AUDIO["Audio (singleton)"]
|
||||
RES["Resource::Loader / Pack"]
|
||||
LOC["Locale (i18n)"]
|
||||
OVL["Notifier · ServiceMenu<br/>DebugOverlay · DefineInputs"]
|
||||
end
|
||||
|
||||
subgraph game["source/game (juego)"]
|
||||
SCN["Scenes<br/>Logo · Title · Game"]
|
||||
ENT["Entities<br/>Ship · Enemy · Bullet"]
|
||||
SYS["Systems<br/>Collision · EnemyAi · DemoPilot"]
|
||||
STG["StageManager / WaveRunner"]
|
||||
FX["Effects<br/>debris · firework · score · trail"]
|
||||
end
|
||||
|
||||
DIR --> SDLM
|
||||
DIR --> GE
|
||||
DIR --> OVL
|
||||
DIR --> SCN
|
||||
SCN --> ENT
|
||||
SCN --> SYS
|
||||
SCN --> STG
|
||||
SCN --> FX
|
||||
GE --> INPUT
|
||||
SCN -.usa.-> AUDIO
|
||||
SCN -.usa.-> RES
|
||||
OVL -.usa.-> LOC
|
||||
```
|
||||
|
||||
**Patrón dominante de comunicación:** singletons globales (`Input::get()`,
|
||||
`Audio::get()`, `Locale::get()`, `Notifier`, `ServiceMenu`) más paso por
|
||||
referencia de un `Rendering::Renderer*` y un `SceneContext&`. **No hay** un bus de
|
||||
eventos genérico ni un ECS — las entidades viven en `std::array` de tamaño fijo
|
||||
dentro de `GameScene` y los sistemas operan sobre un struct `Context` de punteros
|
||||
(ver [§10](#10-lógica-del-juego)).
|
||||
|
||||
**Rasgo de diseño destacable:** gran parte de la lógica es *data-driven*. Los
|
||||
enemigos, balas y el jugador se describen en **YAML declarativo**
|
||||
(`data/entities/*/*.yaml`: physics/ai/animation/events), los stages en
|
||||
`data/stages/stages.yaml` (oleadas), y las figuras vectoriales en ficheros `.shp`.
|
||||
|
||||
---
|
||||
|
||||
## 2. Punto de entrada y el Director
|
||||
|
||||
El `main` real está en [main.cpp](source/main.cpp) y usa el modo de callbacks de
|
||||
SDL3 (`#define SDL_MAIN_USE_CALLBACKS 1`). En lugar de un bucle `while` clásico,
|
||||
SDL llama a cuatro funciones, y todas son pura fontanería que delega en un
|
||||
`Director`:
|
||||
|
||||
```cpp
|
||||
// main.cpp
|
||||
auto SDL_AppInit(void** appstate, int argc, char* argv[]) -> SDL_AppResult {
|
||||
System::Relaunch::setArgv(argc, argv);
|
||||
auto director = std::make_unique<Director>(argc, argv);
|
||||
*appstate = director.release(); // SDL guarda el puntero
|
||||
return SDL_APP_CONTINUE;
|
||||
}
|
||||
auto SDL_AppEvent(void* s, SDL_Event* e) { return ((Director*)s)->handleEvent(*e); }
|
||||
auto SDL_AppIterate(void* s) { return ((Director*)s)->iterate(); }
|
||||
void SDL_AppQuit(void* s, ...) { /* reabsorbe y destruye el Director */ }
|
||||
```
|
||||
|
||||
La filosofía está escrita en el propio comentario de cabecera de
|
||||
[director.hpp](source/core/system/director.hpp):
|
||||
|
||||
> *El Director és EL programa: posseeix la configuració, els subsistemes i
|
||||
> l'estat.*
|
||||
|
||||
Como con `SDL_MAIN_USE_CALLBACKS` no hay un `scope` que envuelva todo el bucle,
|
||||
el estado que antes vivía en un `run()` ahora es **miembro** del Director:
|
||||
`sdl_` (SDLManager), `context_` (SceneContext), `debug_overlay_` y
|
||||
`current_scene_` (todos `std::unique_ptr`, ver
|
||||
[director.hpp:45-48](source/core/system/director.hpp#L45-L48)).
|
||||
|
||||
### Orden de arranque (constructor)
|
||||
|
||||
El constructor [Director::Director](source/core/system/director.cpp#L46) ejecuta el
|
||||
bootstrap completo, en este orden:
|
||||
|
||||
1. `ConfigYaml::init()` — valores por defecto de configuración.
|
||||
2. Parseo de argumentos (`--console`, `--reset-config`) en
|
||||
[checkProgramArguments](source/core/system/director.cpp#L241).
|
||||
3. `Utils::initializePathSystem()` + sistema de recursos
|
||||
([§8](#8-recursos)): en *release* el `resources.pack` es obligatorio; en *dev*
|
||||
hay fallback a `data/`.
|
||||
4. Crea la carpeta de sistema (`~/.config/jailgames/<NAME>` en Linux) y carga/crea
|
||||
`config.yaml` ([createSystemFolder](source/core/system/director.cpp#L260)).
|
||||
5. Carga el `locale` ([§7](#7-audio) usa lo mismo: i18n).
|
||||
6. `Input::init()` con el `gamecontrollerdb.txt` (autoasigna mandos a P1/P2 la
|
||||
primera vez).
|
||||
7. Crea `SDLManager` (ventana + GPU), oculta el cursor, inicializa `Audio`.
|
||||
8. **Precarga bloqueante** de todos los recursos (música, sonidos, shapes) para
|
||||
evitar tirones de I/O en las transiciones
|
||||
([director.cpp:187-195](source/core/system/director.cpp#L187-L195)).
|
||||
9. Crea el `SceneContext` y fija la escena inicial: `TITLE` en `_DEBUG`, `LOGO`
|
||||
en el resto ([director.cpp:200-205](source/core/system/director.cpp#L200-L205)).
|
||||
10. Inicializa los overlays de sistema: `DebugOverlay`, `Notifier`, `ServiceMenu`,
|
||||
`DefineInputs`.
|
||||
|
||||
El destructor [Director::~Director](source/core/system/director.cpp#L218) guarda
|
||||
la config y destruye los subsistemas **en orden inverso** a la construcción (el
|
||||
`Notifier` referencia el renderer, así que debe morir antes que `sdl_`).
|
||||
|
||||
---
|
||||
|
||||
## 3. Bucle principal
|
||||
|
||||
Cada frame, SDL llama a `SDL_AppIterate`, que delega en
|
||||
[Director::iterate()](source/core/system/director.cpp#L383). Su estructura es:
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant SDL
|
||||
participant Dir as Director::iterate()
|
||||
participant Scene
|
||||
participant SDLM as SDLManager
|
||||
participant GPU as GpuFrameRenderer
|
||||
|
||||
SDL->>Dir: iterate()
|
||||
Note over Dir: si wants_quit_ → SDL_APP_SUCCESS
|
||||
Dir->>Dir: si !scene o scene.isFinished() → advanceScene()
|
||||
Dir->>Dir: delta_time = (now - last) capeado a 50 ms
|
||||
Dir->>Dir: Input::update()
|
||||
Dir->>Scene: update(dt)
|
||||
Dir->>Dir: overlays.update(dt) + Audio::update()
|
||||
Dir->>SDLM: clear() (= GPU.beginFrame)
|
||||
alt swapchain no disponible
|
||||
SDLM-->>Dir: false → saltar draw+present
|
||||
end
|
||||
Dir->>SDLM: updateRenderingContext()
|
||||
Dir->>Scene: draw()
|
||||
Dir->>Dir: overlays.draw() (capas)
|
||||
Dir->>SDLM: present() (= GPU.endFrame → bloom + postfx)
|
||||
```
|
||||
|
||||
Puntos concretos a tener en cuenta:
|
||||
|
||||
- **Pivot de escena**: si no hay escena o la actual reporta `isFinished()`, se
|
||||
llama a [advanceScene()](source/core/system/director.cpp#L338), que destruye la
|
||||
actual y construye la siguiente con
|
||||
[buildScene()](source/core/system/director.cpp#L323) según
|
||||
`context_->nextScene()`.
|
||||
- **Delta time**: se mide con `SDL_GetTicks()` y se **capea a 50 ms** para evitar
|
||||
saltos grandes tras un stall ([director.cpp:397-400](source/core/system/director.cpp#L397-L400)).
|
||||
- **Orden de update**: `Input::update()` → `current_scene_->update(dt)` →
|
||||
`debug_overlay_` → `Notifier` → `ServiceMenu` → `DefineInputs` → `Audio::update()`.
|
||||
- **Render por capas** (de abajo arriba, entre `clear` y `present`):
|
||||
escena → `debug_overlay_` → `Notifier` (toasts) → `ServiceMenu` → `DefineInputs`
|
||||
(modal de rebinding). Si el overlay de rebinding está activo, el menú de servicio
|
||||
no se pinta ([director.cpp:432-439](source/core/system/director.cpp#L432-L439)).
|
||||
- **Salto de frame**: si `sdl_->clear()` devuelve `false` (swapchain no disponible,
|
||||
p. ej. ventana minimizada), se omiten `draw` y `present` ese frame.
|
||||
|
||||
El bucle de eventos vive aparte, en
|
||||
[Director::handleEvent()](source/core/system/director.cpp#L354), que enruta cada
|
||||
`SDL_Event` por la cadena: **ventana → GlobalEvents → F11 (debug overlay) →
|
||||
escena** (ver [§9](#9-comunicación-entre-módulos)).
|
||||
|
||||
---
|
||||
|
||||
## 4. Sistema de escenas
|
||||
|
||||
La interfaz base es [scene.hpp](source/core/system/scene.hpp). Como dice su
|
||||
cabecera, *el frame loop vive en el Director, no en cada escena*. Cada escena
|
||||
implementa cuatro métodos puros:
|
||||
|
||||
```cpp
|
||||
virtual void handleEvent(const SDL_Event&) = 0; // eventos no-globales
|
||||
virtual void update(float delta_time) = 0; // lógica
|
||||
virtual void draw() = 0; // pintado (entre clear y present)
|
||||
virtual auto isFinished() const -> bool = 0; // ¿transición pendiente?
|
||||
```
|
||||
|
||||
Una escena pide transición vía `context_.setNextScene(...)`; en el siguiente frame
|
||||
`isFinished()` devuelve `true` y el Director la destruye para construir la
|
||||
siguiente.
|
||||
|
||||
### SceneContext
|
||||
|
||||
[scene_context.hpp](source/core/system/scene_context.hpp) es el "buzón" de
|
||||
transición que el Director posee y va pasando a cada escena por referencia. Tiene:
|
||||
|
||||
- `SceneType` (enum): `LOGO`, `TITLE`, `GAME`, `EXIT`.
|
||||
- `Option` (p. ej. `JUMP_TO_TITLE_MAIN`) consumible con `consumeOption()`.
|
||||
- `MatchConfig` (jugadores activos, modo NORMAL/DEMO) para pasar a `GAME`.
|
||||
- El **índice del escenario de demo** (`demoScenarioIndex()` / `advanceDemoScenario()`),
|
||||
que persiste entre escenas para que cada entrada al attract mode muestre el
|
||||
siguiente escenario curado (ver [§11](#11-ia-del-modo-demo-attract)).
|
||||
|
||||
Existe además una variable global `SceneManager::actual` que el Director mantiene
|
||||
sincronizada con la escena en curso (compatibilidad hacia atrás).
|
||||
|
||||
### Las tres escenas (FSM jerárquica)
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> LOGO
|
||||
LOGO --> TITLE
|
||||
TITLE --> GAME : START (1P/2P)
|
||||
TITLE --> GAME : idle timeout (DEMO)
|
||||
GAME --> TITLE : game over / fin demo (input)
|
||||
GAME --> LOGO : fin demo (timeout/muerte)
|
||||
TITLE --> [*] : EXIT
|
||||
```
|
||||
|
||||
Cada escena tiene además su **propia** máquina de estados interna:
|
||||
|
||||
- **[LogoScene](source/game/scenes/logo_scene.hpp)** — `AnimationState`:
|
||||
`PRE_ANIMATION → ANIMATION → POST_ANIMATION → EXPLOSION → POST_EXPLOSION`. Anima
|
||||
el logo JAILGAMES y lo hace explotar en fragmentos (debris).
|
||||
- **[TitleScene](source/game/scenes/title_scene.hpp)** — `TitleState`:
|
||||
`STARFIELD_FADE_IN → STARFIELD → MAIN → PLAYER_JOIN_PHASE → BLACK_SCREEN →
|
||||
DEMO_DIVE → DEMO_CURTAIN`. Naves 3D flotantes (vía
|
||||
[ShipAnimator](source/game/title/ship_animator.hpp)), selección 1P/2P, y un
|
||||
`idle_timer_` en el estado `MAIN` que dispara el attract mode por inactividad.
|
||||
- **[GameScene](source/game/scenes/game_scene.hpp)** — es el núcleo del juego y se
|
||||
detalla en [§10](#10-lógica-del-juego).
|
||||
|
||||
---
|
||||
|
||||
## 5. Renderizado: de la lógica al píxel
|
||||
|
||||
Este es el subsistema más denso. La idea central: **toda la geometría son líneas**
|
||||
(la estética es vectorial). El juego acumula líneas en CPU durante `draw()`, y al
|
||||
final del frame se envían a la GPU en un único batch, se rasterizan a una textura
|
||||
*offscreen*, y un par de pases de post-procesado (bloom + flicker/fondo) componen
|
||||
la imagen final sobre la swapchain.
|
||||
|
||||
### 5.1 Capas del subsistema
|
||||
|
||||
| Fichero | Rol |
|
||||
|---|---|
|
||||
| [sdl_manager.hpp/.cpp](source/core/rendering/sdl_manager.hpp) | Crea la ventana SDL, posee el `GpuFrameRenderer`, gestiona zoom/fullscreen/letterbox. Expone `clear()` / `present()` / `getRenderer()`. |
|
||||
| [gpu/gpu_frame_renderer.hpp/.cpp](source/core/rendering/gpu/gpu_frame_renderer.hpp) | Orquestador del frame GPU: `beginFrame` → `pushLine`/`pushRect` → `endFrame` (`flushBatch` + `bloomPass` + `compositePass`). |
|
||||
| [gpu/gpu_device](source/core/rendering/gpu/gpu_device.hpp) | Wrapper del `SDL_GPUDevice` (claim de ventana, formato de swapchain). |
|
||||
| [gpu/gpu_line_pipeline](source/core/rendering/gpu/gpu_line_pipeline.hpp) | Pipeline de líneas: dibuja cada línea como un quad (2 triángulos) con antialias geométrico. |
|
||||
| [gpu/gpu_bloom_pipeline](source/core/rendering/gpu/gpu_bloom_pipeline.hpp) | Blur gaussiano separable (pase H + pase V) sobre dos texturas ping-pong. |
|
||||
| [gpu/gpu_postfx_pipeline](source/core/rendering/gpu/gpu_postfx_pipeline.hpp) | Composite final: mezcla escena + bloom + flicker + fondo pulsante. |
|
||||
| [line_renderer.hpp/.cpp](source/core/rendering/line_renderer.hpp) | API que usa el juego: `Rendering::linea(...)` y `lineaGlow(...)`. |
|
||||
| [shape_renderer.hpp/.cpp](source/core/rendering/shape_renderer.hpp) | `renderShape(...)`: dibuja una `Shape` aplicando transformación y, opcionalmente, glow multipase. |
|
||||
|
||||
### 5.2 Una `Shape` y cómo se carga
|
||||
|
||||
Una "shape" es una figura vectorial: un conjunto de **polilíneas** y **líneas**
|
||||
([shape.hpp](source/core/graphics/shape.hpp)). Los ficheros viven en `data/shapes/`
|
||||
con extensión `.shp` y un formato de texto tipo clave:valor. Ejemplo real
|
||||
([data/shapes/ship/arrow.shp](data/shapes/ship/arrow.shp)):
|
||||
|
||||
```
|
||||
name: arrow
|
||||
scale: 1.0
|
||||
center: 0, 0
|
||||
polyline: 0,-12 8.49,8.49 0,4 -8.49,8.49 0,-12
|
||||
```
|
||||
|
||||
> Nota: el formato real usa directivas `name:`, `scale:`, `center:`,
|
||||
> `polyline:` y `line:` (Y negativo = arriba). No es la sintaxis
|
||||
> `POLYLINE: (x,y)` que podría suponerse de otros motores.
|
||||
|
||||
La carga la centraliza [shape_loader.hpp](source/core/graphics/shape_loader.hpp)
|
||||
(`Graphics::ShapeLoader::load(filename)`), con caché de `std::shared_ptr<Shape>`.
|
||||
Todas las shapes se precargan en el boot del Director.
|
||||
|
||||
### 5.3 El flujo de un frame de render
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A["Scene::draw()<br/>(acumula en CPU)"] --> B["Rendering::linea / renderShape"]
|
||||
B --> C["GpuFrameRenderer::pushLine()<br/>extruye quad → vertices_ / indices_"]
|
||||
C -.repetido N veces.-> C
|
||||
A --> D["SDLManager::present()<br/>= GpuFrameRenderer::endFrame()"]
|
||||
D --> E["flushBatch()<br/>sube VBO/IBO, dibuja sobre OFFSCREEN"]
|
||||
E --> F["bloomPass()<br/>H: high-pass+blur → bloom_a<br/>V: blur → bloom_b"]
|
||||
F --> G["compositePass()<br/>offscreen + bloom_b + flicker + fondo<br/>→ swapchain (letterbox)"]
|
||||
G --> H["SubmitGPUCommandBuffer + present"]
|
||||
```
|
||||
|
||||
Paso a paso, con anclas reales:
|
||||
|
||||
1. **Emisión (juego).** Durante `current_scene_->draw()`, el juego llama a
|
||||
[Rendering::linea()](source/core/rendering/line_renderer.hpp#L33) (y
|
||||
`renderShape`, `VectorText`, `Playfield`, etc.). Las coordenadas son **lógicas
|
||||
(1280×720)**. El color por defecto si `alpha==0` es el verde fósforo CRT
|
||||
`DEFAULT_LINE_COLOR = {100,255,100,255}`.
|
||||
2. **Acumulación (CPU).** `linea()` pre-multiplica el brillo y llama a
|
||||
[GpuFrameRenderer::pushLine()](source/core/rendering/gpu/gpu_frame_renderer.hpp#L88),
|
||||
que **extruye** la línea en un quad (4 vértices, 6 índices) y lo acumula en
|
||||
`vertices_` / `indices_`. Si el antialias está activo, añade ~0.5 px de padding y
|
||||
marca `edge_dist` para el fade del fragment shader.
|
||||
3. **Flush (GPU).** En `endFrame()`, `flushBatch()` sube el batch a un VBO/IBO,
|
||||
abre un render pass sobre el `offscreen_texture_` (R8G8B8A8, tamaño físico
|
||||
configurable, independiente del lógico) y dibuja con el `line_pipeline_`. El
|
||||
vertex shader transforma píxeles lógicos → NDC; el fragment shader aplica
|
||||
`smoothstep` sobre `edge_dist` para el suavizado.
|
||||
4. **Bloom.** `bloomPass()` hace un blur separable: pase H (high-pass por
|
||||
luminancia + blur horizontal → `bloom_texture_a_`) y pase V (blur vertical →
|
||||
`bloom_texture_b_`). Parámetros en `PostFxParams`
|
||||
([gpu_frame_renderer.hpp:33-51](source/core/rendering/gpu/gpu_frame_renderer.hpp#L33-L51)).
|
||||
5. **Composite.** `compositePass()` dibuja un triángulo *fullscreen* sobre la
|
||||
swapchain, muestreando offscreen + bloom, aplicando flicker temporal y un fondo
|
||||
verde pulsante. Aquí se aplica el **letterbox** vía el viewport físico
|
||||
(`setViewport`).
|
||||
|
||||
El interruptor maestro de post-proceso es **F6** (`setPostFxEnabled`): cuando está
|
||||
OFF, la escena offscreen sale tal cual (passthrough), útil para A/B testing.
|
||||
|
||||
### 5.4 Texto, 3D y elementos de escena
|
||||
|
||||
- **[VectorText](source/core/graphics/vector_text.hpp)** — renderiza texto donde
|
||||
cada carácter es una `Shape` precargada.
|
||||
- **[Camera3D](source/core/graphics/camera3d.hpp)** + **[Wireframe3D](source/core/graphics/wireframe3d.hpp)**
|
||||
— proyección perspectiva en CPU de mallas 3D (vértices + aristas) a líneas 2D.
|
||||
Lo usan el starfield 3D y las naves del título.
|
||||
- **[Starfield](source/core/graphics/starfield.hpp)** (campo de estrellas 3D que
|
||||
vienen hacia la cámara) y **[StarfieldParallax](source/core/graphics/starfield_parallax.hpp)**
|
||||
(capas 2D de fondo con parallax).
|
||||
- **[Playfield](source/core/graphics/playfield.hpp)** — rejilla de fondo con
|
||||
animación de construcción y *ripples* (ondas) que reaccionan a la nave y a las
|
||||
explosiones.
|
||||
- **[Border](source/core/graphics/border.hpp)** — marco de 4 lados que se desplaza
|
||||
al recibir impactos.
|
||||
- **[Curtain](source/core/graphics/curtain.hpp)** — cortinilla negra para
|
||||
transiciones; se pinta siempre la última.
|
||||
|
||||
### 5.5 Shaders: fuentes, compilación y selección
|
||||
|
||||
Las fuentes GLSL viven en [shaders/](shaders/): `line.vert.glsl`, `line.frag.glsl`,
|
||||
`postfx.vert.glsl`, `postfx.frag.glsl`, `bloom.frag.glsl`. **No se cargan de disco en
|
||||
runtime**: se embeben como arrays/strings en el binario.
|
||||
|
||||
**Pipeline de compilación (SPIR-V, Linux/Windows).** Lo orquesta
|
||||
[CMakeLists.txt:139-187](CMakeLists.txt#L139). La lógica clave:
|
||||
|
||||
- Para cada `.glsl` hay un header destino en
|
||||
[gpu/spv/](source/core/rendering/gpu/spv/) (p. ej. `line_vert_spv.h`).
|
||||
- CMake busca `glslc` (`find_program(GLSLC_EXE ...)`). Hay **tres caminos**:
|
||||
1. `glslc` presente → un `add_custom_command` regenera los headers SPV cuando
|
||||
cambian los `.glsl`, vía el target `shaders` del que depende el ejecutable.
|
||||
2. `glslc` ausente pero **los headers ya están commiteados** → se usan tal cual
|
||||
(los `.spv.h` están versionados en el repo).
|
||||
3. `glslc` ausente **y** faltan headers → `FATAL_ERROR` pidiendo instalar
|
||||
`shaderc`/`vulkan-sdk`.
|
||||
- La conversión binario→header la hace el script
|
||||
[tools/shaders/compile_spirv.cmake](tools/shaders/compile_spirv.cmake): invoca
|
||||
`glslc -O -fshader-stage=<vert|frag>` para producir el `.spv`, lee el binario como
|
||||
hex (`file(READ ... HEX)`) y escribe un header con
|
||||
`static const uint8_t LINE_VERT_SPV[] = { 0x.., ... };` y su `_SIZE`. Es
|
||||
multiplataforma puro CMake (no necesita `bash` ni `xxd`).
|
||||
|
||||
**MSL (macOS).** Los headers Metal en [gpu/msl/](source/core/rendering/gpu/msl/)
|
||||
(`line_vert.msl.h`, etc.) están **escritos a mano** (no los genera CMake), como
|
||||
strings literales C++.
|
||||
|
||||
**Selección SPV vs MSL: es _compile-time_, no runtime.** La hace
|
||||
[shader_factory.hpp](source/core/rendering/gpu/shader_factory.hpp) con `#ifdef __APPLE__`:
|
||||
en Apple expone `createShaderMSL(...)` (`SDL_GPU_SHADERFORMAT_MSL`), y en el resto
|
||||
`createShaderSPIRV(...)` (`SDL_GPU_SHADERFORMAT_SPIRV`). Cada pipeline llama al helper
|
||||
disponible con el header embebido correspondiente. (Es decir: no es `GpuDevice` quien
|
||||
elige el backend de shader, sino el preprocesador al compilar.)
|
||||
|
||||
---
|
||||
|
||||
## 6. Entrada
|
||||
|
||||
El subsistema de input ([core/input/](source/core/input/)) es un **singleton**
|
||||
(`Input::init()` / `Input::get()` / `Input::destroy()`) que unifica teclado,
|
||||
gamepads y ratón.
|
||||
|
||||
- **Acciones**: enum `InputAction` (`LEFT`, `RIGHT`, `THRUST`, `SHOOT`, `START`,
|
||||
`MENU`, ...) en [input_types.hpp](source/core/input/input_types.hpp).
|
||||
- **Bindings por jugador**: hay bindings separados de teclado y de gamepad para P1
|
||||
y P2, que se cargan de la config con `applyPlayer1Bindings()` /
|
||||
`applyPlayer2Bindings()` (llamados desde el constructor del Director).
|
||||
- **Captura por frame**: `Input::update()` lee `SDL_GetKeyboardState()` y los ejes
|
||||
y botones del gamepad, y hace *edge-detection* para distinguir `just_pressed` de
|
||||
`is_held`. La consulta es `checkAction(...)` / `checkActionPlayer1/2(...)`.
|
||||
- **Hotplug**: `Input::handleEvent()` procesa `SDL_EVENT_GAMEPAD_ADDED/REMOVED`
|
||||
(`addGamepad` / `removeGamepad`) y notifica con un toast vía `Notifier`.
|
||||
- **Ratón**: [mouse.hpp](source/core/input/mouse.hpp) auto-oculta el cursor.
|
||||
- **Rebinding en runtime**: [define_inputs.hpp](source/core/input/define_inputs.hpp)
|
||||
es un modal singleton que captura una secuencia de acciones, persiste en config y
|
||||
reaplica bindings sin reiniciar.
|
||||
|
||||
El enrutado de input ocurre en dos sitios: los eventos **globales** pasan por
|
||||
`GlobalEvents::handle()` (que primero deja a `Input` procesar el hotplug), y la
|
||||
lógica de juego consulta directamente `Input::get()->checkAction...` durante
|
||||
`update()` (p. ej. [Ship::processInput](source/game/entities/ship.hpp)).
|
||||
|
||||
---
|
||||
|
||||
## 7. Audio
|
||||
|
||||
[core/audio/](source/core/audio/) es otro singleton (`Audio::init/get/destroy`)
|
||||
con un motor de bajo nivel propio:
|
||||
|
||||
- **[Audio](source/core/audio/audio.hpp)** — capa lógica: `playMusic()`,
|
||||
`playSound()`, volúmenes por grupo (`GAME`, `INTERFACE`), `playSoundWithEcho/Reverb`.
|
||||
- **[jail_audio.hpp](source/core/audio/jail_audio.hpp)** (`Ja::Engine`) — motor
|
||||
sobre SDL3 audio: streaming de **OGG** (vía `stb_vorbis`) para música, **WAV**
|
||||
descomprimido para efectos, mezcla en N canales.
|
||||
- **[audio_adapter.hpp](source/core/audio/audio_adapter.hpp)** —
|
||||
`AudioResource::getMusic/getSound`: caché *lazy* que carga bytes vía
|
||||
`Resource::Helper` y los decodifica una sola vez.
|
||||
- **[audio_effects.hpp](source/core/audio/audio_effects.hpp)** — DSP de echo y
|
||||
reverb; presets en `data/config/sounds.yaml`
|
||||
([sound_effects_config.hpp](source/core/audio/sound_effects_config.hpp)).
|
||||
|
||||
El Director precarga toda la música y todos los sonidos en el boot, y llama a
|
||||
`Audio::update()` una vez por frame.
|
||||
|
||||
---
|
||||
|
||||
## 8. Recursos
|
||||
|
||||
[core/resources/](source/core/resources/) abstrae de dónde salen los bytes:
|
||||
|
||||
- **[resource_pack](source/core/resources/resource_pack.hpp)** (`Resource::Pack`)
|
||||
— lee un fichero empaquetado con cabecera *magic* `"ORNI"` y entradas con CRC32
|
||||
para validación de integridad.
|
||||
- **[resource_loader](source/core/resources/resource_loader.hpp)**
|
||||
(`Resource::Loader`, singleton Meyers) — `loadResource()`, `resourceExists()`,
|
||||
`listResources(prefix)`, `validatePack()`.
|
||||
- **[resource_helper](source/core/resources/resource_helper.hpp)** — wrappers de
|
||||
conveniencia (`initializeResourceSystem`, `listResources`, `loadFile`).
|
||||
|
||||
**Estrategia dual** (decidida en el constructor del Director,
|
||||
[director.cpp:64-93](source/core/system/director.cpp#L64-L93)):
|
||||
|
||||
- **Release** (`RELEASE_BUILD`): `resources.pack` es **obligatorio** y se valida su
|
||||
integridad; si falla, el juego aborta. No hay fallback (ver memoria de proyecto
|
||||
*"No fallback a SDL_Renderer"* — aquí es la política equivalente para recursos).
|
||||
- **Dev**: intenta el pack; si no está, hace **fallback al directorio `data/`** del
|
||||
filesystem, escaneándolo según prefijo (`music/`, `sounds/`, `shapes/`).
|
||||
|
||||
El formato de datos de juego:
|
||||
|
||||
- **Entidades** (`data/entities/<nombre>/<nombre>.yaml`) — YAML declarativo con
|
||||
`shape`, `physics`, `ai`, `animation`, `wounded`, `spawn`, `colors`, `score`,
|
||||
`events`. Ejemplo: [data/entities/square/square.yaml](data/entities/square/square.yaml).
|
||||
- **Stages** (`data/stages/stages.yaml`) — oleadas (`waves`) con `spawn`,
|
||||
`spawn_interval`, `next` y multiplicadores de dificultad por stage.
|
||||
- **Shapes** (`data/shapes/**/*.shp`) — figuras vectoriales (ver [§5.2](#52-una-shape-y-cómo-se-carga)).
|
||||
|
||||
El parser YAML usado es [fkyaml](source/external/fkyaml_node.hpp) (cabecera única),
|
||||
envuelto por [config_yaml](source/game/config_yaml.hpp).
|
||||
|
||||
---
|
||||
|
||||
## 9. Comunicación entre módulos
|
||||
|
||||
No hay un sistema de mensajería desacoplado. La comunicación es:
|
||||
|
||||
1. **Eventos SDL → cadena del Director.** Por cada `SDL_Event`,
|
||||
[Director::handleEvent](source/core/system/director.cpp#L354) intenta, en orden:
|
||||
`SDLManager::handleWindowEvent` → `GlobalEvents::handle` → F11 (debug overlay) →
|
||||
`current_scene_->handleEvent`.
|
||||
|
||||
2. **GlobalEvents** ([global_events.cpp](source/core/system/global_events.cpp)) es
|
||||
el orquestador de la entrada global. Su `handle()` hace, en orden:
|
||||
`Input::get()->handleEvent` (hotplug) → `consumeIfDefineActive` (si el modal de
|
||||
rebinding está activo, **engulle todo**) → `SDL_EVENT_QUIT` → ratón → botón MENU
|
||||
del mando → reenvío al `ServiceMenu` si está abierto → teclas de función:
|
||||
|
||||
| Tecla | Acción |
|
||||
|---|---|
|
||||
| F1 / F2 | reducir / aumentar tamaño de ventana |
|
||||
| F3 | fullscreen |
|
||||
| F4 | VSync |
|
||||
| F5 | antialias geométrico |
|
||||
| F6 | post-procesado (bloom/flicker/fondo) |
|
||||
| F7 | idioma ca ↔ en (hot-swap de `Locale`) |
|
||||
| F11 | debug overlay (gestionado en el Director, no en GlobalEvents) |
|
||||
| F12 | menú de servicio |
|
||||
| ESC | doble pulsación para salir (la 1ª muestra un toast de confirmación) |
|
||||
|
||||
3. **Singletons compartidos.** `Input`, `Audio`, `Locale`, `Notifier`,
|
||||
`ServiceMenu`, `DefineInputs` se acceden globalmente vía `::get()`. Muchos
|
||||
comprueban `nullptr` para degradar con elegancia (p. ej. el hotplug notifica
|
||||
solo si `Notifier::get() != nullptr`).
|
||||
|
||||
4. **Paso por referencia.** Las escenas reciben `SDLManager&` y `SceneContext&`; el
|
||||
render se propaga como `Rendering::Renderer*`. Los sistemas de juego reciben un
|
||||
struct `Context` con punteros a los pools (ver [§10](#10-lógica-del-juego)).
|
||||
|
||||
**Overlays de sistema** (todos singletons, todos por encima de la escena):
|
||||
|
||||
- **[Notifier](source/core/system/notifier.hpp)** — toasts deslizantes centrados
|
||||
(`notifyInfo/Warn/Exit`), con máquina de animación HIDDEN/ENTERING/HOLDING/EXITING.
|
||||
- **[ServiceMenu](source/core/system/service_menu.hpp)** — menú de configuración
|
||||
(F12) con pila de páginas (vídeo, audio, controles, sistema...).
|
||||
- **[DebugOverlay](source/core/system/debug_overlay.hpp)** — HUD de FPS/VSync (F11).
|
||||
- **[Relaunch](source/core/system/relaunch.hpp)** — reinicio en caliente vía
|
||||
`execv` (lo solicita el ServiceMenu, lo ejecuta `SDL_AppQuit`).
|
||||
|
||||
**Lo que NO existe** (verificado): no hay event bus genérico, ni cola de mensajes
|
||||
desacoplada, ni un FSM genérico reutilizable fuera de las máquinas de estado
|
||||
concretas de cada escena/sistema, ni un ECS.
|
||||
|
||||
---
|
||||
|
||||
## 10. Lógica del juego
|
||||
|
||||
Toda la partida vive en [GameScene](source/game/scenes/game_scene.hpp). Es la clase
|
||||
más grande del juego y actúa como orquestador. Posee:
|
||||
|
||||
- El mundo físico [Physics::PhysicsWorld](source/core/physics/physics_world.hpp)
|
||||
(integración cinemática + colisiones físicas).
|
||||
- Pools de tamaño **fijo**: `std::array<Ship, 2>`,
|
||||
`std::array<Enemy, MAX_ORNIS>` (15), `std::array<Bullet, MAX_BULLETS_TOTAL>` (6:
|
||||
P1=[0,1,2], P2=[3,4,5]).
|
||||
- Estado de partida: vidas, score y *death timers* por jugador, máquina de
|
||||
game over (`GameOverState`: `NONE/CONTINUE/GAME_OVER`), continues usados.
|
||||
- El stage system, los efectos visuales, y los `DemoPilot` (uno por nave).
|
||||
|
||||
### 10.1 Orquestación por frame
|
||||
|
||||
[GameScene::update()](source/game/scenes/game_scene.cpp) es un orquestador delgado;
|
||||
cada paso es una función privada (descompuesto para reducir complejidad cognitiva):
|
||||
|
||||
```cpp
|
||||
void GameScene::update(float dt) {
|
||||
if (ServiceMenu abierto) return; // pausa global (draw sí sigue)
|
||||
stepPhysics(dt);
|
||||
if (mode == DEMO) { if (stepDemo(dt)) return; }
|
||||
else if (game_over_state_ == NONE) { stepShootingInput(); stepMidGameJoin(); }
|
||||
if (stepContinueScreen(dt)) return;
|
||||
if (stepGameOver(dt)) return;
|
||||
stepDeathSequence(dt);
|
||||
stepStageStateMachine(dt);
|
||||
}
|
||||
```
|
||||
|
||||
El corazón del gameplay es
|
||||
[stepStageStateMachine](source/game/scenes/game_scene.hpp#L166), que despacha según
|
||||
el estado del stage; en `PLAYING`,
|
||||
[runStagePlaying](source/game/scenes/game_scene.hpp#L169) ejecuta: WaveRunner
|
||||
(spawns) → IA de cada enemigo → control de naves
|
||||
([updateShipsControl](source/game/scenes/game_scene.cpp), que en demo usa
|
||||
`applyMovement` con el control del pilot y fuera de demo usa `processInput`) →
|
||||
detección de colisiones ([runCollisionDetections](source/game/scenes/game_scene.hpp#L176)).
|
||||
|
||||
`draw()` despacha de forma análoga según `GameOverState` y el estado del stage, y
|
||||
siempre pinta la cortinilla al final.
|
||||
|
||||
### 10.2 Entidades
|
||||
|
||||
Las tres heredan de `Entities::Entity` ([entity.hpp](source/core/entities/entity.hpp)):
|
||||
|
||||
- **[Ship](source/game/entities/ship.hpp)** — nave del jugador. `processInput()`
|
||||
(humano) y `applyMovement()` (usado por la IA demo). Estados: activa,
|
||||
invulnerable (parpadeo tras spawn), herida (`hurt`). Al morir genera debris con
|
||||
la inercia heredada.
|
||||
- **[Enemy](source/game/entities/enemy.hpp)** — 5 tipos (`EnemyType`: `PENTAGON`,
|
||||
`SQUARE`, `PINWHEEL`, `STAR`, `ORB`). Toda su config (físicas, IA, animación,
|
||||
eventos) viene del **YAML** vía [EnemyRegistry](source/game/entities/enemy_registry.hpp).
|
||||
Tiene salud (la mayoría HP=1; `ORB` HP=10) y estado *wounded* (parpadeo).
|
||||
- **[Bullet](source/game/entities/bullet.hpp)** — con `owner_id` (0=P1, 1=P2,
|
||||
≥16=enemigo) y `prev_position` para colisión *swept* (la bala que cruza un enemigo
|
||||
entre dos frames). Config en [BulletRegistry](source/game/entities/bullet_registry.hpp).
|
||||
|
||||
### 10.3 IA de enemigos: declarativa
|
||||
|
||||
Los enemigos **no** tienen comportamiento hardcoded. El YAML describe:
|
||||
|
||||
- Una **primitiva de movimiento** (`MovementType` en
|
||||
[enemy_ai.hpp](source/game/entities/enemy_ai.hpp)): `ZIGZAG`, `TRACKING`,
|
||||
`RECTILINEAR_PROXIMITY`, `WANDER`, `CHASE`, `FLEE`.
|
||||
- **Acciones de tick** periódicas (p. ej. `SHOOT`).
|
||||
- **Eventos** (`on_hit`, `on_no_health`, `on_hurt_end`, `on_destroy`) con acciones
|
||||
(`APPLY_IMPULSE`, `DECREASE_HEALTH`, `CREATE_DEBRIS`, `ADD_SCORE`, `FLASH`,
|
||||
`FIRE_BULLET`, `DESTROY`, ...).
|
||||
|
||||
Dos sistemas los ejecutan:
|
||||
|
||||
- **[EnemyAiSystem](source/game/systems/enemy_ai_system.hpp)** — `move()` aplica la
|
||||
primitiva de movimiento; `tick()` añade las acciones periódicas. Helper
|
||||
`findNearestShipPosition()` para las primitivas que buscan al jugador.
|
||||
- **[EnemyEventDispatcher](source/game/systems/enemy_event_dispatcher.hpp)** —
|
||||
ejecuta las acciones declarativas cuando se dispara un evento.
|
||||
|
||||
### 10.4 Colisiones
|
||||
|
||||
[CollisionSystem](source/game/systems/collision_system.hpp) recibe un struct
|
||||
`Context` (punteros a ships/enemies/bullets, managers de efectos, timers, scores,
|
||||
vidas y un callback `on_player_hit`) que GameScene construye en
|
||||
[buildCollisionContext](source/game/scenes/game_scene.hpp#L174). Detecta:
|
||||
bala↔enemigo, nave↔enemigo, bala↔jugador (fuego amigo / autodisparo), bala
|
||||
enemiga↔nave, y balas fuera del área. Reglas observadas: el primer impacto deja al
|
||||
enemigo *wounded*; el segundo lo destruye y suma score. La nave entra en `hurt` al
|
||||
primer toque y muere al segundo durante ese estado.
|
||||
|
||||
### 10.5 Stages y oleadas
|
||||
|
||||
- **[StageManager](source/game/stage_system/stage_manager.hpp)** — FSM del stage
|
||||
(`EstatStage`): `INIT_HUD` (anima el HUD, 3 s) → `LEVEL_START` ("ENEMY INCOMING",
|
||||
3 s, arranca `game.ogg`) → `PLAYING` → `LEVEL_COMPLETED` ("GOOD JOB COMMANDER!",
|
||||
3 s) → siguiente stage. `initDemo(stage_id)` arranca directamente en `PLAYING`
|
||||
para el attract mode.
|
||||
- **[WaveRunner](source/game/stage_system/wave_runner.hpp)** — emite los enemigos de
|
||||
cada oleada según `spawn_interval` y avanza cuando se cumple `next` (`all_dead`,
|
||||
`timeout`, o ambos).
|
||||
- **[StageConfig](source/game/stage_system/stage_config.hpp)** /
|
||||
[StageLoader](source/game/stage_system/stage_loader.hpp) — modelo y carga del
|
||||
YAML de stages.
|
||||
|
||||
### 10.6 Dos capas de colisión: física vs gameplay
|
||||
|
||||
Conviene no confundirlas, porque conviven:
|
||||
|
||||
**1. Física** — [PhysicsWorld](source/core/physics/physics_world.hpp) /
|
||||
[physics_world.cpp](source/core/physics/physics_world.cpp). Es un mundo 2D
|
||||
minimalista de arcade. Cada frame, `update(dt)` hace tres pasos:
|
||||
|
||||
1. **Integración** semi-implícita de Euler con damping exponencial
|
||||
(`v += (F·invMass)·dt; v *= exp(-damping·dt); x += v·dt`) sobre cada
|
||||
[RigidBody](source/core/physics/rigid_body.hpp) no estático. Un cuerpo con
|
||||
`mass=0` (`inverse_mass=0`) es estático (masa infinita).
|
||||
2. **Rebote contra los bordes** del `PLAYAREA` (`resolveBoundsCollisions`): reposiciona
|
||||
el cuerpo dentro del rect y refleja la componente normal de la velocidad por su
|
||||
`restitution`. Antes de reflejar, invoca un `BoundsHitCallback` opcional con la
|
||||
velocidad de impacto entrante (lo usa GameScene para los efectos de borde).
|
||||
3. **Colisiones cuerpo-cuerpo** (`resolveBodyCollisions`): broadphase trivial
|
||||
**O(n²)** (suficiente para ~23 cuerpos), círculo-círculo, con corrección posicional
|
||||
de penetración + **impulso elástico** `j = -(1+e)(v_rel·n) / (1/mₐ + 1/m_b)`
|
||||
(referencia Box2D / Chris Hecker, en `resolveBodyPair`). Los cuerpos con `radius=0`
|
||||
(las balas, cinemáticas puras) **no** participan aquí.
|
||||
|
||||
Los `RigidBody` los poseen las entidades; el mundo solo guarda punteros no-owning
|
||||
(`addBody`/`removeBody`).
|
||||
|
||||
**2. Gameplay** — [collision_system.cpp](source/game/systems/collision_system.cpp)
|
||||
(ver [§10.4](#104-colisiones)), que decide *qué pasa* (daño, score, muerte). Usa los
|
||||
helpers de [collision.hpp](source/core/physics/collision.hpp): `checkCollision`
|
||||
(círculo-círculo discreto, distancia al cuadrado sin `sqrt`) y `checkCollisionSwept`
|
||||
(segment-círculo, para que una bala rápida no atraviese un enemigo entre frames —
|
||||
*anti-tunneling*). Estos checks usan el `collision_radius` de la **entidad**
|
||||
(con amplificador opcional de hitbox), no el `radius` del body.
|
||||
|
||||
En resumen: la **física** mueve y rebota los cuerpos; el **gameplay** detecta los
|
||||
contactos relevantes para las reglas. Una bala no rebota físicamente (radius 0) pero sí
|
||||
provoca daño vía el check *swept*.
|
||||
|
||||
---
|
||||
|
||||
## 11. IA del modo demo (attract)
|
||||
|
||||
El attract mode es una partida que se juega sola para atraer al jugador. Se activa
|
||||
desde [TitleScene](source/game/scenes/title_scene.hpp) cuando el `idle_timer_` en el
|
||||
estado `MAIN` supera el umbral de inactividad, y desde
|
||||
[GameScene](source/game/scenes/game_scene.hpp) cuando `match_config_.mode == DEMO`.
|
||||
|
||||
La IA vive en [DemoPilot](source/game/systems/demo_pilot.hpp) /
|
||||
[demo_pilot.cpp](source/game/systems/demo_pilot.cpp). Su diseño es explícito en la
|
||||
cabecera: busca **parecer humano, no ser óptimo**. Características clave:
|
||||
|
||||
- **Solo lectura**: `DemoPilot::compute(ship, enemies, bullets, play_area, dt)`
|
||||
devuelve un `Control{left,right,thrust,shoot}`. No lee `Input` ni muta entidades;
|
||||
GameScene aplica el resultado vía `Ship::applyMovement` + `fireBullet`.
|
||||
- **Escenarios curados**: hay 4 (`SCENARIOS` en
|
||||
[demo_pilot.hpp:36-42](source/game/systems/demo_pilot.hpp#L36-L42)): stages
|
||||
`{5,8,6,10}` con 1 o 2 naves IA. El `SceneContext` recuerda el índice y rota al
|
||||
siguiente en cada entrada al demo.
|
||||
|
||||
**Lógica de decisión por prioridad** (verificado en `demo_pilot.cpp`, con sus
|
||||
constantes):
|
||||
|
||||
1. **Esquiva de bala** — si una bala enemiga entrante está dentro de
|
||||
`DODGE_SCAN_RADIUS = 190 px` y viene hacia la nave (`DODGE_HEADING_MIN = 0.25`),
|
||||
maniobra perpendicular a la bala con sesgo al centro (`WALL_BIAS = 0.6`); no
|
||||
dispara mientras esquiva.
|
||||
2. **Sin enemigos** — deriva tranquila (giro lento).
|
||||
3. **Peligro cercano** — si el objetivo está a menos de `DANGER_RADIUS = 95 px`, se
|
||||
aleja con sesgo al centro.
|
||||
4. **Combate** — apuntado con *lead* (`LEAD_TIME = 0.30 s`) más un error humano
|
||||
(`AIM_JITTER_MAX = 0.10 rad`); dispara si el error es menor que
|
||||
`FIRE_TOLERANCE = 0.18 rad` y el cooldown (`FIRE_COOLDOWN = 0.32 s`) lo permite;
|
||||
se acerca si está más lejos que `APPROACH_RADIUS = 250 px`.
|
||||
|
||||
Temporización "humana": reevalúa el objetivo cada `RETARGET_INTERVAL = 0.15 s` y usa
|
||||
una zona muerta de rotación (`ROTATE_DEADZONE = 0.05 rad`) para no oscilar. La demo
|
||||
se rompe con cualquier input (vuelve a TITLE) o por timeout/muerte (vuelve a LOGO),
|
||||
gestionado en [stepDemo](source/game/scenes/game_scene.hpp#L157).
|
||||
|
||||
---
|
||||
|
||||
## 12. Efectos visuales
|
||||
|
||||
Viven en [game/effects/](source/game/effects/) y son managers con pools:
|
||||
|
||||
- **[DebrisManager](source/game/effects/debris_manager.hpp)** — rompe una shape en
|
||||
fragmentos que vuelan radialmente, heredando inercia del cuerpo y, opcionalmente,
|
||||
el impulso de la bala que causó la muerte. Notifica al `Border` (bump) y al
|
||||
`Playfield` (ripple). Lo usan muerte de nave/enemigo, balas fuera de área y las
|
||||
explosiones del logo.
|
||||
- **[FireworkManager](source/game/effects/firework_manager.hpp)** — bursts de fuegos
|
||||
artificiales.
|
||||
- **[FloatingScoreManager](source/game/effects/floating_score_manager.hpp)** —
|
||||
números de puntuación flotantes ("+150").
|
||||
- **[TrailManager](source/game/effects/trail_manager.hpp)** — estela tras las naves.
|
||||
|
||||
---
|
||||
|
||||
## 13. Configuración, constantes y convenciones
|
||||
|
||||
**Configuración:**
|
||||
|
||||
- **[EngineConfig](source/core/config/engine_config.hpp)** — struct POD con
|
||||
ventana, rendering, audio, bindings de jugadores, locale, console. Es la config
|
||||
persistente (`config.yaml`), gestionada por
|
||||
[config_yaml](source/game/config_yaml.hpp) (`ConfigYaml::engine_config`,
|
||||
`loadFromFile`/`saveToFile`).
|
||||
- **[PostFxConfig](source/core/config/postfx_config.hpp)** — carga los `PostFxParams`
|
||||
(bloom/flicker/fondo) desde YAML.
|
||||
- **[GameConfig::MatchConfig](source/core/system/game_config.hpp)** — config no
|
||||
persistente de la partida (jugadores activos, modo NORMAL/DEMO).
|
||||
|
||||
**Constantes y tipos:**
|
||||
|
||||
- **[core/types.hpp](source/core/types.hpp)** — `Vec2` / `Vec3` (agregados con
|
||||
operadores y helpers como `length()`, `normalized()`, `dot()`, `cross()`).
|
||||
- **[core/defaults/](source/core/defaults/)** — un fichero por dominio
|
||||
(`window.hpp`, `rendering.hpp`, `audio.hpp`, `entities.hpp`, `notifier.hpp`...)
|
||||
con todas las constantes por defecto. `game/constants.hpp` reexporta varias como
|
||||
alias (`MAX_ORNIS`, `MAX_BULLETS`, `PI`) y añade helpers de área de juego.
|
||||
|
||||
**Convenciones de código** (de `.clang-tidy`, confirmadas en memoria de proyecto):
|
||||
|
||||
- Métodos en `camelBack`, tipos en `CamelCase`, constantes en `UPPER_CASE`.
|
||||
- Comentarios mayormente en **catalán** (algunos en castellano); el código y los
|
||||
identificadores mezclan catalán/castellano/inglés.
|
||||
- Patrón recurrente: **singletons** con `init/get/destroy` y comprobación de
|
||||
`nullptr` para degradación elegante.
|
||||
- Patrón recurrente: descomposición de funciones grandes (`update`/`draw`) en
|
||||
sub-pasos privados (`stepX`/`runX`/`drawXState`) para mantener baja la complejidad
|
||||
cognitiva.
|
||||
- Análisis estático (cppcheck/clang-tidy) corre vía git hooks
|
||||
([.githooks/](.githooks/)); la política es **arreglar la causa**, no suprimir el
|
||||
diagnóstico.
|
||||
|
||||
---
|
||||
|
||||
## 14. Guía de navegación
|
||||
|
||||
| Si quieres tocar… | Mira… |
|
||||
|---|---|
|
||||
| El arranque, orden de init, o el bucle de frame | [director.cpp](source/core/system/director.cpp) (`Director::iterate` / `handleEvent`) |
|
||||
| Las callbacks de SDL | [main.cpp](source/main.cpp) |
|
||||
| Añadir/cambiar una escena o una transición | [scene.hpp](source/core/system/scene.hpp), [scene_context.hpp](source/core/system/scene_context.hpp), `Director::buildScene` |
|
||||
| Cómo se dibuja una línea / el frame de render | [line_renderer.cpp](source/core/rendering/line_renderer.cpp) → [gpu_frame_renderer.cpp](source/core/rendering/gpu/gpu_frame_renderer.cpp) |
|
||||
| Bloom / flicker / fondo (post-proceso) | [gpu_postfx_pipeline](source/core/rendering/gpu/gpu_postfx_pipeline.hpp), [gpu_bloom_pipeline](source/core/rendering/gpu/gpu_bloom_pipeline.hpp), shaders en [shaders/](shaders/) |
|
||||
| Crear/editar una figura vectorial | `data/shapes/**/*.shp` + [shape_loader.hpp](source/core/graphics/shape_loader.hpp) |
|
||||
| El texto en pantalla | [vector_text.hpp](source/core/graphics/vector_text.hpp) |
|
||||
| Eventos globales (teclas F, ESC, hotplug) | [global_events.cpp](source/core/system/global_events.cpp) |
|
||||
| Controles, bindings, rebinding | [input.cpp](source/core/input/input.cpp), [define_inputs.cpp](source/core/input/define_inputs.cpp) |
|
||||
| Reproducir música/efectos | [audio.hpp](source/core/audio/audio.hpp), [audio_adapter.hpp](source/core/audio/audio_adapter.hpp) |
|
||||
| Cómo se cargan los recursos / el pack | [resource_loader.cpp](source/core/resources/resource_loader.cpp), [resource_pack.cpp](source/core/resources/resource_pack.cpp) |
|
||||
| Reglas de la partida, vidas, game over | [game_scene.cpp](source/game/scenes/game_scene.cpp) |
|
||||
| Comportamiento de un enemigo | su YAML en `data/entities/<tipo>/` + [enemy_ai_system.cpp](source/game/systems/enemy_ai_system.cpp) |
|
||||
| Definir oleadas / dificultad de un nivel | [data/stages/stages.yaml](data/stages/stages.yaml) + [stage_manager.cpp](source/game/stage_system/stage_manager.cpp) |
|
||||
| Colisiones | [collision_system.cpp](source/game/systems/collision_system.cpp) |
|
||||
| La IA del modo demo | [demo_pilot.cpp](source/game/systems/demo_pilot.cpp) |
|
||||
| Explosiones / partículas | [debris_manager.cpp](source/game/effects/debris_manager.cpp) |
|
||||
| El menú de servicio (F12) | [service_menu.cpp](source/core/system/service_menu.cpp) |
|
||||
| Textos traducibles | `data/locale/*.yaml` + [locale.cpp](source/core/locale/locale.cpp) |
|
||||
| Constantes por defecto | [core/defaults/](source/core/defaults/) |
|
||||
|
||||
---
|
||||
|
||||
### Notas de honestidad sobre la cobertura
|
||||
|
||||
- Todas las secciones se verificaron leyendo directamente los ficheros y firmas
|
||||
citados, incluyendo el **pipeline de compilación de shaders**
|
||||
([§5.5](#55-shaders-fuentes-compilación-y-selección): `CMakeLists.txt` +
|
||||
`tools/shaders/compile_spirv.cmake` + `shader_factory.hpp`) y el interior de la
|
||||
**física** ([§10.6](#106-dos-capas-de-colisión-física-vs-gameplay):
|
||||
`physics_world.cpp` + `collision.hpp` + `rigid_body.hpp`).
|
||||
- Lo que **no** se ha trazado a fondo y queda como lectura directa del código si hace
|
||||
falta: los detalles finos de animación de cada overlay (curvas de easing del
|
||||
`Notifier`/`ServiceMenu`) y la coreografía interna completa de `LogoScene` y
|
||||
`TitleScene` (más allá de sus estados). Son descriptivos, no estructurales.
|
||||
</content>
|
||||
</invoke>
|
||||
@@ -84,9 +84,18 @@ else
|
||||
endif
|
||||
|
||||
.PHONY: all debug release _windows-release _macos-release _linux-release \
|
||||
run run-debug clean rebuild show-version pack \
|
||||
run run-debug clean rebuild show-version pack controllerdb \
|
||||
format format-check tidy tidy-fix cppcheck hooks-install help
|
||||
|
||||
# Còpia del gamecontrollerdb.txt (si existeix) al directori de build, perquè
|
||||
# director.cpp el resolgui via resource_base = directori de l'executable.
|
||||
# Silenciós si el fitxer no existeix (l'usuari encara no ha fet `make controllerdb`).
|
||||
ifeq ($(OS),Windows_NT)
|
||||
CP_CONTROLLERDB = @powershell -Command "if (Test-Path 'gamecontrollerdb.txt') { Copy-Item 'gamecontrollerdb.txt' -Destination '$(BUILDDIR)' -Force }"
|
||||
else
|
||||
CP_CONTROLLERDB = @if [ -f gamecontrollerdb.txt ]; then cp gamecontrollerdb.txt $(BUILDDIR)/; fi
|
||||
endif
|
||||
|
||||
# ==============================================================================
|
||||
# COMPILACIÓ
|
||||
# ==============================================================================
|
||||
@@ -98,10 +107,12 @@ endif
|
||||
all:
|
||||
@cmake -S . -B $(BUILDDIR) $(CMAKE_GEN) -DCMAKE_BUILD_TYPE=Release $(CMAKE_DEFS)
|
||||
@cmake --build $(BUILDDIR) -j$(JOBS)
|
||||
$(CP_CONTROLLERDB)
|
||||
|
||||
debug:
|
||||
@cmake -S . -B $(BUILDDIR) $(CMAKE_GEN) -DCMAKE_BUILD_TYPE=Debug $(CMAKE_DEFS)
|
||||
@cmake --build $(BUILDDIR) -j$(JOBS)
|
||||
$(CP_CONTROLLERDB)
|
||||
|
||||
run: all
|
||||
@./$(BUILDDIR)/$(PROJECT)
|
||||
@@ -138,6 +149,7 @@ _linux-release:
|
||||
|
||||
# Còpia de fitxers
|
||||
cp $(BUILDDIR)/resources.pack "$(RELEASE_FOLDER)"
|
||||
cp gamecontrollerdb.txt "$(RELEASE_FOLDER)"
|
||||
cp README.md "$(RELEASE_FOLDER)"
|
||||
@[ -f LICENSE ] && cp LICENSE "$(RELEASE_FOLDER)" || true
|
||||
cp "$(TARGET_FILE)" "$(RELEASE_FILE)"
|
||||
@@ -166,6 +178,7 @@ _windows-release:
|
||||
@powershell -Command "if (-not (Test-Path '$(RELEASE_FOLDER)')) {New-Item '$(RELEASE_FOLDER)' -ItemType Directory}"
|
||||
|
||||
@powershell -Command "Copy-Item -Path '$(BUILDDIR)/resources.pack' -Destination '$(RELEASE_FOLDER)'"
|
||||
@powershell -Command "Copy-Item 'gamecontrollerdb.txt' -Destination '$(RELEASE_FOLDER)'"
|
||||
@powershell -Command "if (Test-Path 'LICENSE') { Copy-Item 'LICENSE' -Destination '$(RELEASE_FOLDER)' }"
|
||||
@powershell -Command "Copy-Item 'README.md' -Destination '$(RELEASE_FOLDER)'"
|
||||
@powershell -Command "if (Test-Path 'release\windows\dll') { Copy-Item 'release\windows\dll\*.dll' -Destination '$(RELEASE_FOLDER)' }"
|
||||
@@ -206,6 +219,7 @@ _macos-release:
|
||||
|
||||
# Còpia de recursos i metadades del bundle
|
||||
cp $(BUILDDIR)/arm/resources.pack "$(RELEASE_FOLDER)/$(APP_NAME).app/Contents/Resources"
|
||||
cp gamecontrollerdb.txt "$(RELEASE_FOLDER)/$(APP_NAME).app/Contents/Resources"
|
||||
cp -R release/macos/frameworks/SDL3.xcframework/macos-arm64_x86_64/SDL3.framework "$(RELEASE_FOLDER)/$(APP_NAME).app/Contents/Frameworks"
|
||||
cp release/icons/icon.icns "$(RELEASE_FOLDER)/$(APP_NAME).app/Contents/Resources"
|
||||
cp release/macos/Info.plist "$(RELEASE_FOLDER)/$(APP_NAME).app/Contents"
|
||||
@@ -274,6 +288,19 @@ pack:
|
||||
@cmake --build $(BUILDDIR) --target pack_resources
|
||||
@./$(BUILDDIR)/pack_resources data $(BUILDDIR)/resources.pack
|
||||
|
||||
# ==============================================================================
|
||||
# DESCÀRREGA DE GAMECONTROLLERDB
|
||||
# ==============================================================================
|
||||
# Descarrega l'última versió de gamecontrollerdb.txt (mappings de gamepads
|
||||
# mantinguts per la comunitat) a l'arrel del projecte. SDL el carrega via
|
||||
# filesystem real (no dins resources.pack) i s'ha de copiar al costat del binari
|
||||
# en cada build (gestionat per CP_CONTROLLERDB a `all`/`debug` i pels release targets).
|
||||
controllerdb:
|
||||
@echo "Descargando gamecontrollerdb.txt..."
|
||||
curl -fsSL https://raw.githubusercontent.com/mdqinc/SDL_GameControllerDB/master/gamecontrollerdb.txt \
|
||||
-o gamecontrollerdb.txt
|
||||
@echo "gamecontrollerdb.txt actualizado"
|
||||
|
||||
# ==============================================================================
|
||||
# CODE QUALITY (delegats a cmake)
|
||||
# ==============================================================================
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
name: bullet
|
||||
|
||||
# Shape de la bala. El bounding_radius del .shp dóna el hitbox base (~3 px);
|
||||
# scale el modula visualment i pel hitbox.
|
||||
shape:
|
||||
path: bullet/basic.shp
|
||||
scale: 1.0
|
||||
collision_factor: 1.0
|
||||
|
||||
# Cinemàtica pura: la bala no col·lisiona físicament al PhysicsWorld
|
||||
# (body_.radius = 0 al spawn), però sí participa al gameplay via
|
||||
# checkCollisionSwept. La mass i l'impact_momentum_factor es fan servir
|
||||
# només per calcular l'impuls que rep l'enemic en impactar.
|
||||
physics:
|
||||
mass: 0.5
|
||||
restitution: 0.0 # irrelevant (no rebota)
|
||||
linear_damping: 0.0 # movement rectilini uniforme
|
||||
angular_damping: 0.0
|
||||
impact_momentum_factor: 3.0 # factor de transferència de moment bala→enemic
|
||||
|
||||
colors:
|
||||
normal: [155, 255, 175] # verd laser
|
||||
@@ -0,0 +1,21 @@
|
||||
name: bullet_double
|
||||
|
||||
# Variant de bala "anular" (dos cercles concèntrics, aspecte d'aura de plasma).
|
||||
# Pensada per a contra-atacs d'enemic (ex: orb dispara una bullet_double al
|
||||
# jugador quan rep un impacte). Mateixa física que la bala bàsica del player;
|
||||
# canvien la forma (cercle doble) i el color per llegir-se com a tret enemic
|
||||
# distintiu (groc verdós vs. el verd laser del player o el roig de bullet_long).
|
||||
shape:
|
||||
path: bullet/double.shp
|
||||
scale: 1.5
|
||||
collision_factor: 1.0
|
||||
|
||||
physics:
|
||||
mass: 0.5
|
||||
restitution: 0.0
|
||||
linear_damping: 0.0
|
||||
angular_damping: 0.0
|
||||
impact_momentum_factor: 4.0
|
||||
|
||||
colors:
|
||||
normal: [200, 255, 80] # groc verdós (chartreuse) — contra-atac de l'orb
|
||||
@@ -0,0 +1,19 @@
|
||||
name: bullet_long
|
||||
|
||||
# Variant de bala més llarga, pensada per a bales d'enemic: més visible per al
|
||||
# jugador i amb prou marge per reaccionar. La velocitat NO viu aquí: es passa
|
||||
# a Bullet::fire() i la decideix qui dispara (l'AiTickAction).
|
||||
shape:
|
||||
path: bullet/long.shp
|
||||
scale: 1.0
|
||||
collision_factor: 0.5
|
||||
|
||||
physics:
|
||||
mass: 0.5
|
||||
restitution: 0.0
|
||||
linear_damping: 0.0
|
||||
angular_damping: 0.0
|
||||
impact_momentum_factor: 3.0
|
||||
|
||||
colors:
|
||||
normal: [255, 100, 100] # roig clar — diferencia visualment del verd laser del player
|
||||
@@ -0,0 +1,86 @@
|
||||
name: orb
|
||||
ai_type: orb # Validat contra el directori; mapeja a EnemyType::ORB.
|
||||
|
||||
# Shape circular pròpia (anell exterior + anell interior + 6 radis + nucli),
|
||||
# pensada per llegir-se com a "reactor / orb" amb més detall que els enemics
|
||||
# petits.
|
||||
shape:
|
||||
path: enemy/orb.shp
|
||||
scale: 1.0
|
||||
collision_factor: 1.0
|
||||
|
||||
physics:
|
||||
mass: 50.0 # Molt pesat: una bala el frena un poc però no el "envia a passejar".
|
||||
speed: 50.0 # Avança decidit cap al ship (no és lent passiu, és amenaça constant).
|
||||
rotation_delta_min: 0.3
|
||||
rotation_delta_max: 1.5
|
||||
restitution: 1.0
|
||||
linear_damping: 0.0
|
||||
angular_damping: 0.0
|
||||
|
||||
ai:
|
||||
# Persecució contínua del ship més proper. chase_strength alt (1.0 = ~1s
|
||||
# per realinear-se) perquè, encara que una bala l'empentja lateralment,
|
||||
# ràpidament torna a posar la seua proa cap al jugador.
|
||||
movement:
|
||||
type: chase
|
||||
chase_strength: 1.0
|
||||
|
||||
animation:
|
||||
pulse:
|
||||
trigger_prob_per_second: 0.01
|
||||
duration_min: 1.0
|
||||
duration_max: 3.0
|
||||
amplitude_min: 0.08
|
||||
amplitude_max: 0.20
|
||||
frequency_min: 1.5
|
||||
frequency_max: 3.0
|
||||
rotation_accel:
|
||||
trigger_prob_per_second: 0.02
|
||||
duration_min: 3.0
|
||||
duration_max: 8.0
|
||||
multiplier_min: 0.3
|
||||
multiplier_max: 4.0
|
||||
|
||||
wounded:
|
||||
duration: 1.5 # Una mica més llarg que els altres (és un boss).
|
||||
blink_hz: 10.0
|
||||
|
||||
spawn:
|
||||
invulnerability_duration: 3.0
|
||||
invulnerability_brightness_start: 0.3
|
||||
invulnerability_brightness_end: 0.7
|
||||
invulnerability_scale_start: 0.0
|
||||
invulnerability_scale_end: 1.0
|
||||
safety_distance: 54.0 # 1.5× del normal (alineat amb scale 1.5).
|
||||
|
||||
colors:
|
||||
normal: [255, 140, 110] # taronja rosat (coral) — distintiu del boss orb.
|
||||
wounded: [255, 220, 60]
|
||||
|
||||
score: 500 # 5x un enemic normal: aguanta 10x més.
|
||||
|
||||
# Estrenant el sistema HP: 10 unitats. Cada bala fa decrease_health + flash
|
||||
# + create_debris_partial (xip a 0.3x) + create_fireworks_small (espurna).
|
||||
# Al 10è hit (HP=0), on_no_health encadena destroy directe — sense passar
|
||||
# per wounded (com Star). 10 HP ja és prou dificultat sense afegir un hit
|
||||
# extra.
|
||||
health: 10
|
||||
|
||||
events:
|
||||
on_hit:
|
||||
- action: fire_bullet # contra-atac: dispara bullet_double dirigida al jugador
|
||||
bullet: bullet_double
|
||||
bullet_speed: 200.0
|
||||
aim_mode: aimed
|
||||
- action: decrease_health # primer: si arriba a 0 dispara on_no_health
|
||||
#- action: flash # feedback visual de damage parcial
|
||||
- action: create_debris_partial # xip a 0.3x mida (sense ser letal)
|
||||
#- action: create_fireworks_small # espurna a cada hit (12 punts, lent)
|
||||
- action: apply_impulse # empenta el cos (skip si will_die)
|
||||
on_no_health:
|
||||
- action: destroy # mort directa, sense wounded
|
||||
on_destroy:
|
||||
- action: add_score
|
||||
- action: create_debris # explosió completa
|
||||
- action: create_fireworks
|
||||
@@ -0,0 +1,72 @@
|
||||
name: pentagon
|
||||
ai_type: pentagon # Validat contra el directori; mapeja a EnemyType::PENTAGON.
|
||||
|
||||
shape:
|
||||
path: enemy/pentagon.shp
|
||||
scale: 1.0 # multiplicador visual + hitbox sobre la mida nativa del .shp
|
||||
collision_factor: 1.0 # ajust opcional del hitbox (default 1.0)
|
||||
|
||||
physics:
|
||||
mass: 5.0
|
||||
speed: 35.0 # px/s (esquivador lent)
|
||||
rotation_delta_min: 0.75 # rad/s — rotació visual mínima
|
||||
rotation_delta_max: 3.75 # rad/s — rotació visual màxima
|
||||
restitution: 1.0 # rebot elàstic perfecte contra parets
|
||||
linear_damping: 0.0 # manté velocitat (sense fricció)
|
||||
angular_damping: 0.0
|
||||
|
||||
behavior:
|
||||
# Pentagon: zigzag esquivador (canvi de direcció probabilístic per segon).
|
||||
angle_change_max: 1.0 # rad — magnitud del canvi de direcció
|
||||
zigzag_prob_per_second: 0.8
|
||||
|
||||
animation:
|
||||
pulse: # respiració d'escala aleatòria
|
||||
trigger_prob_per_second: 0.01
|
||||
duration_min: 1.0
|
||||
duration_max: 3.0
|
||||
amplitude_min: 0.08
|
||||
amplitude_max: 0.20
|
||||
frequency_min: 1.5
|
||||
frequency_max: 3.0
|
||||
rotation_accel: # acceleració/desacceleració de rotació visual
|
||||
trigger_prob_per_second: 0.02
|
||||
duration_min: 3.0
|
||||
duration_max: 8.0
|
||||
multiplier_min: 0.3
|
||||
multiplier_max: 4.0
|
||||
|
||||
wounded:
|
||||
duration: 1.0 # segons en estat ferit abans d'explotar
|
||||
blink_hz: 10.0 # parpelleig color normal ↔ wounded
|
||||
|
||||
spawn:
|
||||
invulnerability_duration: 3.0
|
||||
invulnerability_brightness_start: 0.3
|
||||
invulnerability_brightness_end: 0.7
|
||||
invulnerability_scale_start: 0.0
|
||||
invulnerability_scale_end: 1.0
|
||||
safety_distance: 36.0 # px mínim respecte al player al spawn
|
||||
|
||||
colors:
|
||||
normal: [0, 255, 255] # Cyan pur "esquivador"
|
||||
wounded: [255, 220, 60] # Daurat (parpelleig al rebre impacte)
|
||||
|
||||
score: 100
|
||||
|
||||
events:
|
||||
# HP=1 (default): decrement → on_no_health → set_hurt → wounded → mort.
|
||||
# decrease_health primer perquè si la mort cau aquí (segon hit durant wounded),
|
||||
# el dispatcher salta la resta del chain (incloent apply_impulse) sobre el
|
||||
# cos ja destruït.
|
||||
on_hit:
|
||||
- action: decrease_health
|
||||
- action: apply_impulse
|
||||
on_no_health:
|
||||
- action: set_hurt
|
||||
on_hurt_end:
|
||||
- action: destroy
|
||||
on_destroy:
|
||||
- action: add_score
|
||||
- action: create_debris
|
||||
- action: create_fireworks
|
||||
@@ -0,0 +1,69 @@
|
||||
name: pinwheel
|
||||
ai_type: pinwheel # Validat contra el directori; mapeja a EnemyType::PINWHEEL.
|
||||
|
||||
shape:
|
||||
path: enemy/pinwheel.shp
|
||||
scale: 1.0 # multiplicador visual + hitbox sobre la mida nativa del .shp
|
||||
collision_factor: 1.0 # ajust opcional del hitbox (default 1.0)
|
||||
|
||||
physics:
|
||||
mass: 4.0 # Més lleuger — àgil
|
||||
speed: 50.0 # px/s (el més ràpid)
|
||||
rotation_delta_min: 3.0 # rad/s — rotació base elevada
|
||||
rotation_delta_max: 6.0
|
||||
restitution: 1.0
|
||||
linear_damping: 0.0
|
||||
angular_damping: 0.0
|
||||
|
||||
behavior:
|
||||
# Pinwheel: movement rectilíniauniforme + boost de rotació visual prop de la nau.
|
||||
rotation_proximity_multiplier: 3.0 # Multiplicador de rotació quan és prop de la nau
|
||||
proximity_distance: 100.0 # Llindar de distància (px)
|
||||
|
||||
animation:
|
||||
pulse:
|
||||
trigger_prob_per_second: 0.01
|
||||
duration_min: 1.0
|
||||
duration_max: 3.0
|
||||
amplitude_min: 0.08
|
||||
amplitude_max: 0.20
|
||||
frequency_min: 1.5
|
||||
frequency_max: 3.0
|
||||
rotation_accel:
|
||||
trigger_prob_per_second: 0.02
|
||||
duration_min: 3.0
|
||||
duration_max: 8.0
|
||||
multiplier_min: 0.3
|
||||
multiplier_max: 4.0
|
||||
|
||||
wounded:
|
||||
duration: 1.0
|
||||
blink_hz: 10.0
|
||||
|
||||
spawn:
|
||||
invulnerability_duration: 3.0
|
||||
invulnerability_brightness_start: 0.3
|
||||
invulnerability_brightness_end: 0.7
|
||||
invulnerability_scale_start: 0.0
|
||||
invulnerability_scale_end: 1.0
|
||||
safety_distance: 36.0
|
||||
|
||||
colors:
|
||||
normal: [255, 0, 255] # Magenta pur "agressiu"
|
||||
wounded: [255, 220, 60]
|
||||
|
||||
score: 200
|
||||
|
||||
events:
|
||||
# HP=1 (default): decrement → on_no_health → set_hurt → wounded → mort.
|
||||
on_hit:
|
||||
- action: decrease_health
|
||||
- action: apply_impulse
|
||||
on_no_health:
|
||||
- action: set_hurt
|
||||
on_hurt_end:
|
||||
- action: destroy
|
||||
on_destroy:
|
||||
- action: add_score
|
||||
- action: create_debris
|
||||
- action: create_fireworks
|
||||
@@ -0,0 +1,49 @@
|
||||
name: player_ship
|
||||
|
||||
# Shape de la nau. Resolt per ShapeLoader (busca a "shapes/<path>").
|
||||
# Nota: el segon jugador rep un override del shape ("ship/wedge.shp") al ctor.
|
||||
# Quan s'introdueixin variants reals de nau, es crearà un YAML separat
|
||||
# per cada model.
|
||||
#
|
||||
# scale: multiplicador visual i de hitbox sobre la mida nativa del .shp (1.0 = mida del fitxer).
|
||||
# collision_factor: ajust opcional del hitbox respecte el cercle circumscrit
|
||||
# automàtic de la shape; tocar només si el feel del hitbox
|
||||
# no quadra amb la silueta visual (default 1.0).
|
||||
shape:
|
||||
path: ship/arrow.shp
|
||||
scale: 1.0
|
||||
collision_factor: 1.0
|
||||
|
||||
physics:
|
||||
mass: 10.0
|
||||
restitution: 0.6
|
||||
linear_damping: 1.5
|
||||
angular_damping: 0.0
|
||||
rotation_speed: 3.14 # rad/s (~180 deg/s, input-driven sense inercia)
|
||||
acceleration: 400.0 # px/s^2 multiplicat per la massa quan THRUST
|
||||
max_velocity: 180.0 # px/s (clamp post-integració per preservar feel arcade)
|
||||
# Factor de transferència del moment lineal de la nau a l'enemic en el
|
||||
# frame exacte que mor per col·lisió (afegit per damunt del rebot natural).
|
||||
death_impact_factor: 0.3
|
||||
|
||||
invulnerability:
|
||||
duration: 3.0 # segons d'invulnerabilitat post-respawn
|
||||
blink_visible: 0.1 # segons visible per cicle de parpelleig
|
||||
blink_invisible: 0.1 # segons invisible per cicle de parpelleig
|
||||
|
||||
hurt:
|
||||
duration: 15.0 # segons en estat "ferit" abans de tornar a normal
|
||||
blink_hz: 10.0 # freqüència parpelleig color normal <-> color hurt
|
||||
|
||||
# Empenta visual: la nau s'escala lleugerament amb la velocitat.
|
||||
# Manté la sensació del Pascal original (0..MAX_VEL → 1.0..~1.5).
|
||||
visual_thrust:
|
||||
push_divisor: 33.33
|
||||
scale_divisor: 12.0
|
||||
|
||||
colors:
|
||||
normal: [255, 255, 255] # blanc neutre
|
||||
hurt: [255, 0, 0] # roig pur (estat ferit)
|
||||
|
||||
weapon:
|
||||
bullet_speed: 700.0 # velocitat escalar de la bullet (px/s)
|
||||
@@ -0,0 +1,70 @@
|
||||
name: square
|
||||
ai_type: square # Validat contra el directori; mapeja a EnemyType::SQUARE.
|
||||
|
||||
shape:
|
||||
path: enemy/square.shp
|
||||
scale: 1.0 # multiplicador visual + hitbox sobre la mida nativa del .shp
|
||||
collision_factor: 1.0 # ajust opcional del hitbox (default 1.0)
|
||||
|
||||
physics:
|
||||
mass: 8.0 # Més pesat — "tanc"
|
||||
speed: 40.0 # px/s (velocitat mitjana)
|
||||
rotation_delta_min: 0.3 # rad/s — rotació lenta
|
||||
rotation_delta_max: 1.5
|
||||
restitution: 1.0
|
||||
linear_damping: 0.0
|
||||
angular_damping: 0.0
|
||||
|
||||
ai:
|
||||
# Square: persecució contínua del ship més proper (steering suau, "tanc lent").
|
||||
movement:
|
||||
type: chase
|
||||
chase_strength: 0.5 # Força/segon de la LERP cap a la direcció ideal (1.0 = ~1s per realinear)
|
||||
|
||||
animation:
|
||||
pulse:
|
||||
trigger_prob_per_second: 0.01
|
||||
duration_min: 1.0
|
||||
duration_max: 3.0
|
||||
amplitude_min: 0.08
|
||||
amplitude_max: 0.20
|
||||
frequency_min: 1.5
|
||||
frequency_max: 3.0
|
||||
rotation_accel:
|
||||
trigger_prob_per_second: 0.02
|
||||
duration_min: 3.0
|
||||
duration_max: 8.0
|
||||
multiplier_min: 0.3
|
||||
multiplier_max: 4.0
|
||||
|
||||
wounded:
|
||||
duration: 1.0
|
||||
blink_hz: 10.0
|
||||
|
||||
spawn:
|
||||
invulnerability_duration: 3.0
|
||||
invulnerability_brightness_start: 0.3
|
||||
invulnerability_brightness_end: 0.7
|
||||
invulnerability_scale_start: 0.0
|
||||
invulnerability_scale_end: 1.0
|
||||
safety_distance: 36.0
|
||||
|
||||
colors:
|
||||
normal: [255, 0, 0] # Roig pur "tanc"
|
||||
wounded: [255, 220, 60]
|
||||
|
||||
score: 150
|
||||
|
||||
events:
|
||||
# HP=1 (default): decrement → on_no_health → set_hurt → wounded → mort.
|
||||
on_hit:
|
||||
- action: decrease_health
|
||||
- action: apply_impulse
|
||||
on_no_health:
|
||||
- action: set_hurt
|
||||
on_hurt_end:
|
||||
- action: destroy
|
||||
on_destroy:
|
||||
- action: add_score
|
||||
- action: create_debris
|
||||
- action: create_fireworks
|
||||
@@ -0,0 +1,77 @@
|
||||
name: star
|
||||
ai_type: star # Validat contra el directori; mapeja a EnemyType::STAR.
|
||||
|
||||
shape:
|
||||
path: enemy/star.shp
|
||||
scale: 0.7 # Lleugerament més petit que els altres enemics per diferenciar visualment.
|
||||
collision_factor: 1.0
|
||||
|
||||
physics:
|
||||
mass: 5.0
|
||||
speed: 35.0 # Mateixos paràmetres que pentagon (esquivador lent).
|
||||
rotation_delta_min: 0.75
|
||||
rotation_delta_max: 3.75
|
||||
restitution: 1.0
|
||||
linear_damping: 0.0
|
||||
angular_damping: 0.0
|
||||
|
||||
ai:
|
||||
# Movement: zigzag esquivador (com Pentagon).
|
||||
movement:
|
||||
type: zigzag
|
||||
angle_change_max: 1.0
|
||||
zigzag_prob_per_second: 0.8
|
||||
# Accions periòdiques: cada ~2.5s dispara una bala apuntada al ship més proper.
|
||||
tick:
|
||||
- action: shoot
|
||||
interval: 2.5
|
||||
aim_mode: aimed # apunta al ship més proper (atan2)
|
||||
jitter_rad: 0.0 # sense soroll: tret perfecte
|
||||
bullet: bullet_long # variant més visible per al jugador
|
||||
bullet_speed: 150.0 # px/s — prou lenta per reaccionar
|
||||
|
||||
animation:
|
||||
pulse:
|
||||
trigger_prob_per_second: 0.01
|
||||
duration_min: 1.0
|
||||
duration_max: 3.0
|
||||
amplitude_min: 0.08
|
||||
amplitude_max: 0.20
|
||||
frequency_min: 1.5
|
||||
frequency_max: 3.0
|
||||
rotation_accel:
|
||||
trigger_prob_per_second: 0.02
|
||||
duration_min: 3.0
|
||||
duration_max: 8.0
|
||||
multiplier_min: 0.3
|
||||
multiplier_max: 4.0
|
||||
|
||||
wounded:
|
||||
duration: 1.0
|
||||
blink_hz: 10.0
|
||||
|
||||
spawn:
|
||||
invulnerability_duration: 3.0
|
||||
invulnerability_brightness_start: 0.3
|
||||
invulnerability_brightness_end: 0.7
|
||||
invulnerability_scale_start: 0.0
|
||||
invulnerability_scale_end: 1.0
|
||||
safety_distance: 36.0
|
||||
|
||||
colors:
|
||||
normal: [255, 255, 0] # Groc estrella
|
||||
wounded: [255, 220, 60]
|
||||
|
||||
score: 100
|
||||
|
||||
events:
|
||||
# STAR: mor al primer impacte, sense passar per wounded.
|
||||
# HP=1 (default): decrement → on_no_health → destroy directe (sense wounded).
|
||||
on_hit:
|
||||
- action: decrease_health
|
||||
on_no_health:
|
||||
- action: destroy
|
||||
on_destroy:
|
||||
- action: add_score
|
||||
- action: create_debris
|
||||
- action: create_fireworks
|
||||
@@ -27,6 +27,9 @@ hud:
|
||||
title:
|
||||
press_start: "PREMEU START PER JUGAR"
|
||||
|
||||
demo:
|
||||
banner: "MODE DEMO - PREMEU START"
|
||||
|
||||
game_screen:
|
||||
game_over: "FI DEL JOC"
|
||||
continue: "CONTINUAR"
|
||||
|
||||
@@ -26,6 +26,9 @@ hud:
|
||||
title:
|
||||
press_start: "PRESS START TO PLAY"
|
||||
|
||||
demo:
|
||||
banner: "DEMO MODE - PRESS START"
|
||||
|
||||
game_screen:
|
||||
game_over: "GAME OVER"
|
||||
continue: "CONTINUE"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# bullet.shp - Projectil (octàgon, radi=3)
|
||||
# bullet/basic.shp - Projectil (octàgon, radi=3)
|
||||
|
||||
name: bullet
|
||||
name: basic
|
||||
scale: 1.0
|
||||
center: 0, 0
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
# bullet/double.shp - Bala anular (dos cercles concèntrics)
|
||||
# © 2026 JailDesigner
|
||||
#
|
||||
# Dos octàgons concèntrics al centre (0,0):
|
||||
# - Exterior: radi 4 (lleugerament més gran que la bala estàndard, radi 3)
|
||||
# - Interior: radi 2 (lleugerament més petit que la bala estàndard)
|
||||
# Aspecte d'anell / aura de plasma. Bounding radius natiu = 4.
|
||||
|
||||
name: double
|
||||
scale: 1.0
|
||||
center: 0, 0
|
||||
|
||||
# Cercle exterior (octàgon, radi 4)
|
||||
polyline: 0,-4 2.83,-2.83 4,0 2.83,2.83 0,4 -2.83,2.83 -4,0 -2.83,-2.83 0,-4
|
||||
|
||||
# Cercle interior (octàgon, radi 2)
|
||||
polyline: 0,-2 1.41,-1.41 2,0 1.41,1.41 0,2 -1.41,1.41 -2,0 -1.41,-1.41 0,-2
|
||||
@@ -0,0 +1,32 @@
|
||||
# bullet/long.shp - Bala allargada vertical (dos mig-octàgons + dos costats)
|
||||
# © 2026 JailDesigner
|
||||
#
|
||||
# Càpsula orientada al llarg de l'eix Y: la bala viatja segons el seu angle
|
||||
# de moviment (angle=0 = Y negatiu), i així s'estira en la direcció de vol.
|
||||
# Es dibuixen només els segments exteriors per evitar veure la unió interna
|
||||
# dels dos cercles; el resultat visual són dos "mig-octàgons" separats per
|
||||
# un petit gap al centre, units pels dos costats verticals.
|
||||
#
|
||||
# Geometria:
|
||||
# Mig-octàgon superior (radi 3) centrat a (0, -3)
|
||||
# Mig-octàgon inferior (radi 3) centrat a (0, 3)
|
||||
# Punt extrem superior: (0, -6)
|
||||
# Punt extrem inferior: (0, 6)
|
||||
# Bounding radius natiu = 6 (extrem vertical a y=±6).
|
||||
# collision_factor al YAML compensa el bounding doble (0.5 → hitbox ≈ 3).
|
||||
|
||||
name: long
|
||||
scale: 1.0
|
||||
center: 0, 0
|
||||
|
||||
# Mig-octàgon superior (5 vèrtexs: del cantó dret cap al punt extrem i a l'esquerre)
|
||||
polyline: 3,-3 2.12,-5.12 0,-6 -2.12,-5.12 -3,-3
|
||||
|
||||
# Mig-octàgon inferior
|
||||
polyline: 3,3 2.12,5.12 0,6 -2.12,5.12 -3,3
|
||||
|
||||
# Costat dret (uneix extrem inferior del mig superior amb extrem superior del mig inferior)
|
||||
polyline: 3,-3 3,3
|
||||
|
||||
# Costat esquerre
|
||||
polyline: -3,-3 -3,3
|
||||
@@ -1,7 +1,7 @@
|
||||
# star.shp - Estrella per a starfield
|
||||
# effect/starfield.shp - Estrella per a starfield
|
||||
# © 2026 JailDesigner
|
||||
|
||||
name: star
|
||||
name: starfield
|
||||
scale: 1.0
|
||||
center: 0, 0
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# title_flash.shp - Sparkle 4-puntes amb costats còncaus (Atari-style)
|
||||
# effect/title_flash.shp - Sparkle 4-puntes amb costats còncaus (Atari-style)
|
||||
# 4 puntes als cardinals (radi 30) i valls còncaus als 45° (corba Bezier
|
||||
# quadràtica amb control point ±8). 5 punts per arc subdividint la corba.
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
# enemy/orb.shp - ORNI enemic gegant (orb circular, doble anell amb radis)
|
||||
# © 2026 JailDesigner
|
||||
#
|
||||
# Forma "reactor / boss circular" — més detall que els enemics petits perquè
|
||||
# es renderitza a escala 1.5x i ha de llegir-se com a amenaça gran.
|
||||
# - Anell exterior: dodecàgon (12 vèrtexs) — aparença circular suau, radi 20.
|
||||
# - Anell interior: hexàgon (6 vèrtexs, rotat 30°) — radi 10.
|
||||
# - 6 radis curts que connecten l'anell interior amb l'exterior.
|
||||
# - Petit "+" central com a nucli.
|
||||
# Bounding radius natiu = 20 (alineat amb la resta d'enemics).
|
||||
|
||||
name: orb
|
||||
scale: 1.0
|
||||
center: 0, 0
|
||||
|
||||
# Anell exterior (dodecàgon, vèrtex apuntant amunt)
|
||||
polyline: 0,-20 10,-17.32 17.32,-10 20,0 17.32,10 10,17.32 0,20 -10,17.32 -17.32,10 -20,0 -17.32,-10 -10,-17.32 0,-20
|
||||
|
||||
# Anell interior (hexàgon, vèrtex apuntant a la dreta — rotat 30° respecte l'exterior)
|
||||
polyline: 5,-8.66 10,0 5,8.66 -5,8.66 -10,0 -5,-8.66 5,-8.66
|
||||
|
||||
# 6 radis: del vèrtex de l'hexàgon interior al vèrtex corresponent del dodecàgon exterior
|
||||
line: 5,-8.66 10,-17.32
|
||||
line: 10,0 20,0
|
||||
line: 5,8.66 10,17.32
|
||||
line: -5,8.66 -10,17.32
|
||||
line: -10,0 -20,0
|
||||
line: -5,-8.66 -10,-17.32
|
||||
|
||||
# Nucli central: petit "+" (2 segments creuats, radi 3)
|
||||
line: -3,0 3,0
|
||||
line: 0,-3 0,3
|
||||
@@ -1,6 +1,6 @@
|
||||
# enemy_pentagon.shp - ORNI enemic (pentàgon doble concentric, radi exterior=20)
|
||||
# enemy/pentagon.shp - ORNI enemic (pentàgon doble concentric, radi exterior=20)
|
||||
|
||||
name: enemy_pentagon
|
||||
name: pentagon
|
||||
scale: 1.0
|
||||
center: 0, 0
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# enemy_pinwheel.shp - ORNI enemic (molinillo de 4 triangles)
|
||||
# enemy/pinwheel.shp - ORNI enemic (molinillo de 4 triangles)
|
||||
# © 2026 JailDesigner
|
||||
|
||||
name: enemy_pinwheel
|
||||
name: pinwheel
|
||||
scale: 1.0
|
||||
center: 0, 0
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# enemy_square.shp - ORNI enemic (rombe, radi=20) + ull amb pupil·la al centre
|
||||
# enemy/square.shp - ORNI enemic (rombe, radi=20) + ull amb pupil·la al centre
|
||||
|
||||
name: enemy_square
|
||||
name: square
|
||||
scale: 1.0
|
||||
center: 0, 0
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
# enemy/star.shp - ORNI enemic (estrella de 5 puntes, només perímetre)
|
||||
# © 2026 JailDesigner
|
||||
#
|
||||
# Pentagrama clàssic: 5 vèrtexs exteriors (radi 20) alternant amb 5 vèrtexs
|
||||
# interiors (radi 7.64 = 20/φ² ≈ proporció àuria) per donar puntes esveltes.
|
||||
# Vèrtex apuntant amunt (igual que enemy_pentagon).
|
||||
#
|
||||
# Sense línies interiors: una única polyline que recorre el perímetre.
|
||||
# Bounding radius natiu ≈ 20 (alineat amb pentagon/square/pinwheel).
|
||||
|
||||
name: star
|
||||
scale: 1.0
|
||||
center: 0, 0
|
||||
|
||||
polyline: 0,-20 4.49,-6.18 19.02,-6.18 7.27,2.36 11.76,16.18 0,7.64 -11.76,16.18 -7.27,2.36 -19.02,-6.18 -4.49,-6.18 0,-20
|
||||
@@ -1,8 +0,0 @@
|
||||
# ship.shp - Nau del jugador 1
|
||||
# Triangle amb base còncava (punta de fletxa)
|
||||
|
||||
name: ship
|
||||
scale: 1.0
|
||||
center: 0, 0
|
||||
|
||||
polyline: 0,-12 8.49,8.49 0,4 -8.49,8.49 0,-12
|
||||
@@ -0,0 +1,7 @@
|
||||
# ship/arrow.shp - Nau del jugador 1 (triangle amb base còncava, punta de fletxa)
|
||||
|
||||
name: arrow
|
||||
scale: 1.0
|
||||
center: 0, 0
|
||||
|
||||
polyline: 0,-12 8.49,8.49 0,4 -8.49,8.49 0,-12
|
||||
@@ -1,7 +1,7 @@
|
||||
# ship2.shp - Nau del jugador 2 (interceptor amb ales)
|
||||
# ship/interceptor.shp - Interceptor amb ales laterals pronunciades
|
||||
# © 2026 JailDesigner
|
||||
|
||||
name: ship2
|
||||
name: interceptor
|
||||
scale: 1.0
|
||||
center: 0, 0
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# ship2.shp - Nau del jugador 2
|
||||
# Triangle amb cercle central (distintiu visual)
|
||||
# ship/wedge.shp - Nau del jugador 2 (triangle amb cercle central)
|
||||
|
||||
name: ship2
|
||||
name: wedge
|
||||
scale: 1.0
|
||||
center: 0, 0
|
||||
|
||||
Binary file not shown.
+174
-159
@@ -1,168 +1,183 @@
|
||||
# stages.yaml - Configuració de les 10 etapes d'Orni Attack
|
||||
# stages.yaml - Configuració de les fases d'Orni Attack
|
||||
# © 2026 JailDesigner
|
||||
#
|
||||
# Format basat en onades (waves). Cada wave:
|
||||
# - spawn: list d'enemics a generar, en ordre.
|
||||
# - spawn_interval: segons entre spawns interns (default 0 = simultanis).
|
||||
# - next: condició per avançar a la wave següent.
|
||||
# - "all_dead" / "end" → quan tots els enemics de l'arena han mort.
|
||||
# - { timeout: T } → quan han passat T segons des de l'inici de la wave.
|
||||
# - { all_dead: true, timeout: T } → el que arribe abans (amuntegament si vas lent).
|
||||
#
|
||||
# Tipus d'enemic: pentagon, square (alias: cuadrado), pinwheel (alias: molinillo), star, orb.
|
||||
|
||||
metadata:
|
||||
version: "1.0"
|
||||
version: "2.0"
|
||||
total_stages: 10
|
||||
description: "Progressive difficulty curve from novice to expert"
|
||||
description: "Wave-based progression"
|
||||
|
||||
stages:
|
||||
# STAGE 1: Tutorial - Mix de tots els tipus, velocitat lenta
|
||||
# STAGE 1 — Tutorial: contacte amb pentagons i un cuadrado.
|
||||
# (Test: també hi ha un orb a la primera onada per provar el contra-atac.)
|
||||
- stage_id: 1
|
||||
total_enemies: 50
|
||||
spawn_config:
|
||||
mode: "progressive"
|
||||
initial_delay: 0.3
|
||||
spawn_interval: 0.4
|
||||
enemy_distribution:
|
||||
pentagon: 34
|
||||
cuadrado: 33
|
||||
molinillo: 33
|
||||
difficulty_multipliers:
|
||||
speed_multiplier: 0.7
|
||||
rotation_multiplier: 0.8
|
||||
tracking_strength: 0.0
|
||||
|
||||
# STAGE 2: Introduction to tracking enemies
|
||||
- stage_id: 2
|
||||
total_enemies: 7
|
||||
spawn_config:
|
||||
mode: "progressive"
|
||||
initial_delay: 1.5
|
||||
spawn_interval: 2.5
|
||||
enemy_distribution:
|
||||
pentagon: 70
|
||||
cuadrado: 30
|
||||
molinillo: 0
|
||||
difficulty_multipliers:
|
||||
speed_multiplier: 0.85
|
||||
rotation_multiplier: 0.9
|
||||
tracking_strength: 0.3
|
||||
|
||||
# STAGE 3: All enemy types, normal speed
|
||||
- stage_id: 3
|
||||
total_enemies: 10
|
||||
spawn_config:
|
||||
mode: "progressive"
|
||||
initial_delay: 1.0
|
||||
spawn_interval: 2.0
|
||||
enemy_distribution:
|
||||
pentagon: 50
|
||||
cuadrado: 30
|
||||
molinillo: 20
|
||||
difficulty_multipliers:
|
||||
speed_multiplier: 1.0
|
||||
rotation_multiplier: 1.0
|
||||
tracking_strength: 0.5
|
||||
|
||||
# STAGE 4: Increased count, faster enemies
|
||||
- stage_id: 4
|
||||
total_enemies: 12
|
||||
spawn_config:
|
||||
mode: "progressive"
|
||||
initial_delay: 0.8
|
||||
spawn_interval: 1.8
|
||||
enemy_distribution:
|
||||
pentagon: 40
|
||||
cuadrado: 35
|
||||
molinillo: 25
|
||||
difficulty_multipliers:
|
||||
speed_multiplier: 1.1
|
||||
rotation_multiplier: 1.15
|
||||
tracking_strength: 0.6
|
||||
|
||||
# STAGE 5: Maximum count reached
|
||||
- stage_id: 5
|
||||
total_enemies: 15
|
||||
spawn_config:
|
||||
mode: "progressive"
|
||||
initial_delay: 0.5
|
||||
spawn_interval: 1.5
|
||||
enemy_distribution:
|
||||
pentagon: 35
|
||||
cuadrado: 35
|
||||
molinillo: 30
|
||||
difficulty_multipliers:
|
||||
speed_multiplier: 1.2
|
||||
rotation_multiplier: 1.25
|
||||
tracking_strength: 0.7
|
||||
|
||||
# STAGE 6: Molinillo becomes dominant
|
||||
- stage_id: 6
|
||||
total_enemies: 15
|
||||
spawn_config:
|
||||
mode: "progressive"
|
||||
initial_delay: 0.3
|
||||
spawn_interval: 1.3
|
||||
enemy_distribution:
|
||||
pentagon: 30
|
||||
cuadrado: 30
|
||||
molinillo: 40
|
||||
difficulty_multipliers:
|
||||
speed_multiplier: 1.3
|
||||
rotation_multiplier: 1.4
|
||||
tracking_strength: 0.8
|
||||
|
||||
# STAGE 7: High intensity, fast spawns
|
||||
- stage_id: 7
|
||||
total_enemies: 15
|
||||
spawn_config:
|
||||
mode: "progressive"
|
||||
initial_delay: 0.2
|
||||
spawn_interval: 1.0
|
||||
enemy_distribution:
|
||||
pentagon: 25
|
||||
cuadrado: 30
|
||||
molinillo: 45
|
||||
difficulty_multipliers:
|
||||
speed_multiplier: 1.4
|
||||
rotation_multiplier: 1.5
|
||||
tracking_strength: 0.9
|
||||
|
||||
# STAGE 8: Expert level, 50% molinillos
|
||||
- stage_id: 8
|
||||
total_enemies: 15
|
||||
spawn_config:
|
||||
mode: "progressive"
|
||||
initial_delay: 0.1
|
||||
spawn_interval: 0.8
|
||||
enemy_distribution:
|
||||
pentagon: 20
|
||||
cuadrado: 30
|
||||
molinillo: 50
|
||||
difficulty_multipliers:
|
||||
speed_multiplier: 1.5
|
||||
rotation_multiplier: 1.6
|
||||
tracking_strength: 1.0
|
||||
|
||||
# STAGE 9: Near-maximum difficulty
|
||||
- stage_id: 9
|
||||
total_enemies: 15
|
||||
spawn_config:
|
||||
mode: "progressive"
|
||||
initial_delay: 0.0
|
||||
multipliers: { velocity: 0.85, rotation: 0.9, tracking: 0.3 }
|
||||
waves:
|
||||
- spawn: [pentagon, pentagon, orb]
|
||||
spawn_interval: 0.6
|
||||
enemy_distribution:
|
||||
pentagon: 15
|
||||
cuadrado: 25
|
||||
molinillo: 60
|
||||
difficulty_multipliers:
|
||||
speed_multiplier: 1.6
|
||||
rotation_multiplier: 1.7
|
||||
tracking_strength: 1.1
|
||||
|
||||
# STAGE 10: Final challenge, 70% molinillos
|
||||
- stage_id: 10
|
||||
total_enemies: 15
|
||||
spawn_config:
|
||||
mode: "progressive"
|
||||
initial_delay: 0.0
|
||||
next: all_dead
|
||||
- spawn: [pentagon, pentagon, square]
|
||||
spawn_interval: 0.5
|
||||
enemy_distribution:
|
||||
pentagon: 10
|
||||
cuadrado: 20
|
||||
molinillo: 70
|
||||
difficulty_multipliers:
|
||||
speed_multiplier: 1.8
|
||||
rotation_multiplier: 2.0
|
||||
tracking_strength: 1.2
|
||||
next: all_dead
|
||||
- spawn: [pentagon, pentagon, square, square]
|
||||
spawn_interval: 0.4
|
||||
next: end
|
||||
|
||||
# STAGE 2 — Apareixen molinillos.
|
||||
- stage_id: 2
|
||||
multipliers: { velocity: 0.95, rotation: 1.0, tracking: 0.4 }
|
||||
waves:
|
||||
- spawn: [pentagon, pentagon, pentagon]
|
||||
spawn_interval: 0.5
|
||||
next: all_dead
|
||||
- spawn: [pinwheel]
|
||||
next: all_dead
|
||||
- spawn: [pentagon, square, pinwheel]
|
||||
spawn_interval: 0.6
|
||||
next: all_dead
|
||||
- spawn: [pinwheel, pinwheel, pentagon]
|
||||
spawn_interval: 0.5
|
||||
next: end
|
||||
|
||||
# STAGE 3 — Primer orb (HP=10).
|
||||
- stage_id: 3
|
||||
multipliers: { velocity: 1.0, rotation: 1.0, tracking: 0.5 }
|
||||
waves:
|
||||
- spawn: [pentagon, pentagon, square]
|
||||
spawn_interval: 0.4
|
||||
next: all_dead
|
||||
- spawn: [orb]
|
||||
next: { all_dead: true, timeout: 12.0 }
|
||||
- spawn: [pinwheel, pinwheel]
|
||||
spawn_interval: 0.5
|
||||
next: all_dead
|
||||
- spawn: [pentagon, square, pinwheel, pinwheel]
|
||||
spawn_interval: 0.4
|
||||
next: end
|
||||
|
||||
# STAGE 4 — Pressió creixent: timeouts curts que poden encavalcar onades.
|
||||
- stage_id: 4
|
||||
multipliers: { velocity: 1.05, rotation: 1.1, tracking: 0.6 }
|
||||
waves:
|
||||
- spawn: [pentagon, pentagon, pentagon]
|
||||
spawn_interval: 0.3
|
||||
next: { all_dead: true, timeout: 5.0 }
|
||||
- spawn: [square, square]
|
||||
spawn_interval: 0.4
|
||||
next: { all_dead: true, timeout: 6.0 }
|
||||
- spawn: [pinwheel, pinwheel, pinwheel]
|
||||
spawn_interval: 0.4
|
||||
next: all_dead
|
||||
- spawn: [orb, pentagon, pentagon]
|
||||
spawn_interval: 0.5
|
||||
next: end
|
||||
|
||||
# STAGE 5 — Apareix la star (zigzag clon del pentagon).
|
||||
- stage_id: 5
|
||||
multipliers: { velocity: 1.1, rotation: 1.2, tracking: 0.7 }
|
||||
waves:
|
||||
- spawn: [star, star]
|
||||
spawn_interval: 0.4
|
||||
next: all_dead
|
||||
- spawn: [pentagon, square, star]
|
||||
spawn_interval: 0.4
|
||||
next: { all_dead: true, timeout: 6.0 }
|
||||
- spawn: [pinwheel, pinwheel, star, star]
|
||||
spawn_interval: 0.4
|
||||
next: all_dead
|
||||
- spawn: [orb, square, square]
|
||||
spawn_interval: 0.5
|
||||
next: end
|
||||
|
||||
# STAGE 6 — Densitat alta, mix amb timeouts agressius.
|
||||
- stage_id: 6
|
||||
multipliers: { velocity: 1.15, rotation: 1.25, tracking: 0.8 }
|
||||
waves:
|
||||
- spawn: [pentagon, pinwheel, pentagon, pinwheel]
|
||||
spawn_interval: 0.3
|
||||
next: { all_dead: true, timeout: 5.0 }
|
||||
- spawn: [square, square, star]
|
||||
spawn_interval: 0.4
|
||||
next: { all_dead: true, timeout: 5.0 }
|
||||
- spawn: [pinwheel, pinwheel, pinwheel]
|
||||
spawn_interval: 0.3
|
||||
next: all_dead
|
||||
- spawn: [orb, pinwheel, pinwheel]
|
||||
spawn_interval: 0.4
|
||||
next: end
|
||||
|
||||
# STAGE 7 — Tiradors i agressivitat.
|
||||
- stage_id: 7
|
||||
multipliers: { velocity: 1.25, rotation: 1.35, tracking: 0.9 }
|
||||
waves:
|
||||
- spawn: [square, square, square]
|
||||
spawn_interval: 0.5
|
||||
next: { all_dead: true, timeout: 6.0 }
|
||||
- spawn: [pinwheel, pinwheel, pentagon, pentagon]
|
||||
spawn_interval: 0.3
|
||||
next: { all_dead: true, timeout: 5.0 }
|
||||
- spawn: [star, star, star]
|
||||
spawn_interval: 0.4
|
||||
next: all_dead
|
||||
- spawn: [orb, pinwheel, pinwheel, square]
|
||||
spawn_interval: 0.5
|
||||
next: end
|
||||
|
||||
# STAGE 8 — Pressió constant.
|
||||
- stage_id: 8
|
||||
multipliers: { velocity: 1.35, rotation: 1.45, tracking: 1.0 }
|
||||
waves:
|
||||
- spawn: [pinwheel, pinwheel, pinwheel]
|
||||
spawn_interval: 0.3
|
||||
next: { all_dead: true, timeout: 4.0 }
|
||||
- spawn: [square, square, star, star]
|
||||
spawn_interval: 0.3
|
||||
next: { all_dead: true, timeout: 5.0 }
|
||||
- spawn: [orb]
|
||||
next: { all_dead: true, timeout: 8.0 }
|
||||
- spawn: [pinwheel, pinwheel, square, star, pentagon]
|
||||
spawn_interval: 0.3
|
||||
next: end
|
||||
|
||||
# STAGE 9 — Quasi-final.
|
||||
- stage_id: 9
|
||||
multipliers: { velocity: 1.5, rotation: 1.6, tracking: 1.1 }
|
||||
waves:
|
||||
- spawn: [pinwheel, pinwheel, star, star]
|
||||
spawn_interval: 0.3
|
||||
next: { all_dead: true, timeout: 4.0 }
|
||||
- spawn: [orb, square, square]
|
||||
spawn_interval: 0.4
|
||||
next: { all_dead: true, timeout: 8.0 }
|
||||
- spawn: [pinwheel, pinwheel, pinwheel, pinwheel]
|
||||
spawn_interval: 0.3
|
||||
next: { all_dead: true, timeout: 5.0 }
|
||||
- spawn: [orb, pinwheel, pinwheel, square, star]
|
||||
spawn_interval: 0.4
|
||||
next: end
|
||||
|
||||
# STAGE 10 — Repte final.
|
||||
- stage_id: 10
|
||||
multipliers: { velocity: 1.7, rotation: 1.8, tracking: 1.2 }
|
||||
waves:
|
||||
- spawn: [pinwheel, pinwheel, pinwheel, pinwheel]
|
||||
spawn_interval: 0.25
|
||||
next: { all_dead: true, timeout: 4.0 }
|
||||
- spawn: [orb, square, star]
|
||||
spawn_interval: 0.4
|
||||
next: { all_dead: true, timeout: 6.0 }
|
||||
- spawn: [pinwheel, pinwheel, star, star, square]
|
||||
spawn_interval: 0.3
|
||||
next: { all_dead: true, timeout: 5.0 }
|
||||
- spawn: [orb, orb, pinwheel, pinwheel, star]
|
||||
spawn_interval: 0.4
|
||||
next: end
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -25,7 +25,6 @@
|
||||
#include "core/defaults/physics.hpp"
|
||||
#include "core/defaults/playfield.hpp"
|
||||
#include "core/defaults/rendering.hpp"
|
||||
#include "core/defaults/ship.hpp"
|
||||
#include "core/defaults/starfield_parallax.hpp"
|
||||
#include "core/defaults/title.hpp"
|
||||
#include "core/defaults/trail.hpp"
|
||||
|
||||
@@ -35,10 +35,11 @@ namespace Defaults::Music {
|
||||
namespace Defaults::Sound {
|
||||
|
||||
constexpr const char* CONTINUE = "effects/continue.wav"; // Cuenta atras
|
||||
constexpr const char* EXPLOSION = "effects/explosion.wav"; // Explosión
|
||||
constexpr const char* EXPLOSION2 = "effects/explosion2.wav"; // Explosión alternativa
|
||||
constexpr const char* ENEMY_EXPLOSION = "effects/enemy_explosion.wav"; // Explosió d'enemic (debris default)
|
||||
constexpr const char* ENEMY_HIT = "effects/enemy_hit.wav"; // Impacte parcial a enemic (debris_partial — HP > 1)
|
||||
constexpr const char* PLAYER_EXPLOSION = "effects/player_explosion.wav"; // Explosió de la nau del jugador
|
||||
constexpr const char* FRIENDLY_FIRE_HIT = "effects/friendly_fire.wav"; // Friendly fire hit
|
||||
constexpr const char* HIT = "effects/hit.wav"; // Enemic ferit (primer impacte → HURT)
|
||||
constexpr const char* BULLET_ZAP = "effects/bullet_zap.wav"; // Bala desintegrant-se (qualsevol impacte o eixida de playarea)
|
||||
constexpr const char* HURT = "effects/hurt.wav"; // Nau pròpia entra a HURT
|
||||
constexpr const char* INIT_HUD = "effects/init_hud.wav"; // Para la animación del HUD
|
||||
constexpr const char* LASER = "effects/laser_shoot.wav"; // Disparo
|
||||
|
||||
@@ -1,101 +1,45 @@
|
||||
// enemies.hpp - Configuració per tipus d'enemic (Pentagon/Square/Molinillo), spawn i scoring
|
||||
// enemies.hpp - Constants tècniques compartides per al sistema d'enemics.
|
||||
// © 2026 JailDesigner
|
||||
//
|
||||
// Tots els paràmetres jugables (physics, animation, wounded, spawn,
|
||||
// behavior, colors, scoring) viuen a data/entities/<type>/<type>.yaml i
|
||||
// s'accedeixen via EnemyRegistry::get(EnemyType). Aquí només queda el
|
||||
// que no és per personalitzar per tipus.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "core/defaults/entities.hpp"
|
||||
namespace Defaults::Enemies::Spawn {
|
||||
|
||||
namespace Defaults::Enemies {
|
||||
// Sostre de reintents al cercar una posició de spawn que respecti el
|
||||
// safety_distance del tipus. No és un paràmetre jugable: és el llindar
|
||||
// tècnic abans de caure a un fallback aleatori amb advertència.
|
||||
constexpr int MAX_SPAWN_ATTEMPTS = 50;
|
||||
|
||||
// Cuerpo físico común (valores por defecto del constructor)
|
||||
namespace Body {
|
||||
constexpr float DEFAULT_MASS = 5.0F; // Más liviano que la nave (10.0)
|
||||
constexpr float RESTITUTION = 1.0F; // Rebote elástico perfecto contra paredes
|
||||
constexpr float LINEAR_DAMPING = 0.0F; // Sin fricción: mantienen velocidad
|
||||
constexpr float ANGULAR_DAMPING = 0.0F;
|
||||
} // namespace Body
|
||||
} // namespace Defaults::Enemies::Spawn
|
||||
|
||||
// Pentagon (esquivador - zigzag evasion)
|
||||
namespace Pentagon {
|
||||
constexpr float SPEED = 35.0F; // px/s (slightly slower)
|
||||
constexpr float MASS = 5.0F; // Masa estándar
|
||||
constexpr float ANGLE_CHANGE_PROB = 0.20F; // 20% per wall hit (frequent zigzag)
|
||||
constexpr float ANGLE_CHANGE_MAX = 1.0F; // Max random angle change (rad)
|
||||
constexpr float ZIGZAG_PROB_PER_SECOND = 0.8F; // Probabilidad de zigzag por segundo
|
||||
constexpr float ROTATION_DELTA_MIN = 0.75F; // Min visual rotation (rad/s) [+50%]
|
||||
constexpr float ROTATION_DELTA_MAX = 3.75F; // Max visual rotation (rad/s) [+50%]
|
||||
constexpr const char* SHAPE_FILE = "enemy_pentagon.shp";
|
||||
} // namespace Pentagon
|
||||
namespace Defaults::Enemies::Visual {
|
||||
|
||||
// Square (perseguidor - tracks player)
|
||||
namespace Square {
|
||||
constexpr float SPEED = 40.0F; // px/s (medium speed)
|
||||
constexpr float MASS = 8.0F; // Más pesado, "tanque"
|
||||
constexpr float TRACKING_STRENGTH = 0.5F; // Interpolation toward player (0.0-1.0)
|
||||
constexpr float TRACKING_INTERVAL = 1.0F; // Seconds between angle updates
|
||||
constexpr float ROTATION_DELTA_MIN = 0.3F; // Slow rotation [+50%]
|
||||
constexpr float ROTATION_DELTA_MAX = 1.5F; // [+50%]
|
||||
constexpr const char* SHAPE_FILE = "enemy_square.shp";
|
||||
} // namespace Square
|
||||
// Duració del "flash" que dispara l'acció FLASH (feedback per impacte
|
||||
// parcial en enemics HP>1). Curt: l'efecte ha de llegir-se com un cop,
|
||||
// no com una transició.
|
||||
constexpr float FLASH_DURATION = 0.08F;
|
||||
|
||||
// Molinillo (agressiu - fast straight lines, proximity spin-up)
|
||||
namespace Pinwheel {
|
||||
constexpr float SPEED = 50.0F; // px/s (fastest)
|
||||
constexpr float MASS = 4.0F; // Más liviano, ágil
|
||||
constexpr float ANGLE_CHANGE_PROB = 0.05F; // 5% per wall hit (rare direction change)
|
||||
constexpr float ANGLE_CHANGE_MAX = 0.3F; // Small angle adjustments
|
||||
constexpr float ROTATION_DELTA_MIN = 3.0F; // Base rotation (rad/s) [+50%]
|
||||
constexpr float ROTATION_DELTA_MAX = 6.0F; // [+50%]
|
||||
constexpr float ROTATION_DELTA_PROXIMITY_MULTIPLIER = 3.0F; // Spin-up multiplier when near ship
|
||||
constexpr float PROXIMITY_DISTANCE = 100.0F; // Distance threshold (px)
|
||||
constexpr const char* SHAPE_FILE = "enemy_pinwheel.shp";
|
||||
} // namespace Pinwheel
|
||||
} // namespace Defaults::Enemies::Visual
|
||||
|
||||
// Animation parameters (shared)
|
||||
namespace Animation {
|
||||
// Palpitation
|
||||
constexpr float PULSE_TRIGGER_PROB = 0.01F; // 1% chance per second
|
||||
constexpr float PULSE_DURATION_MIN = 1.0F; // Min duration (seconds)
|
||||
constexpr float PULSE_DURATION_MAX = 3.0F; // Max duration (seconds)
|
||||
constexpr float PULSE_AMPLITUD_MIN = 0.08F; // Min scale variation
|
||||
constexpr float PULSE_AMPLITUD_MAX = 0.20F; // Max scale variation
|
||||
constexpr float PULSE_FREQ_MIN = 1.5F; // Min frequency (Hz)
|
||||
constexpr float PULSE_FREQ_MAX = 3.0F; // Max frequency (Hz)
|
||||
namespace Defaults::Enemies::Debris {
|
||||
|
||||
// Rotation acceleration
|
||||
constexpr float ROTATION_ACCEL_TRIGGER_PROB = 0.02F; // 2% chance per second [4x more frequent]
|
||||
constexpr float ROTATION_ACCEL_DURATION_MIN = 3.0F; // Min transition time
|
||||
constexpr float ROTATION_ACCEL_DURATION_MAX = 8.0F; // Max transition time
|
||||
constexpr float ROTATION_ACCEL_MULTIPLIER_MIN = 0.3F; // Min speed multiplier [more dramatic]
|
||||
constexpr float ROTATION_ACCEL_MULTIPLIER_MAX = 4.0F; // Max speed multiplier [more dramatic]
|
||||
} // namespace Animation
|
||||
// Escala dels fragments per a l'acció CREATE_DEBRIS_PARTIAL (xip d'impacte
|
||||
// en enemics HP>1). 0.3 = trossos petits, com de "casc esquerdat".
|
||||
constexpr float PARTIAL_PIECE_SCALE = 0.3F;
|
||||
|
||||
// Wounded state (entre primer impacto y explosión)
|
||||
namespace Wounded {
|
||||
constexpr float DURATION = 1.0F; // Segundos en estado herido antes de explotar
|
||||
constexpr float BLINK_HZ = 10.0F; // Frecuencia de parpadeo color tipo ↔ dorado
|
||||
} // namespace Wounded
|
||||
} // namespace Defaults::Enemies::Debris
|
||||
|
||||
// Spawn safety and invulnerability system
|
||||
namespace Spawn {
|
||||
// Safe spawn distance from player
|
||||
constexpr float SAFETY_DISTANCE_MULTIPLIER = 3.0F; // 3x ship radius
|
||||
constexpr float SAFETY_DISTANCE = Defaults::Entities::SHIP_RADIUS * SAFETY_DISTANCE_MULTIPLIER; // 36.0f px
|
||||
constexpr int MAX_SPAWN_ATTEMPTS = 50; // Max attempts to find safe position
|
||||
namespace Defaults::Enemies::Fireworks {
|
||||
|
||||
// Invulnerability system
|
||||
constexpr float INVULNERABILITY_DURATION = 3.0F; // Seconds
|
||||
constexpr float INVULNERABILITY_BRIGHTNESS_START = 0.3F; // Dim
|
||||
constexpr float INVULNERABILITY_BRIGHTNESS_END = 0.7F; // Normal (same as Defaults::Brightness::ENEMIC)
|
||||
constexpr float INVULNERABILITY_SCALE_START = 0.0F; // Invisible
|
||||
constexpr float INVULNERABILITY_SCALE_END = 1.0F; // Full size
|
||||
} // namespace Spawn
|
||||
// Paràmetres del firework "petit" per a l'acció CREATE_FIREWORKS_SMALL
|
||||
// (feedback per impacte parcial en enemics HP>1). Pocs punts i baixa
|
||||
// velocitat: una espurna breu, no una explosió.
|
||||
constexpr int SMALL_N_POINTS = 20;
|
||||
constexpr float SMALL_SPEED = 250.0F;
|
||||
|
||||
// Scoring system (puntuación per type de enemy)
|
||||
namespace Scoring {
|
||||
constexpr int PENTAGON_SCORE = 100; // Pentágono (esquivador, 35 px/s)
|
||||
constexpr int SQUARE_SCORE = 150; // Square (perseguidor, 40 px/s)
|
||||
constexpr int PINWHEEL_SCORE = 200; // Molinillo (agressiu, 50 px/s)
|
||||
} // namespace Scoring
|
||||
|
||||
} // namespace Defaults::Enemies
|
||||
} // namespace Defaults::Enemies::Fireworks
|
||||
|
||||
@@ -3,13 +3,28 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace Defaults::Entities {
|
||||
|
||||
constexpr int MAX_ORNIS = 15;
|
||||
constexpr int MAX_BULLETS = 50;
|
||||
constexpr int MAX_BULLETS = 50; // per jugador (P1 + P2 = 2× aquest valor)
|
||||
constexpr int MAX_ENEMY_BULLETS = 50; // pool reservat per a bales d'enemic
|
||||
|
||||
constexpr float SHIP_RADIUS = 12.0F;
|
||||
constexpr float ENEMY_RADIUS = 20.0F;
|
||||
constexpr float BULLET_RADIUS = 3.0F;
|
||||
// Total real de slots a l'array global bullets_: zona P1, zona P2 i zona enemic.
|
||||
// Reservar zones impedeix que les bales d'enemic ocupin slots del jugador.
|
||||
constexpr int MAX_BULLETS_TOTAL = (MAX_BULLETS * 2) + MAX_ENEMY_BULLETS;
|
||||
constexpr int ENEMY_BULLET_START_IDX = MAX_BULLETS * 2;
|
||||
|
||||
// Convenció d'owner_id per a Bullet::fire:
|
||||
// 0..1 = players (P1, P2)
|
||||
// ENEMY_OWNER_BASE + index = enemic concret (per identificar el seu autoimpacte)
|
||||
// Una bala mata a qualsevol col·lisió excepte amb el seu propi creador.
|
||||
constexpr uint8_t ENEMY_OWNER_BASE = 128;
|
||||
|
||||
// SHIP_RADIUS / ENEMY_RADIUS / BULLET_RADIUS han migrat: ara cada entitat
|
||||
// calcula el seu collision_radius com a
|
||||
// shape.bounding_radius × shape.scale × shape.collision_factor
|
||||
// a partir del seu YAML (data/entities/<name>/<name>.yaml).
|
||||
|
||||
} // namespace Defaults::Entities
|
||||
|
||||
@@ -29,7 +29,7 @@ namespace Defaults::Game {
|
||||
// Friendly fire system
|
||||
constexpr bool FRIENDLY_FIRE_ENABLED = true; // Activar friendly fire
|
||||
constexpr float COLLISION_BULLET_PLAYER_AMPLIFIER = 1.0F; // Hitbox exacto (100%)
|
||||
constexpr float BULLET_SPEED = 700.0F; // Velocidad escalar (px/s). Pascal: 7 px/frame × 20 FPS
|
||||
// BULLET_SPEED migrat a data/entities/player/player.yaml (weapon.bullet_speed).
|
||||
|
||||
// Transición LEVEL_START (mensajes aleatorios PRE-level)
|
||||
constexpr float LEVEL_START_DURATION = 3.0F; // Duración total
|
||||
@@ -39,6 +39,19 @@ namespace Defaults::Game {
|
||||
constexpr float LEVEL_COMPLETED_DURATION = 3.0F; // Duración total
|
||||
constexpr float LEVEL_COMPLETED_TYPING_RATIO = 0.05F; // ~150ms de typewriter (escan ràpid però visible)
|
||||
|
||||
// Attract mode: transició TÍTOL → DEMO. Primer un "dive" de càmera cap al
|
||||
// punt de fuga (deixa enrere títol/naus/logo) i després una cortinilla negra
|
||||
// que cau per tapar; a la demo, la cortinilla segueix caient i destapa.
|
||||
namespace Dive {
|
||||
constexpr float DURATION = 0.55F; // Durada del dive (s), amb acceleració (ease-in)
|
||||
constexpr float CAMERA_DISTANCE = 450.0F; // Avanç de la càmera en +Z (passa les naus, a Z≈323)
|
||||
constexpr float ZOOM_MAX = 7.0F; // Zoom final dels elements 2D (logo + peu) en travessar-los
|
||||
} // namespace Dive
|
||||
namespace Curtain {
|
||||
constexpr float COVER_DURATION = 0.35F; // TÍTOL: la tela cau i tapa
|
||||
constexpr float REVEAL_DURATION = 0.45F; // DEMO: la tela segueix caient i destapa
|
||||
} // namespace Curtain
|
||||
|
||||
// Transición INIT_HUD (animación inicial del HUD)
|
||||
constexpr float INIT_HUD_DURATION = 3.0F; // Duración total del estado
|
||||
|
||||
|
||||
@@ -12,6 +12,17 @@ namespace Defaults::Hud {
|
||||
constexpr float SCOREBOARD_TEXT_SCALE = 0.85F;
|
||||
constexpr float SCOREBOARD_TEXT_SPACING = 0.0F;
|
||||
|
||||
// Colors per segment del marcador. Jerarquia per funció (score/vides/nivell)
|
||||
// + diferenciació de jugador (P1 blanc vs P2 rosa) sense xocar amb els
|
||||
// colors d'enemics (cyan/roig). Amb alpha=255 el line_renderer usa el color
|
||||
// directament sense caure al fallback verd (Rendering::DEFAULT_LINE_COLOR).
|
||||
namespace Colors {
|
||||
constexpr SDL_Color SCORE_P1 = {.r = 255, .g = 255, .b = 255, .a = 255}; // blanc
|
||||
constexpr SDL_Color SCORE_P2 = {.r = 255, .g = 130, .b = 200, .a = 255}; // rosa magenta
|
||||
constexpr SDL_Color LIVES = {.r = 255, .g = 180, .b = 60, .a = 255}; // ambre / or
|
||||
constexpr SDL_Color LEVEL = {.r = 155, .g = 255, .b = 175, .a = 255}; // verd sistema
|
||||
} // namespace Colors
|
||||
|
||||
// Animación de entrada del HUD (init_hud_animator).
|
||||
namespace InitAnim {
|
||||
// Spawn vertical de la nave: 50 px bajo la PLAYAREA (sale desde fuera).
|
||||
|
||||
@@ -6,19 +6,18 @@
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
// Paleta semántica por tipo de entidad. Si una entity declara color, lo
|
||||
// pasa al pipeline con alpha=255 (sentinela "color válido"); si no, se
|
||||
// usa el color global del oscilador (g_current_line_color).
|
||||
// pasa al pipeline con alpha=255 (sentinela "color válido"); si no,
|
||||
// line_renderer::linea() cau a DEFAULT_LINE_COLOR (verd fòsfor fallback).
|
||||
namespace Defaults::Palette {
|
||||
|
||||
// Paleta neon: pujada lleugera dels canals secundaris per millorar la
|
||||
// brillantor perceptual sota el bloom (sense alterar la identitat de color).
|
||||
// El canal dominant es manté a 255 a cada color per maximitzar la saturació
|
||||
// visible quan el halo s'expandeix.
|
||||
constexpr SDL_Color SHIP = {.r = 255, .g = 255, .b = 255, .a = 255}; // Blanco neutro
|
||||
constexpr SDL_Color BULLET = {.r = 155, .g = 255, .b = 175, .a = 255}; // Verde laser
|
||||
constexpr SDL_Color PENTAGON = {.r = 0, .g = 255, .b = 255, .a = 255}; // Cyan pur "esquivador"
|
||||
constexpr SDL_Color SQUARE = {.r = 255, .g = 0, .b = 0, .a = 255}; // Roig pur "tank"
|
||||
constexpr SDL_Color PINWHEEL = {.r = 255, .g = 0, .b = 255, .a = 255}; // Magenta pur "agressiu"
|
||||
constexpr SDL_Color WOUNDED = {.r = 255, .g = 220, .b = 60, .a = 255}; // Dorado: enemigo herido
|
||||
// Tots els colors d'entitats han migrat al seu YAML respectiu
|
||||
// (data/entities/<name>/<name>.yaml, secció `colors`):
|
||||
// - SHIP → player.yaml
|
||||
// - PENTAGON / SQUARE / PINWHEEL / WOUNDED → cada enemy.yaml
|
||||
// - BULLET → bullet.yaml
|
||||
|
||||
} // namespace Defaults::Palette
|
||||
|
||||
@@ -3,31 +3,15 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
namespace Defaults::Physics {
|
||||
// NOTA: els paràmetres del player (rotation_speed, acceleration,
|
||||
// max_velocity, death_impact_factor) viuen a data/entities/player/player.yaml.
|
||||
// Els paràmetres específics de la bala (mass, restitution, damping,
|
||||
// impact_momentum_factor) viuen a data/entities/bullet/bullet.yaml.
|
||||
// Aquest fitxer només conté els paràmetres compartits del subsistema de
|
||||
// debris (explosions visuals).
|
||||
|
||||
constexpr float ROTATION_SPEED = 3.14F; // rad/s (~180°/s)
|
||||
constexpr float ACCELERATION = 400.0F; // px/s²
|
||||
constexpr float MAX_VELOCITY = 180.0F; // px/s
|
||||
constexpr float FRICTION = 20.0F; // px/s²
|
||||
namespace Defaults::Physics::Debris {
|
||||
|
||||
// Bullet — impacto físico contra enemigo (impulse mass-aware).
|
||||
// Model: el impulse és el moment lineal de la bala (m·v) multiplicat per
|
||||
// un factor de transferència [0..1]. 1.0 = transfereix tot el moment
|
||||
// (col·lisió perfectament inelàstica), 0.5 = transfereix la meitat.
|
||||
namespace Bullet {
|
||||
constexpr float IMPACT_MOMENTUM_FACTOR = 3.0F; // Factor de transferència de moment bala→enemic
|
||||
} // namespace Bullet
|
||||
|
||||
// Ship → enemy: impuls explícit aplicat a l'enemic en el moment exacte
|
||||
// que la nau mor per col·lisió amb ell (afegit per damunt del rebot
|
||||
// natural de PhysicsWorld, que ja és present però subtil amb la
|
||||
// damping de la nau).
|
||||
namespace Ship {
|
||||
constexpr float DEATH_IMPACT_MOMENTUM_FACTOR = 0.3F;
|
||||
} // namespace Ship
|
||||
|
||||
// Explosions (debris physics)
|
||||
namespace Debris {
|
||||
constexpr float SPEED_BASE = 80.0F; // Velocidad inicial (px/s)
|
||||
constexpr float VARIACIO_SPEED = 40.0F; // ±variació aleatòria (px/s)
|
||||
constexpr float ACCELERACIO = -60.0F; // Fricció/desacceleració (px/s²)
|
||||
@@ -59,6 +43,13 @@ namespace Defaults::Physics {
|
||||
// 1.0 = inèrcia completa; >1.0 amplifica la deriva; <1.0 la atenua.
|
||||
constexpr float ENEMY_VELOCITY_INHERITANCE = 1.0F;
|
||||
|
||||
// Velocitat de la bala traspassada a cada fragment de debris al moment
|
||||
// de l'impacte. Separat de la inèrcia del cos (velocitat_objecte): permet
|
||||
// que els trossos volin "amb la força de la bala" encara que el cos pesi
|
||||
// molt i amb prou feines es mogui. 0.4 a 700 px/s = ~280 px/s extra per
|
||||
// fragment, molt visible sense ser excessiu.
|
||||
constexpr float BULLET_IMPULSE_FACTOR = 0.4F;
|
||||
|
||||
// Tuneig específic de l'explosió d'enemic (overrides als defaults
|
||||
// que es passen com a paràmetres opcionals a explode()).
|
||||
constexpr float ENEMY_LIFETIME = 2.5F; // Vida mínima del debris (s) — els que segueixen movent-se viuen més
|
||||
@@ -69,6 +60,5 @@ namespace Defaults::Physics {
|
||||
// Excess above this threshold is converted to tangential linear velocity
|
||||
// Prevents "vortex trap" problem with high-rotation enemies
|
||||
constexpr float SPEED_ROT_MAX = 1.5F; // rad/s (~86°/s)
|
||||
} // namespace Debris
|
||||
|
||||
} // namespace Defaults::Physics
|
||||
} // namespace Defaults::Physics::Debris
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
|
||||
namespace Defaults::Rendering {
|
||||
@@ -35,8 +34,12 @@ namespace Defaults::Rendering {
|
||||
constexpr int RENDER_HEIGHT_DEFAULT = 720;
|
||||
|
||||
constexpr auto isValidRenderResolution(int w, int h) -> bool {
|
||||
return std::ranges::any_of(RESOLUTION_PRESETS,
|
||||
[w, h](const ResolutionPreset& preset) { return preset.w == w && preset.h == h; });
|
||||
for (const auto& preset : RESOLUTION_PRESETS) {
|
||||
if (preset.w == w && preset.h == h) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace Defaults::Rendering
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
// ship.hpp - Configuració de la nau (invulnerabilitat, parpelleig)
|
||||
// © 2026 JailDesigner
|
||||
|
||||
#pragma once
|
||||
|
||||
namespace Defaults::Ship {
|
||||
|
||||
// Invulnerabilidad post-respawn
|
||||
constexpr float INVULNERABILITY_DURATION = 3.0F; // Segundos de invulnerabilidad
|
||||
|
||||
// Parpadeo visual durante invulnerabilidad
|
||||
constexpr float BLINK_VISIBLE_TIME = 0.1F; // Tiempo visible (segundos)
|
||||
constexpr float BLINK_INVISIBLE_TIME = 0.1F; // Tiempo invisible (segundos)
|
||||
// Frecuencia total: 0.2s/ciclo = 5 Hz (~15 parpadeos en 3s)
|
||||
|
||||
// Cuerpo físico
|
||||
constexpr float MASS = 10.0F; // Masa de referencia para choques
|
||||
constexpr float RESTITUTION = 0.6F; // Rebote moderado contra paredes
|
||||
constexpr float LINEAR_DAMPING = 1.5F; // Fricción exponencial (s⁻¹)
|
||||
constexpr float ANGULAR_DAMPING = 0.0F; // Rotación 100% por input (no inercial)
|
||||
|
||||
// Empuje visual: escala proporcional a la velocidad (0..200 px/s → 1.0..1.5)
|
||||
// Mantiene la sensación del Pascal original.
|
||||
constexpr float VISUAL_PUSH_DIVISOR = 33.33F; // SPEED / DIVISOR = empuje visual
|
||||
constexpr float VISUAL_SCALE_DIVISOR = 12.0F; // SCALE = 1 + (PUSH / DIVISOR)
|
||||
|
||||
// Estat "ferit": entre primera col·lisió amb enemic i recuperació o segona col·lisió mortal.
|
||||
namespace Hurt {
|
||||
constexpr float DURATION = 15.0F; // Segons en estat ferit (provisional)
|
||||
constexpr float BLINK_HZ = 10.0F; // Freqüència parpelleig color normal ↔ ferit
|
||||
} // namespace Hurt
|
||||
|
||||
} // namespace Defaults::Ship
|
||||
@@ -7,7 +7,7 @@ namespace Defaults::Trail {
|
||||
|
||||
constexpr int POOL_SIZE = 200;
|
||||
|
||||
constexpr float SPEED_THRESHOLD_PX_S = 54.0F; // 30% de Physics::MAX_VELOCITY (180)
|
||||
constexpr float SPEED_THRESHOLD_PX_S = 54.0F; // 30% de player.yaml::physics.max_velocity (180 px/s)
|
||||
constexpr float EMIT_INTERVAL_S = 0.04F; // ~25 Hz nominal
|
||||
constexpr float EMIT_JITTER_S = 0.015F; // ±15 ms al cooldown
|
||||
constexpr float POSITION_JITTER_PX = 2.5F; // jitter al punt de naixement
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
// entity_loader.cpp - Implementació del carregador d'entitats YAML
|
||||
// © 2026 JailDesigner
|
||||
|
||||
#include "core/entities/entity_loader.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <exception>
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "core/resources/resource_helper.hpp"
|
||||
|
||||
namespace Entities {
|
||||
|
||||
std::unordered_map<std::string, std::shared_ptr<fkyaml::node>> EntityLoader::cache;
|
||||
|
||||
auto EntityLoader::load(const std::string& name) -> std::shared_ptr<fkyaml::node> {
|
||||
// Cache hit
|
||||
auto it = cache.find(name);
|
||||
if (it != cache.end()) {
|
||||
std::cout << "[EntityLoader] Cache hit: " << name << '\n';
|
||||
return it->second;
|
||||
}
|
||||
|
||||
const std::string PATH = "entities/" + name + "/" + name + ".yaml";
|
||||
|
||||
std::vector<uint8_t> data = Resource::Helper::loadFile(PATH);
|
||||
if (data.empty()) {
|
||||
std::cerr << "[EntityLoader] Error: no s'ha pogut load " << PATH << '\n';
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
try {
|
||||
std::string yaml_content(data.begin(), data.end());
|
||||
std::stringstream stream(yaml_content);
|
||||
auto node = std::make_shared<fkyaml::node>(fkyaml::node::deserialize(stream));
|
||||
|
||||
std::cout << "[EntityLoader] Carregat: " << PATH << '\n';
|
||||
cache[name] = node;
|
||||
return node;
|
||||
} catch (const std::exception& e) {
|
||||
std::cerr << "[EntityLoader] Excepció parsejant " << PATH << ": " << e.what() << '\n';
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
void EntityLoader::clearCache() {
|
||||
std::cout << "[EntityLoader] Netejant caché (" << cache.size() << " entitats)" << '\n';
|
||||
cache.clear();
|
||||
}
|
||||
|
||||
auto EntityLoader::getCacheSize() -> size_t { return cache.size(); }
|
||||
|
||||
} // namespace Entities
|
||||
@@ -0,0 +1,38 @@
|
||||
// entity_loader.hpp - Carregador genèric de descriptors d'entitats en YAML
|
||||
// © 2026 JailDesigner
|
||||
//
|
||||
// Cada entitat viu a `data/entities/<name>/<name>.yaml` (mateix patró que el
|
||||
// projecte germà aee_arcade). Aquest loader resol el path, llegeix del
|
||||
// resource pack via Resource::Helper, parseja amb fkyaml i cacheja el node
|
||||
// per evitar relectures. Retorna nullptr en cas d'error (el caller decideix
|
||||
// si abortar).
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
#include "external/fkyaml_node.hpp"
|
||||
|
||||
namespace Entities {
|
||||
|
||||
class EntityLoader {
|
||||
public:
|
||||
EntityLoader() = delete; // tot estàtic
|
||||
|
||||
// Carrega el descriptor d'una entitat per nom (ex. "player" →
|
||||
// "entities/player/player.yaml"). Retorna nullptr si no es pot
|
||||
// carregar o parsejar. Cachejat per nom.
|
||||
static auto load(const std::string& name) -> std::shared_ptr<fkyaml::node>;
|
||||
|
||||
// Buidar caché (útil per debug/recàrrega).
|
||||
static void clearCache();
|
||||
|
||||
[[nodiscard]] static auto getCacheSize() -> size_t;
|
||||
|
||||
private:
|
||||
static std::unordered_map<std::string, std::shared_ptr<fkyaml::node>> cache;
|
||||
};
|
||||
|
||||
} // namespace Entities
|
||||
@@ -51,12 +51,12 @@ namespace Graphics {
|
||||
|
||||
namespace {
|
||||
|
||||
// Lerp de l'oscil·lador (color base actual) cap a un color "flash" en
|
||||
// funció de f ∈ [0, 1]. Retorna sempre amb alpha>0 perquè el line_renderer
|
||||
// l'use directament (sense barrejar amb el global).
|
||||
// Lerp del color base verd fòsfor cap a un color "flash" en funció de
|
||||
// f ∈ [0, 1]. Retorna sempre amb alpha>0 perquè el line_renderer l'usi
|
||||
// directament (sense caure al fallback DEFAULT_LINE_COLOR).
|
||||
auto lerpColor(SDL_Color flash, float f) -> SDL_Color {
|
||||
const float CLAMPED = std::clamp(f, 0.0F, 1.0F);
|
||||
const SDL_Color BASE = Rendering::getLineColor();
|
||||
constexpr SDL_Color BASE = Rendering::DEFAULT_LINE_COLOR;
|
||||
const auto LERP_U8 = [&](unsigned char a, unsigned char b) {
|
||||
const float OUT = (static_cast<float>(a) * (1.0F - CLAMPED)) + (static_cast<float>(b) * CLAMPED);
|
||||
return static_cast<unsigned char>(OUT);
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
// curtain.cpp - Implementació de la cortinilla negra
|
||||
// © 2026 JailDesigner
|
||||
|
||||
#include "core/graphics/curtain.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#include "core/defaults/game.hpp"
|
||||
#include "core/math/easing.hpp"
|
||||
|
||||
namespace Graphics {
|
||||
|
||||
namespace {
|
||||
constexpr float SCREEN_H = static_cast<float>(Defaults::Game::HEIGHT);
|
||||
constexpr float SCREEN_W = static_cast<float>(Defaults::Game::WIDTH);
|
||||
} // namespace
|
||||
|
||||
Curtain::Curtain(Rendering::Renderer* renderer)
|
||||
: renderer_(renderer) {}
|
||||
|
||||
void Curtain::cover(float duration) {
|
||||
// Caire superior de -H (fora, a dalt) fins a 0 (tela tapant tota la pantalla).
|
||||
from_ = -SCREEN_H;
|
||||
to_ = 0.0F;
|
||||
duration_ = duration;
|
||||
elapsed_ = 0.0F;
|
||||
active_ = true;
|
||||
}
|
||||
|
||||
void Curtain::reveal(float duration) {
|
||||
// Caire superior de 0 (tapant) fins a +H (tela fora per baix).
|
||||
from_ = 0.0F;
|
||||
to_ = SCREEN_H;
|
||||
duration_ = duration;
|
||||
elapsed_ = 0.0F;
|
||||
active_ = true;
|
||||
}
|
||||
|
||||
void Curtain::update(float delta_time) {
|
||||
if (!active_) {
|
||||
return;
|
||||
}
|
||||
elapsed_ += delta_time;
|
||||
}
|
||||
|
||||
auto Curtain::topY() const -> float {
|
||||
if (duration_ <= 0.0F) {
|
||||
return to_;
|
||||
}
|
||||
const float T = std::clamp(elapsed_ / duration_, 0.0F, 1.0F);
|
||||
// Ease-in: la tela "cau" accelerant, com per gravetat.
|
||||
return Easing::lerp(from_, to_, Easing::easeInQuad(T));
|
||||
}
|
||||
|
||||
auto Curtain::isDone() const -> bool {
|
||||
return !active_ || elapsed_ >= duration_;
|
||||
}
|
||||
|
||||
void Curtain::draw() const {
|
||||
if (!active_) {
|
||||
return;
|
||||
}
|
||||
const float TOP = topY();
|
||||
// Si la tela ja ha sortit completament per baix, no hi ha res a pintar.
|
||||
if (TOP >= SCREEN_H) {
|
||||
return;
|
||||
}
|
||||
renderer_->pushRect(0.0F, TOP, SCREEN_W, SCREEN_H, 0.0F, 0.0F, 0.0F, 1.0F);
|
||||
}
|
||||
|
||||
} // namespace Graphics
|
||||
@@ -0,0 +1,48 @@
|
||||
// curtain.hpp - Cortinilla negra per a transicions d'escena
|
||||
// © 2026 JailDesigner
|
||||
//
|
||||
// Tela negra a pantalla completa que es mou SEMPRE cap avall:
|
||||
// - cover(): cau des de dalt fins a tapar-ho tot (queda negre).
|
||||
// - reveal(): segueix caient i surt per baix, deixant veure l'escena.
|
||||
// Una escena la posseeix, l'actualitza cada frame i la dibuixa l'ÚLTIM (per
|
||||
// damunt de tot). En repòs (no arrencada o reveal acabada) el draw() és no-op.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "core/rendering/render_context.hpp"
|
||||
|
||||
namespace Graphics {
|
||||
|
||||
class Curtain {
|
||||
public:
|
||||
explicit Curtain(Rendering::Renderer* renderer);
|
||||
|
||||
// Tela que cau des de dalt fins a tapar tota la pantalla en 'duration' s.
|
||||
void cover(float duration);
|
||||
|
||||
// Tela que segueix caient i surt per baix (destapa) en 'duration' s.
|
||||
void reveal(float duration);
|
||||
|
||||
// Avança el temporitzador intern.
|
||||
void update(float delta_time);
|
||||
|
||||
// Dibuixa la tela negra a la seva posició vertical actual. No-op si no
|
||||
// queda res visible.
|
||||
void draw() const;
|
||||
|
||||
// Cert quan el moviment actual ha acabat (o no s'ha arrencat mai).
|
||||
[[nodiscard]] auto isDone() const -> bool;
|
||||
|
||||
private:
|
||||
// Posició actual del caire superior de la tela (píxels lògics).
|
||||
[[nodiscard]] auto topY() const -> float;
|
||||
|
||||
Rendering::Renderer* renderer_;
|
||||
float from_{0.0F};
|
||||
float to_{0.0F};
|
||||
float duration_{0.0F};
|
||||
float elapsed_{0.0F};
|
||||
bool active_{false};
|
||||
};
|
||||
|
||||
} // namespace Graphics
|
||||
@@ -62,6 +62,12 @@ namespace Graphics {
|
||||
buildLines();
|
||||
}
|
||||
|
||||
void Playfield::completeBuild() {
|
||||
// Avançar el rellotge intern més enllà de tota la finestra d'spawn + el
|
||||
// creixement de l'última línia: computeLineProgress() retorna 1.0 per a totes.
|
||||
elapsed_s_ = Defaults::Playfield::TOTAL_ANIMATION_DURATION_S;
|
||||
}
|
||||
|
||||
void Playfield::update(float delta_time) {
|
||||
elapsed_s_ += delta_time;
|
||||
for (auto& ripple : ripples_) {
|
||||
|
||||
@@ -30,6 +30,11 @@ namespace Graphics {
|
||||
// Avança timers interns (creació + ripples).
|
||||
void update(float delta_time);
|
||||
|
||||
// Completa instantàniament l'animació de creació de la graella (totes les
|
||||
// línies al 100%). Útil per a la demo (attract), que arrenca amb la
|
||||
// partida "ja començada" i no ha de mostrar el muntatge del fons.
|
||||
void completeBuild();
|
||||
|
||||
// Pinta la graella. La porció dibuixada de cada línia depèn del timer intern,
|
||||
// i s'aplica deformació radial per cada ripple activa que afecti la línia.
|
||||
void draw() const;
|
||||
|
||||
@@ -20,7 +20,7 @@ namespace Graphics {
|
||||
return it->second; // Cache hit
|
||||
}
|
||||
|
||||
// Normalize path: "ship.shp" → "shapes/ship.shp"
|
||||
// Normalize path: "ship/arrow.shp" → "shapes/ship/arrow.shp"
|
||||
// "logo/letra_j.shp" → "shapes/logo/letra_j.shp"
|
||||
std::string normalized = filename;
|
||||
if (!normalized.starts_with("shapes/")) {
|
||||
@@ -53,7 +53,8 @@ namespace Graphics {
|
||||
|
||||
// Cache and return
|
||||
std::cout << "[ShapeLoader] Carregat: " << normalized << " (" << shape->getName()
|
||||
<< ", " << shape->getNumPrimitives() << " primitives)" << '\n';
|
||||
<< ", " << shape->getNumPrimitives() << " primitives, bounding_radius="
|
||||
<< shape->getBoundingRadius() << ")" << '\n';
|
||||
|
||||
cache[filename] = shape;
|
||||
return shape;
|
||||
|
||||
@@ -19,7 +19,7 @@ namespace Graphics {
|
||||
|
||||
// Carregar shape desde file (con caché)
|
||||
// Retorna punter compartit (nullptr si error)
|
||||
// Exemple: load("ship.shp") → busca a "data/shapes/ship.shp"
|
||||
// Exemple: load("ship/arrow.shp") → busca a "data/shapes/ship/arrow.shp"
|
||||
static auto load(const std::string& filename) -> std::shared_ptr<Shape>;
|
||||
|
||||
// Netejar caché (útil per debug/recàrrega)
|
||||
|
||||
@@ -26,7 +26,7 @@ namespace Graphics {
|
||||
// - scale: factor de scale (1.0 = 20×40 px por carácter)
|
||||
// - spacing: espacio entre caracteres en píxeles (a scale 1.0)
|
||||
// - brightness: factor de brightness (0.0-1.0, default 1.0 = màxima brightness)
|
||||
// - color: color RGBA explícit; si alpha==0 (default) s'usa l'oscil·lador global
|
||||
// - color: color RGBA explícit; si alpha==0 (default) es fa fallback a Rendering::DEFAULT_LINE_COLOR
|
||||
void render(const std::string& text, const Vec2& position, float scale = 1.0F, float spacing = 2.0F, float brightness = 1.0F, SDL_Color color = {0, 0, 0, 0}) const;
|
||||
|
||||
// Renderizar string centrado en un punto
|
||||
@@ -35,7 +35,7 @@ namespace Graphics {
|
||||
// - scale: factor de scale (1.0 = 20×40 px por carácter)
|
||||
// - spacing: espacio entre caracteres en píxeles (a scale 1.0)
|
||||
// - brightness: factor de brightness (0.0-1.0, default 1.0 = màxima brightness)
|
||||
// - color: color RGBA explícit; si alpha==0 (default) s'usa l'oscil·lador global
|
||||
// - color: color RGBA explícit; si alpha==0 (default) es fa fallback a Rendering::DEFAULT_LINE_COLOR
|
||||
void renderCentered(const std::string& text, const Vec2& centre_point, float scale = 1.0F, float spacing = 2.0F, float brightness = 1.0F, SDL_Color color = {0, 0, 0, 0}) const;
|
||||
|
||||
// Calcular ancho total de un string (útil para centrado).
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Mesh3D = llista de vèrtexs Vec3 + llista d'arestes (parells d'índexs).
|
||||
// drawWireframe() aplica una Transform3D al mesh, projecta amb Camera3D i
|
||||
// emet cada aresta com una línia 2D pel pipeline `Rendering::linea` (mateix
|
||||
// pipeline que la resta del joc: glow verd via ColorOscillator si color.a==0).
|
||||
// pipeline que la resta del joc: verd fòsfor via Rendering::DEFAULT_LINE_COLOR si color.a==0).
|
||||
//
|
||||
// Sense depth buffer: el caller és responsable d'ordenar els meshos per
|
||||
// profunditat decreixent si vol oclusió coherent (la pipeline és LINE_LIST
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
|
||||
#include "core/input/define_inputs.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <format>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
@@ -154,9 +153,12 @@ namespace System {
|
||||
}
|
||||
|
||||
auto DefineInputs::isInUse(int code) const -> bool {
|
||||
return std::ranges::any_of(sequence_, [code](const Step& s) {
|
||||
return s.captured == code;
|
||||
});
|
||||
for (const auto& s : sequence_) {
|
||||
if (s.captured == code) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void DefineInputs::captureAndAdvance(int code) {
|
||||
|
||||
+19
-11
@@ -2,7 +2,6 @@
|
||||
|
||||
#include <SDL3/SDL.h> // Para SDL_GetGamepadAxis, SDL_GamepadAxis, SDL_GamepadButton, SDL_GetError, SDL_JoystickID, SDL_AddGamepadMappingsFromFile, SDL_Event, SDL_EventType, SDL_GetGamepadButton, SDL_GetKeyboardState, SDL_INIT_GAMEPAD, SDL_InitSubSystem, SDL_LogError, SDL_OpenGamepad, SDL_PollEvent, SDL_WasInit, Sint16, SDL_Gamepad, SDL_LogCategory, SDL_Scancode
|
||||
|
||||
#include <algorithm> // Para std::ranges::any_of
|
||||
#include <iostream> // Para basic_ostream, operator<<, cout, cerr
|
||||
#include <memory> // Para shared_ptr, __shared_ptr_access, allocator, operator==, make_shared
|
||||
#include <unordered_map> // Para unordered_map, _Node_iterator, operator==, _Node_iterator_base, _Node_const_iterator
|
||||
@@ -166,9 +165,12 @@ auto Input::checkAnyButton(bool repeat) -> bool {
|
||||
|
||||
// Comprueba si algún player (P1 o P2) presionó alguna acción de una lista
|
||||
auto Input::checkAnyPlayerAction(const std::span<const InputAction>& actions, bool repeat) -> bool {
|
||||
return std::ranges::any_of(actions, [this, repeat](const InputAction& action) {
|
||||
return checkActionPlayer1(action, repeat) || checkActionPlayer2(action, repeat);
|
||||
});
|
||||
for (const auto& action : actions) {
|
||||
if (checkActionPlayer1(action, repeat) || checkActionPlayer2(action, repeat)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Comprueba si hay algun mando conectado
|
||||
@@ -307,8 +309,11 @@ auto Input::checkTriggerInput(Action action, const std::shared_ptr<Gamepad>& gam
|
||||
}
|
||||
|
||||
void Input::addGamepadMappingsFromFile() {
|
||||
if (SDL_AddGamepadMappingsFromFile(gamepad_mappings_file_.c_str()) < 0) {
|
||||
std::cout << "Error, could not load " << gamepad_mappings_file_.c_str() << " file: " << SDL_GetError() << '\n';
|
||||
const int COUNT = SDL_AddGamepadMappingsFromFile(gamepad_mappings_file_.c_str());
|
||||
if (COUNT < 0) {
|
||||
std::cerr << "[Input] Error carregant " << gamepad_mappings_file_ << ": " << SDL_GetError() << '\n';
|
||||
} else {
|
||||
std::cout << "[Input] " << gamepad_mappings_file_ << " carregat (" << COUNT << " mappings)\n";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -326,8 +331,7 @@ void Input::initSDLGamePad() {
|
||||
} else {
|
||||
addGamepadMappingsFromFile();
|
||||
discoverGamepads();
|
||||
std::cout << "\n** INPUT SYSTEM **\n";
|
||||
std::cout << "Input System initialized successfully\n";
|
||||
std::cout << "[Input] inicialitzat\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -441,9 +445,13 @@ auto Input::addGamepad(int device_index) -> std::string {
|
||||
}
|
||||
|
||||
auto Input::removeGamepad(SDL_JoystickID id) -> std::string {
|
||||
auto it = std::ranges::find_if(gamepads_, [id](const std::shared_ptr<Gamepad>& gamepad) {
|
||||
return gamepad->instance_id == id;
|
||||
});
|
||||
auto it = gamepads_.end();
|
||||
for (auto i = gamepads_.begin(); i != gamepads_.end(); ++i) {
|
||||
if ((*i)->instance_id == id) {
|
||||
it = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (it != gamepads_.end()) {
|
||||
std::string name = (*it)->name;
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
|
||||
#include "core/physics/physics_world.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
#include "core/physics/rigid_body.hpp"
|
||||
@@ -14,10 +13,13 @@ namespace Physics {
|
||||
if (body == nullptr) {
|
||||
return;
|
||||
}
|
||||
if (std::ranges::find(bodies_, body) == bodies_.end()) {
|
||||
bodies_.push_back(body);
|
||||
for (const auto* b : bodies_) {
|
||||
if (b == body) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
bodies_.push_back(body);
|
||||
}
|
||||
|
||||
void PhysicsWorld::removeBody(RigidBody* body) {
|
||||
std::erase(bodies_, body);
|
||||
|
||||
@@ -8,11 +8,6 @@
|
||||
|
||||
namespace Rendering {
|
||||
|
||||
// Color global compartido para líneas sin paleta propia (HUD, debug, texto
|
||||
// genérico). Equivale al "color máximo" de la antigua oscilación CPU: verde
|
||||
// fósforo CRT. El pulso de brillo lo aplica ahora el shader de postpro.
|
||||
SDL_Color g_current_line_color = {100, 255, 100, 255};
|
||||
|
||||
// Grosor global por defecto. Configurable via setLineThickness.
|
||||
float g_current_line_thickness = Defaults::Rendering::LINE_THICKNESS_DEFAULT;
|
||||
|
||||
@@ -36,8 +31,8 @@ namespace Rendering {
|
||||
const auto FX2 = static_cast<float>(x2);
|
||||
const auto FY2 = static_cast<float>(y2);
|
||||
|
||||
// color.alpha==0 → usar color global (verde fósforo). alpha>0 → color directo.
|
||||
const SDL_Color SOURCE = (color.a > 0) ? color : g_current_line_color;
|
||||
// color.alpha==0 → fallback a DEFAULT_LINE_COLOR (verd fòsfor). alpha>0 → color directo.
|
||||
const SDL_Color SOURCE = (color.a > 0) ? color : DEFAULT_LINE_COLOR;
|
||||
const float R = (static_cast<float>(SOURCE.r) * brightness) / 255.0F;
|
||||
const float G = (static_cast<float>(SOURCE.g) * brightness) / 255.0F;
|
||||
const float B = (static_cast<float>(SOURCE.b) * brightness) / 255.0F;
|
||||
@@ -68,10 +63,6 @@ namespace Rendering {
|
||||
}
|
||||
}
|
||||
|
||||
void setLineColor(SDL_Color color) { g_current_line_color = color; }
|
||||
|
||||
auto getLineColor() -> SDL_Color { return g_current_line_color; }
|
||||
|
||||
void setLineThickness(float thickness) {
|
||||
if (thickness > 0.0F) {
|
||||
g_current_line_thickness = thickness;
|
||||
|
||||
@@ -3,9 +3,10 @@
|
||||
//
|
||||
// El dibujo de líneas pasa por el pipeline GPU. Las coordenadas (x1,y1,x2,y2)
|
||||
// son lógicas (1280×720); el shader las mapea a NDC y el viewport del SDLManager
|
||||
// hace el letterbox a píxeles físicos. El brillo modula el color global de
|
||||
// línea (lo gestiona ColorOscillator). El grosor es configurable por línea
|
||||
// (parámetro thickness>0) o global (g_current_line_thickness vía setLineThickness).
|
||||
// hace el letterbox a píxeles físicos. El pulse de brillo lo aplica el shader
|
||||
// de postpro (ya no hi ha un ColorOscillator a CPU). El grosor es configurable
|
||||
// per línia (parámetro thickness>0) o global (g_current_line_thickness vía
|
||||
// setLineThickness).
|
||||
|
||||
#pragma once
|
||||
|
||||
@@ -15,12 +16,17 @@
|
||||
|
||||
namespace Rendering {
|
||||
|
||||
// Color verd fòsfor CRT per defecte: s'usa quan el caller passa color amb
|
||||
// alpha==0 (sentinella "sense color propi"). Constant immutable: la
|
||||
// semàntica de "color global" ja no existeix (era de l'antic ColorOscillator).
|
||||
constexpr SDL_Color DEFAULT_LINE_COLOR = {.r = 100, .g = 255, .b = 100, .a = 255};
|
||||
|
||||
// Dibuja una línea entre dos puntos en coordenadas lógicas (1280×720).
|
||||
// brightness: factor de brillo (0.0..1.0, default 1.0 = brillo máximo).
|
||||
// Pre-multiplica el RGB del color (color dim sobre fons negre).
|
||||
// thickness: grosor en píxeles lógicos. Si <= 0 usa g_current_line_thickness.
|
||||
// color: si alpha==0, se usa el color global del oscilador; si alpha>0 se
|
||||
// usa este color directo (paleta semántica por entidad).
|
||||
// color: si alpha==0, se usa DEFAULT_LINE_COLOR (verd fòsfor fallback);
|
||||
// si alpha>0 se usa este color directo (paleta semántica por entidad).
|
||||
// alpha: alpha que arriba al GPU (default 1.0 = opac, behavior original).
|
||||
// Valors <1.0 fan que la línia es barregi de veritat sobre el dest
|
||||
// en comptes de sobrepintar-lo (útil per halos translúcids).
|
||||
@@ -49,10 +55,6 @@ namespace Rendering {
|
||||
SDL_Color color = {0, 0, 0, 0},
|
||||
SDL_Color glow_color = {0, 0, 0, 0});
|
||||
|
||||
// Color global de las líneas (lo actualiza ColorOscillator vía SDLManager).
|
||||
void setLineColor(SDL_Color color);
|
||||
[[nodiscard]] auto getLineColor() -> SDL_Color;
|
||||
|
||||
// Grosor global por defecto (en píxeles lógicos). Default: 1.5.
|
||||
void setLineThickness(float thickness);
|
||||
[[nodiscard]] auto getLineThickness() -> float;
|
||||
|
||||
@@ -72,8 +72,6 @@ auto Pack::addFile(const std::string& filepath, const std::string& pack_name) ->
|
||||
|
||||
resources_[pack_name] = entry;
|
||||
|
||||
std::cout << "[ResourcePack] Añadido: " << pack_name << " (" << file_data.size()
|
||||
<< " bytes)\n";
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -105,7 +103,6 @@ auto Pack::addDirectory(const std::string& dir_path,
|
||||
relative_path.find(".tsx") != std::string::npos ||
|
||||
relative_path.find(".DS_Store") != std::string::npos ||
|
||||
relative_path.find(".git") != std::string::npos) {
|
||||
std::cout << "[ResourcePack] Saltant: " << relative_path << '\n';
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -154,9 +151,6 @@ auto Pack::savePack(const std::string& pack_file) -> bool {
|
||||
file.write(reinterpret_cast<const char*>(&data_size), sizeof(data_size));
|
||||
file.write(reinterpret_cast<const char*>(encrypted_data.data()), encrypted_data.size());
|
||||
|
||||
std::cout << "[ResourcePack] Guardat: " << pack_file << " (" << resources_.size()
|
||||
<< " recursos, " << data_size << " bytes)\n";
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -219,9 +213,6 @@ auto Pack::loadPack(const std::string& pack_file) -> bool {
|
||||
// Desencriptar
|
||||
decryptData(data_, DEFAULT_ENCRYPT_KEY);
|
||||
|
||||
std::cout << "[ResourcePack] Carregat: " << pack_file << " (" << resources_.size()
|
||||
<< " recursos)\n";
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -299,10 +290,6 @@ auto Pack::validatePack() const -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
if (valid) {
|
||||
std::cout << "[ResourcePack] Validació OK (" << resources_.size() << " recursos)\n";
|
||||
}
|
||||
|
||||
return valid;
|
||||
}
|
||||
|
||||
|
||||
@@ -106,8 +106,11 @@ Director::Director(int argc, char* argv[])
|
||||
// falla, Locale::text() retorna la clau crua i el joc segueix funcionant.
|
||||
Locale::get().load(std::string("locale/") + cfg_->locale + ".yaml");
|
||||
|
||||
// Inicialitzar sistema de input
|
||||
Input::init("data/gamecontrollerdb.txt");
|
||||
// Inicialitzar sistema de input. El gamecontrollerdb.txt viu al costat del
|
||||
// binari (no dins de resources.pack, perquè SDL_AddGamepadMappingsFromFile
|
||||
// necessita una ruta real de filesystem). resource_base ja apunta al directori
|
||||
// de l'executable (o a Contents/Resources en bundles de macOS).
|
||||
Input::init(resource_base + "/gamecontrollerdb.txt");
|
||||
|
||||
// Autoassignacio de primer arranque: si cap dels dos jugadors te mando
|
||||
// assignat al config, repartim els que hi haja detectats (P1 = pad 0,
|
||||
|
||||
@@ -70,10 +70,24 @@ namespace SceneManager {
|
||||
return match_config_;
|
||||
}
|
||||
|
||||
// Nombre d'escenaris demo curats (cicle del attract mode).
|
||||
static constexpr std::uint8_t DEMO_SCENARIO_COUNT = 4;
|
||||
|
||||
// Índex de l'escenari demo actual. Persisteix entre transicions (el
|
||||
// SceneContext el posseeix el Director), així cada entrada al mode demo
|
||||
// mostra el següent escenari de la llista curada.
|
||||
[[nodiscard]] auto demoScenarioIndex() const -> std::uint8_t {
|
||||
return demo_scenario_index_;
|
||||
}
|
||||
void advanceDemoScenario() {
|
||||
demo_scenario_index_ = (demo_scenario_index_ + 1) % DEMO_SCENARIO_COUNT;
|
||||
}
|
||||
|
||||
private:
|
||||
SceneType next_scene_{SceneType::LOGO}; // SceneType a la qual transicionar
|
||||
Option option_{Option::NONE}; // Opción específica per l'escena
|
||||
GameConfig::MatchConfig match_config_; // Configuración de match (jugadors active, mode)
|
||||
std::uint8_t demo_scenario_index_{0}; // Índex de l'escenari demo (attract mode)
|
||||
};
|
||||
|
||||
// Variable global inline per gestionar l'escena actual (backward compatibility)
|
||||
|
||||
@@ -57,13 +57,18 @@ namespace Effects {
|
||||
SDL_Color color,
|
||||
float lifetime,
|
||||
float friction,
|
||||
int segment_multiplier) {
|
||||
int segment_multiplier,
|
||||
const Vec2& bullet_impulse_velocity,
|
||||
float piece_scale) {
|
||||
if (!shape || !shape->isValid()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Reproducir sonido de explosión
|
||||
// Reproducir sonido de explosión. Cadena buida = explosió silenciosa
|
||||
// (p. ex. el logo dins el cicle d'atracció).
|
||||
if (!sound.empty()) {
|
||||
Audio::get()->playSound(sound, Audio::Group::GAME);
|
||||
}
|
||||
|
||||
// Notificar als subscriptors (border, playfield, etc.).
|
||||
if (explosion_callback_) {
|
||||
@@ -84,7 +89,7 @@ namespace Effects {
|
||||
Vec2 world_p2 = transformPoint(local_p2, shape_centre, centro, angle, scale);
|
||||
|
||||
// Si el pool es ple, no té sentit continuar amb la resta de segments
|
||||
if (!spawnDebris(world_p1, world_p2, centro, velocitat_base, brightness, velocitat_objecte, velocitat_angular, factor_herencia_visual, color, lifetime, friction)) {
|
||||
if (!spawnDebris(world_p1, world_p2, centro, velocitat_base, brightness, velocitat_objecte, velocitat_angular, factor_herencia_visual, color, lifetime, friction, bullet_impulse_velocity, piece_scale)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -110,34 +115,47 @@ namespace Effects {
|
||||
return segments;
|
||||
}
|
||||
|
||||
auto DebrisManager::spawnDebris(const Vec2& world_p1, const Vec2& world_p2, const Vec2& centro, float velocitat_base, float brightness, const Vec2& velocitat_objecte, float velocitat_angular, float factor_herencia_visual, SDL_Color color, float lifetime, float friction) -> bool {
|
||||
auto DebrisManager::spawnDebris(const Vec2& world_p1_in, const Vec2& world_p2_in, const Vec2& centro, float velocitat_base, float brightness, const Vec2& velocitat_objecte, float velocitat_angular, float factor_herencia_visual, SDL_Color color, float lifetime, float friction, const Vec2& bullet_impulse_velocity, float piece_scale) -> bool {
|
||||
Debris* debris = findFreeSlot();
|
||||
if (debris == nullptr) {
|
||||
std::cerr << "[DebrisManager] Warning: no debris slots disponibles\n";
|
||||
return false;
|
||||
}
|
||||
|
||||
// Escala el segment al voltant del seu punt mitjà segons piece_scale
|
||||
// (1.0 = original; 0.3 = "esquerda petita"). La resta del càlcul (angle,
|
||||
// half_length, p1/p2) en deriva naturalment.
|
||||
const Vec2 MID = {.x = (world_p1_in.x + world_p2_in.x) / 2.0F,
|
||||
.y = (world_p1_in.y + world_p2_in.y) / 2.0F};
|
||||
const Vec2 WORLD_P1 = {.x = MID.x + ((world_p1_in.x - MID.x) * piece_scale),
|
||||
.y = MID.y + ((world_p1_in.y - MID.y) * piece_scale)};
|
||||
const Vec2 WORLD_P2 = {.x = MID.x + ((world_p2_in.x - MID.x) * piece_scale),
|
||||
.y = MID.y + ((world_p2_in.y - MID.y) * piece_scale)};
|
||||
|
||||
// Geometria autoritaritzada: centro + original_angle + original_half_length.
|
||||
// p1/p2 es reconstrueixen cada frame en update() des d'aquestes dades.
|
||||
const float DX = world_p2.x - world_p1.x;
|
||||
const float DY = world_p2.y - world_p1.y;
|
||||
debris->centro = {.x = (world_p1.x + world_p2.x) / 2.0F,
|
||||
.y = (world_p1.y + world_p2.y) / 2.0F};
|
||||
const float DX = WORLD_P2.x - WORLD_P1.x;
|
||||
const float DY = WORLD_P2.y - WORLD_P1.y;
|
||||
debris->centro = {.x = (WORLD_P1.x + WORLD_P2.x) / 2.0F,
|
||||
.y = (WORLD_P1.y + WORLD_P2.y) / 2.0F};
|
||||
debris->original_angle = std::atan2(DY, DX);
|
||||
debris->original_half_length = std::sqrt((DX * DX) + (DY * DY)) / 2.0F;
|
||||
debris->p1 = world_p1;
|
||||
debris->p2 = world_p2;
|
||||
debris->p1 = WORLD_P1;
|
||||
debris->p2 = WORLD_P2;
|
||||
|
||||
// Direcció radial (desde el centro hacia el segment)
|
||||
Vec2 direccio = computeExplosionDirection(world_p1, world_p2, centro);
|
||||
Vec2 direccio = computeExplosionDirection(WORLD_P1, WORLD_P2, centro);
|
||||
|
||||
// Velocidad inicial (base ± variació aleatòria + velocity heretada de l'objecte)
|
||||
// Velocidad inicial (base ± variació aleatòria + velocity heretada de l'objecte +
|
||||
// velocitat de la bala escalada per BULLET_IMPULSE_FACTOR).
|
||||
float speed =
|
||||
velocitat_base +
|
||||
(((std::rand() / static_cast<float>(RAND_MAX)) * 2.0F - 1.0F) *
|
||||
Defaults::Physics::Debris::VARIACIO_SPEED);
|
||||
debris->velocity.x = (direccio.x * speed) + velocitat_objecte.x;
|
||||
debris->velocity.y = (direccio.y * speed) + velocitat_objecte.y;
|
||||
debris->velocity.x = (direccio.x * speed) + velocitat_objecte.x +
|
||||
(bullet_impulse_velocity.x * Defaults::Physics::Debris::BULLET_IMPULSE_FACTOR);
|
||||
debris->velocity.y = (direccio.y * speed) + velocitat_objecte.y +
|
||||
(bullet_impulse_velocity.y * Defaults::Physics::Debris::BULLET_IMPULSE_FACTOR);
|
||||
debris->acceleration = friction;
|
||||
|
||||
// Rotación de trayectoria (con conversió a tangencial si excedeix cap)
|
||||
|
||||
@@ -47,6 +47,14 @@ namespace Effects {
|
||||
// - lifetime: temps de vida del debris (s, per defecte TEMPS_VIDA = 2s)
|
||||
// - friction: desacceleració del debris (px/s², per defecte ACCELERACIO = -60)
|
||||
// - segment_multiplier: nombre de còpies per segment (per defecte 1 = sense duplicar)
|
||||
// - bullet_impulse_velocity: velocitat de la bala que ha causat l'impacte (px/s,
|
||||
// per defecte 0). S'aplica a cada fragment escalada per
|
||||
// Defaults::Physics::Debris::BULLET_IMPULSE_FACTOR, independent de
|
||||
// velocitat_objecte. Permet que els trossos "salten amb la força de la bala"
|
||||
// encara que el cos sigui pesat i amb prou feines es mogui.
|
||||
// - piece_scale: multiplicador de la longitud de cada fragment al spawn
|
||||
// (per defecte 1.0). Útil per a debris "parcial" d'impactes no letals
|
||||
// en enemics HP>1 (trossos petits, com d'esquerda).
|
||||
void explode(const std::shared_ptr<Graphics::Shape>& shape,
|
||||
const Vec2& centro,
|
||||
float angle,
|
||||
@@ -56,11 +64,14 @@ namespace Effects {
|
||||
const Vec2& velocitat_objecte = {.x = 0.0F, .y = 0.0F},
|
||||
float velocitat_angular = 0.0F,
|
||||
float factor_herencia_visual = 0.0F,
|
||||
const std::string& sound = Defaults::Sound::EXPLOSION,
|
||||
// sound: nom del so d'explosió. Cadena buida ("") = explosió silenciosa.
|
||||
const std::string& sound = Defaults::Sound::ENEMY_EXPLOSION,
|
||||
SDL_Color color = {0, 0, 0, 0}, // alpha==0 → fragmentos usan oscilador global
|
||||
float lifetime = Defaults::Physics::Debris::TEMPS_VIDA,
|
||||
float friction = Defaults::Physics::Debris::ACCELERACIO,
|
||||
int segment_multiplier = 1);
|
||||
int segment_multiplier = 1,
|
||||
const Vec2& bullet_impulse_velocity = {.x = 0.0F, .y = 0.0F},
|
||||
float piece_scale = 1.0F);
|
||||
|
||||
// Actualitzar todos los fragments active
|
||||
void update(float delta_time);
|
||||
@@ -97,7 +108,7 @@ namespace Effects {
|
||||
-> std::vector<std::pair<Vec2, Vec2>>;
|
||||
// Inicialitza un debris en un slot lliure i el deixa actiu. Retorna
|
||||
// false si el pool está ple (la cridadora ha d'aturar el bucle).
|
||||
auto spawnDebris(const Vec2& world_p1, const Vec2& world_p2, const Vec2& centro, float velocitat_base, float brightness, const Vec2& velocitat_objecte, float velocitat_angular, float factor_herencia_visual, SDL_Color color, float lifetime, float friction) -> bool;
|
||||
auto spawnDebris(const Vec2& world_p1, const Vec2& world_p2, const Vec2& centro, float velocitat_base, float brightness, const Vec2& velocitat_objecte, float velocitat_angular, float factor_herencia_visual, SDL_Color color, float lifetime, float friction, const Vec2& bullet_impulse_velocity, float piece_scale) -> bool;
|
||||
static void applyAngularVelocity(Debris& debris, const Vec2& direccio, float velocitat_angular);
|
||||
static void applyVisualRotation(Debris& debris, float velocitat_angular, float factor_herencia_visual);
|
||||
};
|
||||
|
||||
@@ -33,9 +33,9 @@ namespace Effects {
|
||||
|
||||
TrailManager::TrailManager(Rendering::Renderer* renderer)
|
||||
: renderer_(renderer),
|
||||
star_shape_(Graphics::ShapeLoader::load("star.shp")) {
|
||||
star_shape_(Graphics::ShapeLoader::load("effect/starfield.shp")) {
|
||||
if (!star_shape_ || !star_shape_->isValid()) {
|
||||
std::cerr << "[TrailManager] Warning: no s'ha pogut load star.shp\n";
|
||||
std::cerr << "[TrailManager] Warning: no s'ha pogut load effect/starfield.shp\n";
|
||||
}
|
||||
for (auto& particle : pool_) {
|
||||
particle.active = false;
|
||||
|
||||
@@ -14,38 +14,39 @@
|
||||
#include "core/rendering/shape_renderer.hpp"
|
||||
#include "core/types.hpp"
|
||||
#include "game/constants.hpp"
|
||||
#include "game/entities/bullet_config.hpp"
|
||||
#include "game/entities/bullet_registry.hpp"
|
||||
|
||||
Bullet::Bullet(Rendering::Renderer* renderer)
|
||||
: Entity(renderer) {
|
||||
// Brightness específico para balas
|
||||
: Entity(renderer),
|
||||
config_(&BulletRegistry::get()) {
|
||||
brightness_ = Defaults::Brightness::BALA;
|
||||
|
||||
// Configuración del cuerpo físico.
|
||||
// Las balas son cinemáticas: no colisionan con otros bodies ni paredes.
|
||||
// El gameplay (GameScene) gestiona los hits con check_collision y la
|
||||
// salida del PLAYAREA. Por eso radius=0 en el world (no participa en
|
||||
// resolveBodyCollisions ni resolveBoundsCollisions).
|
||||
body_.setMass(0.5F); // Ligera (no afecta a nadie, pero por consistencia)
|
||||
body_.radius = 0.0F; // Sin colisión física (cinemática pura)
|
||||
body_.restitution = 0.0F; // Irrelevante (no rebota)
|
||||
body_.linear_damping = 0.0F; // Sin fricción (movimiento rectilíneo uniforme)
|
||||
body_.angular_damping = 0.0F;
|
||||
// Cinemàtiques pures: no col·lisionen al PhysicsWorld (body_.radius = 0).
|
||||
// El gameplay (GameScene) gestiona els hits via checkCollisionSwept i la
|
||||
// sortida del PLAYAREA.
|
||||
body_.setMass(config_->physics.mass);
|
||||
body_.radius = 0.0F;
|
||||
body_.restitution = config_->physics.restitution;
|
||||
body_.linear_damping = config_->physics.linear_damping;
|
||||
body_.angular_damping = config_->physics.angular_damping;
|
||||
|
||||
// Cargar shape compartida desde archivo
|
||||
shape_ = Graphics::ShapeLoader::load("bullet.shp");
|
||||
shape_ = Graphics::ShapeLoader::load(config_->shape.path);
|
||||
if (!shape_ || !shape_->isValid()) {
|
||||
std::cerr << "[Bullet] Error: no s'ha pogut load bullet.shp" << '\n';
|
||||
std::cerr << "[Bullet] Error: no s'ha pogut carregar " << config_->shape.path << '\n';
|
||||
}
|
||||
|
||||
// Radi de col·lisió derivat del cercle circumscrit de la shape.
|
||||
const float BOUNDING = (shape_ != nullptr) ? shape_->getBoundingRadius() : 0.0F;
|
||||
collision_radius_ = BOUNDING * config_->shape.scale * config_->shape.collision_factor;
|
||||
}
|
||||
|
||||
void Bullet::init() {
|
||||
// Inicialment inactiva
|
||||
is_active_ = false;
|
||||
center_ = {.x = 0.0F, .y = 0.0F};
|
||||
prev_position_ = {.x = 0.0F, .y = 0.0F};
|
||||
angle_ = 0.0F;
|
||||
|
||||
// Reset del cuerpo físico
|
||||
body_.position = Vec2{};
|
||||
body_.velocity = Vec2{};
|
||||
body_.angle = 0.0F;
|
||||
@@ -53,29 +54,43 @@ void Bullet::init() {
|
||||
body_.clearAccumulators();
|
||||
}
|
||||
|
||||
void Bullet::fire(const Vec2& position, float angle, uint8_t owner_id) {
|
||||
// Activar bullet
|
||||
void Bullet::fire(const Vec2& position, float angle, uint8_t owner_id, float bullet_speed, const BulletConfig* cfg) {
|
||||
is_active_ = true;
|
||||
|
||||
// Almacenar propietario (0=P1, 1=P2)
|
||||
owner_id_ = owner_id;
|
||||
|
||||
// Posición y orientación iniciales = ship
|
||||
// Si no es passa cfg, restaurem al config per defecte (BulletRegistry::get):
|
||||
// els slots són reutilitzables i una bala que abans ha estat disparada amb
|
||||
// una variant (p.ex. bullet_long d'enemic) ha de tornar al bullet.shp del
|
||||
// player quan aquest la reutilitza.
|
||||
const BulletConfig* effective = (cfg != nullptr) ? cfg : &BulletRegistry::get();
|
||||
if (effective != config_) {
|
||||
config_ = effective;
|
||||
shape_ = Graphics::ShapeLoader::load(config_->shape.path);
|
||||
if (!shape_ || !shape_->isValid()) {
|
||||
std::cerr << "[Bullet] Error: no s'ha pogut carregar " << config_->shape.path << '\n';
|
||||
}
|
||||
const float BOUNDING = (shape_ != nullptr) ? shape_->getBoundingRadius() : 0.0F;
|
||||
collision_radius_ = BOUNDING * config_->shape.scale * config_->shape.collision_factor;
|
||||
body_.setMass(config_->physics.mass);
|
||||
body_.restitution = config_->physics.restitution;
|
||||
body_.linear_damping = config_->physics.linear_damping;
|
||||
body_.angular_damping = config_->physics.angular_damping;
|
||||
}
|
||||
|
||||
center_ = position;
|
||||
prev_position_ = position; // Al spawn no hi ha moviment encara: swept degenera a punt-cercle
|
||||
prev_position_ = position; // spawn: swept degenera a punt-cercle
|
||||
angle_ = angle;
|
||||
|
||||
// Sincronizar el body físico: posición + velocidad cartesiana
|
||||
// angle - PI/2 porque angle=0 apunta hacia arriba (eje Y negativo SDL)
|
||||
// Sincronizar el body físic: posició + velocitat cartesiana.
|
||||
// angle - PI/2 perquè angle=0 apunta cap amunt (eje Y negatiu SDL).
|
||||
body_.position = position;
|
||||
body_.angle = angle;
|
||||
const float DIR_X = std::cos(angle - (Constants::PI / 2.0F));
|
||||
const float DIR_Y = std::sin(angle - (Constants::PI / 2.0F));
|
||||
body_.velocity = Vec2{.x = DIR_X * Defaults::Game::BULLET_SPEED, .y = DIR_Y * Defaults::Game::BULLET_SPEED};
|
||||
body_.velocity = Vec2{.x = DIR_X * bullet_speed, .y = DIR_Y * bullet_speed};
|
||||
body_.angular_velocity = 0.0F;
|
||||
body_.clearAccumulators();
|
||||
|
||||
// Reproducir sonido de disparo láser
|
||||
Audio::get()->playSound(Defaults::Sound::LASER, Audio::Group::GAME);
|
||||
}
|
||||
|
||||
@@ -87,24 +102,18 @@ void Bullet::update(float /*delta_time*/) {
|
||||
}
|
||||
|
||||
void Bullet::postUpdate(float /*delta_time*/) {
|
||||
// Captura la posició al final del frame anterior abans de sobreescriure center_;
|
||||
// així el sistema de col·lisions pot fer swept (segment-vs-cercle) entre prev_position_
|
||||
// i la nova center_, evitant tunneling a velocitats altes.
|
||||
prev_position_ = center_;
|
||||
center_ = body_.position;
|
||||
// angle_ no cambia (las balas no rotan visualmente).
|
||||
}
|
||||
|
||||
void Bullet::desactivar() {
|
||||
is_active_ = false;
|
||||
// Detener el cuerpo físico para que no acumule deriva mientras inactiva.
|
||||
body_.velocity = Vec2{};
|
||||
body_.angular_velocity = 0.0F;
|
||||
}
|
||||
|
||||
void Bullet::draw() const {
|
||||
if (is_active_ && shape_) {
|
||||
// Les bales roten segons l'angle de trayectòria (estático tras disparo)
|
||||
Rendering::renderShape(renderer_, shape_, center_, angle_, 1.0F, 1.0F, brightness_, Defaults::Palette::BULLET);
|
||||
Rendering::renderShape(renderer_, shape_, center_, angle_, config_->shape.scale, 1.0F, brightness_, config_->colors.normal);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,10 +6,12 @@
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
#include "core/defaults.hpp"
|
||||
#include "core/entities/entity.hpp"
|
||||
#include "core/types.hpp"
|
||||
|
||||
// Forward declaration — la definició completa s'inclou només al .cpp.
|
||||
struct BulletConfig;
|
||||
|
||||
class Bullet : public Entities::Entity {
|
||||
public:
|
||||
Bullet()
|
||||
@@ -17,7 +19,11 @@ class Bullet : public Entities::Entity {
|
||||
explicit Bullet(Rendering::Renderer* renderer);
|
||||
|
||||
void init() override;
|
||||
void fire(const Vec2& position, float angle, uint8_t owner_id);
|
||||
// cfg = nullptr → manté el config actual (per defecte: BulletRegistry::get()).
|
||||
// cfg != nullptr → substitueix el config per a aquesta bala (recarrega
|
||||
// shape, recalcula collision_radius_, mass, etc.). Útil per a bales
|
||||
// d'enemic amb shape pròpia.
|
||||
void fire(const Vec2& position, float angle, uint8_t owner_id, float bullet_speed, const BulletConfig* cfg = nullptr);
|
||||
void update(float delta_time) override;
|
||||
void postUpdate(float delta_time) override;
|
||||
void draw() const override;
|
||||
@@ -25,25 +31,25 @@ class Bullet : public Entities::Entity {
|
||||
// Override: Interfaz de Entity
|
||||
[[nodiscard]] auto isActive() const -> bool override { return is_active_; }
|
||||
|
||||
// Override: Interfaz de colisión (gameplay-level: PLAYAREA bounds-check)
|
||||
[[nodiscard]] auto getCollisionRadius() const -> float override {
|
||||
return Defaults::Entities::BULLET_RADIUS;
|
||||
}
|
||||
// Override: Interfaz de colisión (radi derivat al ctor des del shape).
|
||||
[[nodiscard]] auto getCollisionRadius() const -> float override { return collision_radius_; }
|
||||
[[nodiscard]] auto isCollidable() const -> bool override {
|
||||
return is_active_;
|
||||
}
|
||||
|
||||
// Configuració associada (vàlida des del ctor — la bala l'agafa del BulletRegistry).
|
||||
[[nodiscard]] auto getConfig() const -> const BulletConfig& { return *config_; }
|
||||
|
||||
// Getters (API pública sin cambios)
|
||||
[[nodiscard]] auto getOwnerId() const -> uint8_t { return owner_id_; }
|
||||
// Posició al final del frame anterior, per a CCD segment-vs-cercle.
|
||||
[[nodiscard]] auto getPrevPosition() const -> const Vec2& { return prev_position_; }
|
||||
void desactivar();
|
||||
|
||||
private:
|
||||
// Miembros específicos de Bullet (heredados: renderer_, shape_, center_, angle_, brightness_, body_).
|
||||
// Inicializados en la declaración para que tanto el ctor por defecto como el que toma renderer
|
||||
// dejen el objeto en estado coherente (proyectil inactivo, sin owner).
|
||||
const BulletConfig* config_{nullptr}; // apunta al BulletRegistry; vàlid post-ctor
|
||||
float collision_radius_{0.0F}; // derivat: shape.bounding_radius × scale × collision_factor
|
||||
|
||||
bool is_active_{false};
|
||||
uint8_t owner_id_{0}; // 0=P1, 1=P2
|
||||
Vec2 prev_position_{}; // Posició al final del frame anterior (per a swept collision)
|
||||
Vec2 prev_position_{}; // posició al final del frame anterior (swept CCD)
|
||||
};
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
// bullet_config.cpp - Implementació del parser de BulletConfig
|
||||
// © 2026 JailDesigner
|
||||
|
||||
#include "game/entities/bullet_config.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <exception>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
namespace {
|
||||
|
||||
auto parseColor(const fkyaml::node& node, SDL_Color& out) -> bool {
|
||||
if (!node.is_sequence() || node.size() != 3) {
|
||||
return false;
|
||||
}
|
||||
const auto R = node[0].get_value<uint32_t>();
|
||||
const auto G = node[1].get_value<uint32_t>();
|
||||
const auto B = node[2].get_value<uint32_t>();
|
||||
out = SDL_Color{
|
||||
.r = static_cast<uint8_t>(R),
|
||||
.g = static_cast<uint8_t>(G),
|
||||
.b = static_cast<uint8_t>(B),
|
||||
.a = 255};
|
||||
return true;
|
||||
}
|
||||
|
||||
auto parseShape(const fkyaml::node& node, BulletConfig::ShapeCfg& out) -> bool {
|
||||
if (!node.contains("shape") || !node["shape"].contains("path")) {
|
||||
std::cerr << "[BulletConfig] Error: falta 'shape.path'\n";
|
||||
return false;
|
||||
}
|
||||
const auto& s = node["shape"];
|
||||
out.path = s["path"].get_value<std::string>();
|
||||
out.scale = s.contains("scale") ? s["scale"].get_value<float>() : 1.0F;
|
||||
out.collision_factor = s.contains("collision_factor")
|
||||
? s["collision_factor"].get_value<float>()
|
||||
: 1.0F;
|
||||
return true;
|
||||
}
|
||||
|
||||
auto parsePhysics(const fkyaml::node& node, BulletConfig::PhysicsCfg& out) -> bool {
|
||||
if (!node.contains("physics")) {
|
||||
std::cerr << "[BulletConfig] Error: falta 'physics'\n";
|
||||
return false;
|
||||
}
|
||||
const auto& p = node["physics"];
|
||||
out.mass = p["mass"].get_value<float>();
|
||||
out.restitution = p["restitution"].get_value<float>();
|
||||
out.linear_damping = p["linear_damping"].get_value<float>();
|
||||
out.angular_damping = p["angular_damping"].get_value<float>();
|
||||
out.impact_momentum_factor = p["impact_momentum_factor"].get_value<float>();
|
||||
return true;
|
||||
}
|
||||
|
||||
auto parseColors(const fkyaml::node& node, BulletConfig::ColorsCfg& out) -> bool {
|
||||
if (!node.contains("colors") || !parseColor(node["colors"]["normal"], out.normal)) {
|
||||
std::cerr << "[BulletConfig] Error: 'colors.normal' no és [r,g,b]\n";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
auto BulletConfig::fromYaml(const fkyaml::node& node) -> std::optional<BulletConfig> {
|
||||
try {
|
||||
BulletConfig cfg;
|
||||
cfg.name = node.contains("name") ? node["name"].get_value<std::string>() : "bullet";
|
||||
|
||||
if (!parseShape(node, cfg.shape)) { return std::nullopt; }
|
||||
if (!parsePhysics(node, cfg.physics)) { return std::nullopt; }
|
||||
if (!parseColors(node, cfg.colors)) { return std::nullopt; }
|
||||
|
||||
return cfg;
|
||||
} catch (const std::exception& e) {
|
||||
std::cerr << "[BulletConfig] Excepció parsejant: " << e.what() << '\n';
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
// bullet_config.hpp - Configuració de la bala carregada des de YAML
|
||||
// © 2026 JailDesigner
|
||||
//
|
||||
// Paral·lel a Player/EnemyConfig. Una sola instància a tot el joc (per ara);
|
||||
// es comparteix entre totes les bales actives via BulletRegistry.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <optional>
|
||||
#include <string>
|
||||
|
||||
#include "external/fkyaml_node.hpp"
|
||||
|
||||
struct BulletConfig {
|
||||
struct ShapeCfg {
|
||||
std::string path;
|
||||
float scale;
|
||||
float collision_factor;
|
||||
};
|
||||
|
||||
struct PhysicsCfg {
|
||||
float mass;
|
||||
float restitution;
|
||||
float linear_damping;
|
||||
float angular_damping;
|
||||
float impact_momentum_factor; // factor de transferència bullet→enemic
|
||||
};
|
||||
|
||||
struct ColorsCfg {
|
||||
SDL_Color normal;
|
||||
};
|
||||
|
||||
std::string name;
|
||||
ShapeCfg shape;
|
||||
PhysicsCfg physics;
|
||||
ColorsCfg colors;
|
||||
|
||||
static auto fromYaml(const fkyaml::node& node) -> std::optional<BulletConfig>;
|
||||
};
|
||||
@@ -0,0 +1,56 @@
|
||||
// bullet_registry.cpp - Implementació del registre de bales
|
||||
// © 2026 JailDesigner
|
||||
|
||||
#include "game/entities/bullet_registry.hpp"
|
||||
|
||||
#include <cstdlib>
|
||||
#include <iostream>
|
||||
|
||||
#include "core/entities/entity_loader.hpp"
|
||||
|
||||
std::unordered_map<std::string, BulletConfig> BulletRegistry::configs;
|
||||
bool BulletRegistry::loaded = false;
|
||||
|
||||
namespace {
|
||||
// Tria comú: carrega el YAML d'un name, parseja a BulletConfig i el guarda
|
||||
// al map. Retorna punter al config inserit, o nullptr si falla.
|
||||
auto loadInto(std::unordered_map<std::string, BulletConfig>& configs, const std::string& name) -> const BulletConfig* {
|
||||
auto yaml = Entities::EntityLoader::load(name);
|
||||
if (!yaml) {
|
||||
std::cerr << "[BulletRegistry] Error: no s'ha pogut carregar " << name << ".yaml\n";
|
||||
return nullptr;
|
||||
}
|
||||
auto cfg = BulletConfig::fromYaml(*yaml);
|
||||
if (!cfg) {
|
||||
std::cerr << "[BulletRegistry] Error: format invàlid a " << name << ".yaml\n";
|
||||
return nullptr;
|
||||
}
|
||||
auto [it, _] = configs.insert_or_assign(name, *cfg);
|
||||
return &it->second;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
auto BulletRegistry::load() -> bool {
|
||||
if (loadInto(configs, "bullet") == nullptr) {
|
||||
return false;
|
||||
}
|
||||
loaded = true;
|
||||
std::cout << "[BulletRegistry] Configuració de bala 'bullet' carregada.\n";
|
||||
return true;
|
||||
}
|
||||
|
||||
auto BulletRegistry::get() -> const BulletConfig& {
|
||||
if (!loaded) {
|
||||
std::cerr << "[BulletRegistry] FATAL: get() abans de load()\n";
|
||||
std::exit(EXIT_FAILURE);
|
||||
}
|
||||
return configs.at("bullet");
|
||||
}
|
||||
|
||||
auto BulletRegistry::get(const std::string& name) -> const BulletConfig* {
|
||||
auto it = configs.find(name);
|
||||
if (it != configs.end()) {
|
||||
return &it->second;
|
||||
}
|
||||
return loadInto(configs, name);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// bullet_registry.hpp - Registre estàtic de configuracions de bala
|
||||
// © 2026 JailDesigner
|
||||
//
|
||||
// Diverses configuracions per nom (data/entities/<name>/<name>.yaml). El
|
||||
// config "bullet" es manté com a default històric (player) i es carrega via
|
||||
// load(). Els altres (ex. "bullet_long" per a bales d'enemic) es carreguen
|
||||
// peresosament la primera vegada que algú els demana per nom.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
#include "game/entities/bullet_config.hpp"
|
||||
|
||||
class BulletRegistry {
|
||||
public:
|
||||
BulletRegistry() = delete;
|
||||
|
||||
// Carrega data/entities/bullet/bullet.yaml com a default. Retorna false si falla.
|
||||
static auto load() -> bool;
|
||||
|
||||
// Accés a la configuració per defecte ("bullet"). Avorta amb log fatal si
|
||||
// load() no s'ha cridat o ha fallat. Mantingut per a backwards compat del Bullet ctor.
|
||||
static auto get() -> const BulletConfig&;
|
||||
|
||||
// Accés a una configuració per nom. Lazy-load: si no està al map, intenta
|
||||
// carregar data/entities/<name>/<name>.yaml. Retorna nullptr si no es pot.
|
||||
static auto get(const std::string& name) -> const BulletConfig*;
|
||||
|
||||
private:
|
||||
static std::unordered_map<std::string, BulletConfig> configs;
|
||||
static bool loaded;
|
||||
};
|
||||
+95
-246
@@ -14,6 +14,8 @@
|
||||
#include "core/rendering/shape_renderer.hpp"
|
||||
#include "core/types.hpp"
|
||||
#include "game/constants.hpp"
|
||||
#include "game/entities/enemy_config.hpp"
|
||||
#include "game/entities/enemy_registry.hpp"
|
||||
|
||||
namespace {
|
||||
|
||||
@@ -26,100 +28,70 @@ namespace {
|
||||
};
|
||||
}
|
||||
|
||||
// Recupera el "ángulo equivalente" de un body en movimiento (para zigzag).
|
||||
// Si está parado, devuelve 0.
|
||||
auto velocityToAngle(const Vec2& velocity) -> float {
|
||||
if (velocity.lengthSquared() < 0.0001F) {
|
||||
return 0.0F;
|
||||
// Random float [0..1).
|
||||
auto randFloat01() -> float {
|
||||
return static_cast<float>(std::rand()) / static_cast<float>(RAND_MAX);
|
||||
}
|
||||
// El movimiento (vx, vy) corresponde a angle - PI/2; invertimos.
|
||||
return std::atan2(velocity.y, velocity.x) + (Constants::PI / 2.0F);
|
||||
|
||||
// Random float [min..max).
|
||||
auto randRange(float min, float max) -> float {
|
||||
return min + (randFloat01() * (max - min));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Enemy::Enemy(Rendering::Renderer* renderer)
|
||||
: Entity(renderer),
|
||||
|
||||
tracking_strength_(Defaults::Enemies::Square::TRACKING_STRENGTH) {
|
||||
: Entity(renderer) {
|
||||
brightness_ = Defaults::Brightness::ENEMIC;
|
||||
|
||||
// Configuración del cuerpo físico — defaults para enemy genérico.
|
||||
// init() ajusta velocidad y masa según el tipo (Pentagon/Quadrat/Molinillo).
|
||||
body_.setMass(Defaults::Enemies::Body::DEFAULT_MASS);
|
||||
body_.radius = 0.0F; // 0 hasta spawn (no colisiona inactivo)
|
||||
body_.restitution = Defaults::Enemies::Body::RESTITUTION;
|
||||
body_.linear_damping = Defaults::Enemies::Body::LINEAR_DAMPING;
|
||||
body_.angular_damping = Defaults::Enemies::Body::ANGULAR_DAMPING;
|
||||
// Body queda amb defaults inocus (radius=0 = no col·lisiona) fins
|
||||
// que init() apliqui la configuració del tipus carregada via Registry.
|
||||
body_.radius = 0.0F;
|
||||
}
|
||||
|
||||
void Enemy::init(EnemyType type, const Vec2* ship_pos) {
|
||||
type_ = type;
|
||||
config_ = &EnemyRegistry::get(type);
|
||||
const EnemyConfig& cfg = *config_;
|
||||
|
||||
const char* shape_file = nullptr;
|
||||
float base_speed = 0.0F;
|
||||
float rotation_delta_min = 0.0F;
|
||||
float rotation_delta_max = 0.0F;
|
||||
float type_mass = Defaults::Enemies::Body::DEFAULT_MASS;
|
||||
ai_state_ = EnemyAiState{};
|
||||
ai_state_.tracking_strength = cfg.ai.movement.tracking_strength;
|
||||
|
||||
switch (type_) {
|
||||
case EnemyType::PENTAGON:
|
||||
shape_file = Defaults::Enemies::Pentagon::SHAPE_FILE;
|
||||
base_speed = Defaults::Enemies::Pentagon::SPEED;
|
||||
rotation_delta_min = Defaults::Enemies::Pentagon::ROTATION_DELTA_MIN;
|
||||
rotation_delta_max = Defaults::Enemies::Pentagon::ROTATION_DELTA_MAX;
|
||||
type_mass = Defaults::Enemies::Pentagon::MASS;
|
||||
break;
|
||||
|
||||
case EnemyType::SQUARE:
|
||||
shape_file = Defaults::Enemies::Square::SHAPE_FILE;
|
||||
base_speed = Defaults::Enemies::Square::SPEED;
|
||||
rotation_delta_min = Defaults::Enemies::Square::ROTATION_DELTA_MIN;
|
||||
rotation_delta_max = Defaults::Enemies::Square::ROTATION_DELTA_MAX;
|
||||
type_mass = Defaults::Enemies::Square::MASS;
|
||||
tracking_timer_ = 0.0F;
|
||||
break;
|
||||
|
||||
case EnemyType::PINWHEEL:
|
||||
shape_file = Defaults::Enemies::Pinwheel::SHAPE_FILE;
|
||||
base_speed = Defaults::Enemies::Pinwheel::SPEED;
|
||||
rotation_delta_min = Defaults::Enemies::Pinwheel::ROTATION_DELTA_MIN;
|
||||
rotation_delta_max = Defaults::Enemies::Pinwheel::ROTATION_DELTA_MAX;
|
||||
type_mass = Defaults::Enemies::Pinwheel::MASS;
|
||||
break;
|
||||
|
||||
default:
|
||||
std::cerr << "[Enemy] Error: tipo desconocido ("
|
||||
<< static_cast<int>(type_) << "), usando PENTAGON\n";
|
||||
shape_file = Defaults::Enemies::Pentagon::SHAPE_FILE;
|
||||
base_speed = Defaults::Enemies::Pentagon::SPEED;
|
||||
rotation_delta_min = Defaults::Enemies::Pentagon::ROTATION_DELTA_MIN;
|
||||
rotation_delta_max = Defaults::Enemies::Pentagon::ROTATION_DELTA_MAX;
|
||||
break;
|
||||
// Timers paral·lels a tick: random [0, interval) per evitar que tots els
|
||||
// enemics del mateix tipus disparin sincronitzats al spawn.
|
||||
ai_tick_timers_.resize(cfg.ai.tick.size());
|
||||
for (std::size_t i = 0; i < cfg.ai.tick.size(); ++i) {
|
||||
ai_tick_timers_[i] = randFloat01() * cfg.ai.tick[i].interval;
|
||||
}
|
||||
|
||||
body_.setMass(type_mass);
|
||||
body_.radius = Defaults::Entities::ENEMY_RADIUS;
|
||||
|
||||
// Cargar shape
|
||||
shape_ = Graphics::ShapeLoader::load(shape_file);
|
||||
shape_ = Graphics::ShapeLoader::load(cfg.shape.path);
|
||||
if (!shape_ || !shape_->isValid()) {
|
||||
std::cerr << "[Enemy] Error: no se ha podido cargar " << shape_file << '\n';
|
||||
std::cerr << "[Enemy] Error: no se ha podido cargar " << cfg.shape.path << '\n';
|
||||
}
|
||||
|
||||
// Posición aleatoria con comprobación de seguridad
|
||||
// Radi de col·lisió derivat del cercle circumscrit de la shape.
|
||||
const float BOUNDING = (shape_ != nullptr) ? shape_->getBoundingRadius() : 0.0F;
|
||||
collision_radius_ = BOUNDING * cfg.shape.scale * cfg.shape.collision_factor;
|
||||
|
||||
body_.setMass(cfg.physics.mass);
|
||||
body_.radius = collision_radius_;
|
||||
body_.restitution = cfg.physics.restitution;
|
||||
body_.linear_damping = cfg.physics.linear_damping;
|
||||
body_.angular_damping = cfg.physics.angular_damping;
|
||||
|
||||
// Posició aleatòria amb comprovació de safety_distance.
|
||||
float min_x;
|
||||
float max_x;
|
||||
float min_y;
|
||||
float max_y;
|
||||
Constants::getSafePlayAreaBounds(Defaults::Entities::ENEMY_RADIUS, min_x, max_x, min_y, max_y);
|
||||
Constants::getSafePlayAreaBounds(collision_radius_, min_x, max_x, min_y, max_y);
|
||||
|
||||
if (ship_pos != nullptr) {
|
||||
bool found_safe_position = false;
|
||||
for (int attempt = 0; attempt < Defaults::Enemies::Spawn::MAX_SPAWN_ATTEMPTS; attempt++) {
|
||||
float candidate_x;
|
||||
float candidate_y;
|
||||
if (attemptSafeSpawn(*ship_pos, candidate_x, candidate_y)) {
|
||||
if (attemptSafeSpawn(*ship_pos, collision_radius_, cfg.spawn.safety_distance, candidate_x, candidate_y)) {
|
||||
center_.x = candidate_x;
|
||||
center_.y = candidate_y;
|
||||
found_safe_position = true;
|
||||
@@ -141,33 +113,28 @@ void Enemy::init(EnemyType type, const Vec2* ship_pos) {
|
||||
center_.y = static_cast<float>((std::rand() % RANGE_Y) + static_cast<int>(min_y));
|
||||
}
|
||||
|
||||
// Dirección inicial aleatoria, velocidad escalar según tipo
|
||||
const float ANGLE_INICIAL = (std::rand() % 360) * Constants::PI / 180.0F;
|
||||
setVelocityFromAngle(ANGLE_INICIAL, base_speed);
|
||||
const float ANGLE_INICIAL = static_cast<float>(std::rand() % 360) * Constants::PI / 180.0F;
|
||||
setVelocityFromAngle(ANGLE_INICIAL, cfg.physics.speed);
|
||||
|
||||
// Sincronizar body_ con posición inicial
|
||||
body_.position = center_;
|
||||
body_.angle = 0.0F;
|
||||
body_.angular_velocity = 0.0F;
|
||||
body_.clearAccumulators();
|
||||
|
||||
// Rotación visual aleatoria (independiente del body)
|
||||
const float ROTATION_DELTA_RANGE = rotation_delta_max - rotation_delta_min;
|
||||
rotation_delta_ = rotation_delta_min + ((static_cast<float>(std::rand()) / static_cast<float>(RAND_MAX)) * ROTATION_DELTA_RANGE);
|
||||
// Rotació visual aleatòria dins del rang del tipus
|
||||
rotation_delta_ = randRange(cfg.physics.rotation_delta_min, cfg.physics.rotation_delta_max);
|
||||
rotation_ = 0.0F;
|
||||
|
||||
// Estado de animación
|
||||
animation_ = EnemyAnimation();
|
||||
animation_.rotation_delta_base = rotation_delta_;
|
||||
animation_.rotation_delta_target = rotation_delta_;
|
||||
animation_.rotation_delta_t = 1.0F;
|
||||
|
||||
// Invulnerabilidad post-spawn
|
||||
invulnerability_timer_ = Defaults::Enemies::Spawn::INVULNERABILITY_DURATION;
|
||||
brightness_ = Defaults::Enemies::Spawn::INVULNERABILITY_BRIGHTNESS_START;
|
||||
invulnerability_timer_ = cfg.spawn.invulnerability_duration;
|
||||
brightness_ = cfg.spawn.invulnerability_brightness_start;
|
||||
|
||||
// Timer para próximo cambio de dirección (Pentagon)
|
||||
direction_change_timer_ = 0.0F;
|
||||
health_ = cfg.health;
|
||||
flash_timer_ = 0.0F;
|
||||
|
||||
is_active_ = true;
|
||||
}
|
||||
@@ -177,8 +144,6 @@ void Enemy::update(float delta_time) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Decremento de timer "herido"; al cruzar 0 marca expiración para que el
|
||||
// system layer dispare la explosión diferida.
|
||||
wound_expired_this_frame_ = false;
|
||||
if (wounded_timer_ > 0.0F) {
|
||||
wounded_timer_ -= delta_time;
|
||||
@@ -188,45 +153,33 @@ void Enemy::update(float delta_time) {
|
||||
}
|
||||
}
|
||||
|
||||
// Decremento de invulnerabilidad + LERP de brightness
|
||||
if (flash_timer_ > 0.0F) {
|
||||
flash_timer_ -= delta_time;
|
||||
flash_timer_ = std::max(flash_timer_, 0.0F);
|
||||
}
|
||||
|
||||
if (invulnerability_timer_ > 0.0F) {
|
||||
invulnerability_timer_ -= delta_time;
|
||||
invulnerability_timer_ = std::max(invulnerability_timer_, 0.0F);
|
||||
|
||||
const float T_INV = invulnerability_timer_ / Defaults::Enemies::Spawn::INVULNERABILITY_DURATION;
|
||||
const float T_INV = invulnerability_timer_ / config_->spawn.invulnerability_duration;
|
||||
const float T = 1.0F - T_INV;
|
||||
const float SMOOTH_T = T * T * (3.0F - (2.0F * T));
|
||||
constexpr float START = Defaults::Enemies::Spawn::INVULNERABILITY_BRIGHTNESS_START;
|
||||
constexpr float END = Defaults::Enemies::Spawn::INVULNERABILITY_BRIGHTNESS_END;
|
||||
const float START = config_->spawn.invulnerability_brightness_start;
|
||||
const float END = config_->spawn.invulnerability_brightness_end;
|
||||
brightness_ = START + ((END - START) * SMOOTH_T);
|
||||
}
|
||||
|
||||
// Comportamiento por tipo (ajusta body_.velocity, NO mueve posición).
|
||||
// Skip cuando está herido: el enemy és un "cos mort" inert, només
|
||||
// respon a la inèrcia del impulse rebut i a les col·lisions físiques.
|
||||
if (!isWounded()) {
|
||||
switch (type_) {
|
||||
case EnemyType::PENTAGON:
|
||||
behaviorPentagon(delta_time);
|
||||
break;
|
||||
case EnemyType::SQUARE:
|
||||
behaviorSquare(delta_time);
|
||||
break;
|
||||
case EnemyType::PINWHEEL:
|
||||
behaviorPinwheel(delta_time);
|
||||
break;
|
||||
}
|
||||
}
|
||||
// El moviment es delega a Systems::EnemyAi::tick, invocat des de l'scene
|
||||
// ABANS d'aquest update (manté l'ordre: AI escriu velocity/rotation_delta,
|
||||
// després animation pot modular rotation_delta via rotation_accel).
|
||||
|
||||
// Animaciones (palpitación + rotación acelerada)
|
||||
updateAnimation(delta_time);
|
||||
|
||||
// Rotación visual (decoración, no afecta movimiento)
|
||||
rotation_ += rotation_delta_ * delta_time;
|
||||
}
|
||||
|
||||
void Enemy::postUpdate(float /*delta_time*/) {
|
||||
// Sincronizar mirror tras la integración del world.
|
||||
if (is_active_) {
|
||||
center_ = body_.position;
|
||||
}
|
||||
@@ -236,48 +189,42 @@ void Enemy::draw() const {
|
||||
if (!is_active_ || !shape_) {
|
||||
return;
|
||||
}
|
||||
const float SCALE = computeCurrentScale();
|
||||
SDL_Color color{};
|
||||
switch (type_) {
|
||||
case EnemyType::PENTAGON:
|
||||
color = Defaults::Palette::PENTAGON;
|
||||
break;
|
||||
case EnemyType::SQUARE:
|
||||
color = Defaults::Palette::SQUARE;
|
||||
break;
|
||||
case EnemyType::PINWHEEL:
|
||||
color = Defaults::Palette::PINWHEEL;
|
||||
break;
|
||||
}
|
||||
const float SCALE = config_->shape.scale * computeCurrentScale();
|
||||
SDL_Color color = config_->colors.normal;
|
||||
|
||||
// Parpadeo dorado mientras está herido: alterna color de tipo ↔ dorado
|
||||
// a Wounded::BLINK_HZ usando el timer (fmod sobre el periodo).
|
||||
if (wounded_timer_ > 0.0F) {
|
||||
const float CYCLE = 1.0F / Defaults::Enemies::Wounded::BLINK_HZ;
|
||||
const float CYCLE = 1.0F / config_->wounded.blink_hz;
|
||||
const float T = std::fmod(wounded_timer_, CYCLE);
|
||||
if (T < (CYCLE / 2.0F)) {
|
||||
color = Defaults::Palette::WOUNDED;
|
||||
color = config_->colors.wounded;
|
||||
}
|
||||
}
|
||||
|
||||
Rendering::renderShape(renderer_, shape_, center_, rotation_, SCALE, 1.0F, brightness_, color);
|
||||
// Flash d'impacte parcial (HP>1): força el color a blanc i el brillo a
|
||||
// 1.0 durant la finestra de flash. Té prioritat sobre el blink wounded.
|
||||
float effective_brightness = brightness_;
|
||||
if (flash_timer_ > 0.0F) {
|
||||
color = SDL_Color{.r = 255, .g = 255, .b = 255, .a = 255};
|
||||
effective_brightness = 1.0F;
|
||||
}
|
||||
|
||||
Rendering::renderShape(renderer_, shape_, center_, rotation_, SCALE, 1.0F, effective_brightness, color);
|
||||
}
|
||||
|
||||
void Enemy::destroy() {
|
||||
is_active_ = false;
|
||||
body_.velocity = Vec2{};
|
||||
body_.angular_velocity = 0.0F;
|
||||
body_.radius = 0.0F; // No colisiona mientras está inactivo
|
||||
body_.radius = 0.0F;
|
||||
wounded_timer_ = 0.0F;
|
||||
wound_expired_this_frame_ = false;
|
||||
last_hit_by_ = 0xFF;
|
||||
flash_timer_ = 0.0F;
|
||||
}
|
||||
|
||||
void Enemy::hurt(uint8_t shooter_id) {
|
||||
wounded_timer_ = Defaults::Enemies::Wounded::DURATION;
|
||||
wounded_timer_ = config_->wounded.duration;
|
||||
last_hit_by_ = shooter_id;
|
||||
// El so HIT ara el reprodueix la bala quan es trenca en debris
|
||||
// (Systems::Collision::breakBullet), no l'enemic en entrar a HURT.
|
||||
}
|
||||
|
||||
void Enemy::applyImpulse(const Vec2& impulse) {
|
||||
@@ -285,13 +232,11 @@ void Enemy::applyImpulse(const Vec2& impulse) {
|
||||
}
|
||||
|
||||
void Enemy::setVelocity(float speed) {
|
||||
// Mantener la dirección actual del body, cambiar solo la magnitud.
|
||||
const float CURRENT_SPEED = body_.velocity.length();
|
||||
if (CURRENT_SPEED > 0.0F) {
|
||||
body_.velocity = body_.velocity * (speed / CURRENT_SPEED);
|
||||
} else {
|
||||
// Sin dirección actual: usar ángulo aleatorio
|
||||
const float A = (std::rand() % 360) * Constants::PI / 180.0F;
|
||||
const float A = static_cast<float>(std::rand() % 360) * Constants::PI / 180.0F;
|
||||
setVelocityFromAngle(A, speed);
|
||||
}
|
||||
}
|
||||
@@ -300,109 +245,32 @@ void Enemy::setVelocityFromAngle(float angle_movement, float speed) {
|
||||
body_.velocity = angleToDirection(angle_movement) * speed;
|
||||
}
|
||||
|
||||
// PENTAGON: zigzag esquivador. Cambios de dirección periódicos (probabilísticos)
|
||||
// en lugar de detectar paredes; el rebote contra muros lo hace PhysicsWorld
|
||||
// con restitution=1.0.
|
||||
void Enemy::behaviorPentagon(float delta_time) {
|
||||
direction_change_timer_ += delta_time;
|
||||
|
||||
// Probabilidad de zigzag por segundo (calibrada para sensación equivalente
|
||||
// a la versión vieja que disparaba en cada toque de pared).
|
||||
const float RAND_VAL = static_cast<float>(std::rand()) / static_cast<float>(RAND_MAX);
|
||||
if (RAND_VAL < Defaults::Enemies::Pentagon::ZIGZAG_PROB_PER_SECOND * delta_time) {
|
||||
const float CURRENT_ANGLE = velocityToAngle(body_.velocity);
|
||||
const float DELTA = (static_cast<float>(std::rand()) / static_cast<float>(RAND_MAX)) *
|
||||
Defaults::Enemies::Pentagon::ANGLE_CHANGE_MAX;
|
||||
const float NEW_ANGLE = CURRENT_ANGLE + ((std::rand() % 2 == 0) ? DELTA : -DELTA);
|
||||
const float SPEED = body_.velocity.length();
|
||||
setVelocityFromAngle(NEW_ANGLE, SPEED);
|
||||
direction_change_timer_ = 0.0F;
|
||||
}
|
||||
}
|
||||
|
||||
// SQUARE: tracking discreto cada TRACKING_INTERVAL. Ajusta dirección
|
||||
// hacia el ship mezclando con tracking_strength_.
|
||||
void Enemy::behaviorSquare(float delta_time) {
|
||||
tracking_timer_ += delta_time;
|
||||
|
||||
if (tracking_timer_ >= Defaults::Enemies::Square::TRACKING_INTERVAL && ship_position_ != nullptr) {
|
||||
tracking_timer_ = 0.0F;
|
||||
|
||||
const Vec2 TO_SHIP = *ship_position_ - center_;
|
||||
const float DIST = TO_SHIP.length();
|
||||
if (DIST > 0.0F) {
|
||||
const Vec2 DESIRED_DIR = TO_SHIP / DIST;
|
||||
const float SPEED = body_.velocity.length();
|
||||
const Vec2 DESIRED_VEL = DESIRED_DIR * SPEED;
|
||||
|
||||
// Mezcla LERP: velocidad actual con la deseada según tracking_strength_.
|
||||
body_.velocity = (body_.velocity * (1.0F - tracking_strength_)) +
|
||||
(DESIRED_VEL * tracking_strength_);
|
||||
|
||||
// Renormalizar a la velocidad escalar original
|
||||
const float NEW_SPEED = body_.velocity.length();
|
||||
if (NEW_SPEED > 0.0F) {
|
||||
body_.velocity = body_.velocity * (SPEED / NEW_SPEED);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// PINWHEEL: movimiento recto + boost de rotación visual cerca del ship.
|
||||
// Sin tracking — solo cambios de dirección raros (igual que Pentagon pero
|
||||
// con probabilidad mucho menor).
|
||||
void Enemy::behaviorPinwheel(float /*delta_time*/) {
|
||||
// Boost de rotación visual por proximidad al ship
|
||||
if (ship_position_ != nullptr) {
|
||||
const Vec2 TO_SHIP = *ship_position_ - center_;
|
||||
const float DIST = TO_SHIP.length();
|
||||
if (DIST < Defaults::Enemies::Pinwheel::PROXIMITY_DISTANCE) {
|
||||
rotation_delta_ = animation_.rotation_delta_base * Defaults::Enemies::Pinwheel::ROTATION_DELTA_PROXIMITY_MULTIPLIER;
|
||||
} else {
|
||||
rotation_delta_ = animation_.rotation_delta_base;
|
||||
}
|
||||
}
|
||||
// Movimiento lineal puro: el world se encarga de integrar y rebotar.
|
||||
}
|
||||
|
||||
void Enemy::updateAnimation(float delta_time) {
|
||||
updatePulse(delta_time);
|
||||
updateRotationAcceleration(delta_time);
|
||||
}
|
||||
|
||||
void Enemy::updatePulse(float delta_time) {
|
||||
const auto& cfg = config_->animation.pulse;
|
||||
if (animation_.pulse_active) {
|
||||
animation_.pulse_phase += 2.0F * Constants::PI * animation_.pulse_frequency * delta_time;
|
||||
animation_.pulse_time_remaining -= delta_time;
|
||||
if (animation_.pulse_time_remaining <= 0.0F) {
|
||||
animation_.pulse_active = false;
|
||||
}
|
||||
} else {
|
||||
const float RAND_VAL = static_cast<float>(std::rand()) / static_cast<float>(RAND_MAX);
|
||||
const float TRIGGER_PROB = Defaults::Enemies::Animation::PULSE_TRIGGER_PROB * delta_time;
|
||||
if (RAND_VAL < TRIGGER_PROB) {
|
||||
return;
|
||||
}
|
||||
if (randFloat01() < cfg.trigger_prob_per_second * delta_time) {
|
||||
animation_.pulse_active = true;
|
||||
animation_.pulse_phase = 0.0F;
|
||||
|
||||
const float FREQ_RANGE = Defaults::Enemies::Animation::PULSE_FREQ_MAX -
|
||||
Defaults::Enemies::Animation::PULSE_FREQ_MIN;
|
||||
animation_.pulse_frequency = Defaults::Enemies::Animation::PULSE_FREQ_MIN +
|
||||
((static_cast<float>(std::rand()) / static_cast<float>(RAND_MAX)) * FREQ_RANGE);
|
||||
|
||||
const float AMP_RANGE = Defaults::Enemies::Animation::PULSE_AMPLITUD_MAX -
|
||||
Defaults::Enemies::Animation::PULSE_AMPLITUD_MIN;
|
||||
animation_.pulse_amplitude = Defaults::Enemies::Animation::PULSE_AMPLITUD_MIN +
|
||||
((static_cast<float>(std::rand()) / static_cast<float>(RAND_MAX)) * AMP_RANGE);
|
||||
|
||||
const float DUR_RANGE = Defaults::Enemies::Animation::PULSE_DURATION_MAX -
|
||||
Defaults::Enemies::Animation::PULSE_DURATION_MIN;
|
||||
animation_.pulse_time_remaining = Defaults::Enemies::Animation::PULSE_DURATION_MIN +
|
||||
((static_cast<float>(std::rand()) / static_cast<float>(RAND_MAX)) * DUR_RANGE);
|
||||
}
|
||||
animation_.pulse_frequency = randRange(cfg.frequency_min, cfg.frequency_max);
|
||||
animation_.pulse_amplitude = randRange(cfg.amplitude_min, cfg.amplitude_max);
|
||||
animation_.pulse_time_remaining = randRange(cfg.duration_min, cfg.duration_max);
|
||||
}
|
||||
}
|
||||
|
||||
void Enemy::updateRotationAcceleration(float delta_time) {
|
||||
const auto& cfg = config_->animation.rotation_accel;
|
||||
if (animation_.rotation_delta_t < 1.0F) {
|
||||
animation_.rotation_delta_t += delta_time / animation_.rotation_delta_duration;
|
||||
if (animation_.rotation_delta_t >= 1.0F) {
|
||||
@@ -416,34 +284,24 @@ void Enemy::updateRotationAcceleration(float delta_time) {
|
||||
const float TARGET = animation_.rotation_delta_target;
|
||||
rotation_delta_ = INITIAL + ((TARGET - INITIAL) * SMOOTH_T);
|
||||
}
|
||||
} else {
|
||||
const float RAND_VAL = static_cast<float>(std::rand()) / static_cast<float>(RAND_MAX);
|
||||
const float TRIGGER_PROB = Defaults::Enemies::Animation::ROTATION_ACCEL_TRIGGER_PROB * delta_time;
|
||||
if (RAND_VAL < TRIGGER_PROB) {
|
||||
animation_.rotation_delta_t = 0.0F;
|
||||
|
||||
const float MULT_RANGE = Defaults::Enemies::Animation::ROTATION_ACCEL_MULTIPLIER_MAX -
|
||||
Defaults::Enemies::Animation::ROTATION_ACCEL_MULTIPLIER_MIN;
|
||||
const float MULTIPLIER = Defaults::Enemies::Animation::ROTATION_ACCEL_MULTIPLIER_MIN +
|
||||
((static_cast<float>(std::rand()) / static_cast<float>(RAND_MAX)) * MULT_RANGE);
|
||||
animation_.rotation_delta_target = animation_.rotation_delta_base * MULTIPLIER;
|
||||
|
||||
const float DUR_RANGE = Defaults::Enemies::Animation::ROTATION_ACCEL_DURATION_MAX -
|
||||
Defaults::Enemies::Animation::ROTATION_ACCEL_DURATION_MIN;
|
||||
animation_.rotation_delta_duration = Defaults::Enemies::Animation::ROTATION_ACCEL_DURATION_MIN +
|
||||
((static_cast<float>(std::rand()) / static_cast<float>(RAND_MAX)) * DUR_RANGE);
|
||||
return;
|
||||
}
|
||||
if (randFloat01() < cfg.trigger_prob_per_second * delta_time) {
|
||||
animation_.rotation_delta_t = 0.0F;
|
||||
const float MULTIPLIER = randRange(cfg.multiplier_min, cfg.multiplier_max);
|
||||
animation_.rotation_delta_target = animation_.rotation_delta_base * MULTIPLIER;
|
||||
animation_.rotation_delta_duration = randRange(cfg.duration_min, cfg.duration_max);
|
||||
}
|
||||
}
|
||||
|
||||
auto Enemy::computeCurrentScale() const -> float {
|
||||
float scale = 1.0F;
|
||||
if (invulnerability_timer_ > 0.0F) {
|
||||
const float T_INV = invulnerability_timer_ / Defaults::Enemies::Spawn::INVULNERABILITY_DURATION;
|
||||
const float T_INV = invulnerability_timer_ / config_->spawn.invulnerability_duration;
|
||||
const float T = 1.0F - T_INV;
|
||||
const float SMOOTH_T = T * T * (3.0F - (2.0F * T));
|
||||
constexpr float START = Defaults::Enemies::Spawn::INVULNERABILITY_SCALE_START;
|
||||
constexpr float END = Defaults::Enemies::Spawn::INVULNERABILITY_SCALE_END;
|
||||
const float START = config_->spawn.invulnerability_scale_start;
|
||||
const float END = config_->spawn.invulnerability_scale_end;
|
||||
scale = START + ((END - START) * SMOOTH_T);
|
||||
} else if (animation_.pulse_active) {
|
||||
scale += animation_.pulse_amplitude * std::sin(animation_.pulse_phase);
|
||||
@@ -452,16 +310,7 @@ auto Enemy::computeCurrentScale() const -> float {
|
||||
}
|
||||
|
||||
auto Enemy::getBaseVelocity() const -> float {
|
||||
switch (type_) {
|
||||
case EnemyType::PENTAGON:
|
||||
return Defaults::Enemies::Pentagon::SPEED;
|
||||
case EnemyType::SQUARE:
|
||||
return Defaults::Enemies::Square::SPEED;
|
||||
case EnemyType::PINWHEEL:
|
||||
return Defaults::Enemies::Pinwheel::SPEED;
|
||||
default:
|
||||
return Defaults::Enemies::Pentagon::SPEED;
|
||||
}
|
||||
return EnemyRegistry::get(type_).physics.speed;
|
||||
}
|
||||
|
||||
auto Enemy::getBaseRotation() const -> float {
|
||||
@@ -470,16 +319,16 @@ auto Enemy::getBaseRotation() const -> float {
|
||||
|
||||
void Enemy::setTrackingStrength(float strength) {
|
||||
if (type_ == EnemyType::SQUARE) {
|
||||
tracking_strength_ = strength;
|
||||
ai_state_.tracking_strength = strength;
|
||||
}
|
||||
}
|
||||
|
||||
auto Enemy::attemptSafeSpawn(const Vec2& ship_pos, float& out_x, float& out_y) -> bool {
|
||||
auto Enemy::attemptSafeSpawn(const Vec2& ship_pos, float collision_radius, float safety_distance, float& out_x, float& out_y) -> bool {
|
||||
float min_x;
|
||||
float max_x;
|
||||
float min_y;
|
||||
float max_y;
|
||||
Constants::getSafePlayAreaBounds(Defaults::Entities::ENEMY_RADIUS, min_x, max_x, min_y, max_y);
|
||||
Constants::getSafePlayAreaBounds(collision_radius, min_x, max_x, min_y, max_y);
|
||||
|
||||
const int RANGE_X = static_cast<int>(max_x - min_x);
|
||||
const int RANGE_Y = static_cast<int>(max_y - min_y);
|
||||
@@ -489,5 +338,5 @@ auto Enemy::attemptSafeSpawn(const Vec2& ship_pos, float& out_x, float& out_y) -
|
||||
const float DX = out_x - ship_pos.x;
|
||||
const float DY = out_y - ship_pos.y;
|
||||
const float DISTANCE = std::sqrt((DX * DX) + (DY * DY));
|
||||
return DISTANCE >= Defaults::Enemies::Spawn::SAFETY_DISTANCE;
|
||||
return DISTANCE >= safety_distance;
|
||||
}
|
||||
|
||||
@@ -4,19 +4,29 @@
|
||||
#pragma once
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
#include "core/defaults.hpp"
|
||||
#include "core/defaults/enemies.hpp"
|
||||
#include "core/entities/entity.hpp"
|
||||
#include "core/types.hpp"
|
||||
#include "game/entities/enemy_ai.hpp"
|
||||
|
||||
class Ship;
|
||||
|
||||
// Tipo de enemy
|
||||
enum class EnemyType : uint8_t {
|
||||
PENTAGON = 0, // Pentágono esquivador (zigzag)
|
||||
SQUARE = 1, // Square perseguidor (tracks ship)
|
||||
PINWHEEL = 2 // Molinillo agresivo (rápido, girando)
|
||||
PINWHEEL = 2, // Molinillo agresivo (rápido, girando)
|
||||
STAR = 3, // Estrella de 5 puntes (clone visual de Pentagon, comportament zigzag)
|
||||
ORB = 4, // Orb gegant tough (HP=10, chase lent — primer enemic HP>1)
|
||||
};
|
||||
|
||||
// Forward declaration — EnemyConfig viu a enemy_config.hpp i s'inclou només a enemy.cpp.
|
||||
struct EnemyConfig;
|
||||
|
||||
// Estado de animación (palpitación + rotación acelerada)
|
||||
struct EnemyAnimation {
|
||||
// Palpitación (efecto respiración)
|
||||
@@ -48,10 +58,8 @@ class Enemy : public Entities::Entity {
|
||||
// Override: Interfaz de Entity
|
||||
[[nodiscard]] auto isActive() const -> bool override { return is_active_; }
|
||||
|
||||
// Override: Interfaz de colisión
|
||||
[[nodiscard]] auto getCollisionRadius() const -> float override {
|
||||
return Defaults::Entities::ENEMY_RADIUS;
|
||||
}
|
||||
// Override: Interfaz de colisión. El radi ve del config carregat per tipus.
|
||||
[[nodiscard]] auto getCollisionRadius() const -> float override { return collision_radius_; }
|
||||
// Mentre fa spawn (invulnerable) segueix col·lisionant: les bales el
|
||||
// poden abatre i el cos físic rebota amb la nau. El damage a la nau
|
||||
// segueix filtrat per `isInvulnerable()` al detectShipEnemy.
|
||||
@@ -65,9 +73,22 @@ class Enemy : public Entities::Entity {
|
||||
// Getters
|
||||
[[nodiscard]] auto getRotationDelta() const -> float { return rotation_delta_; }
|
||||
[[nodiscard]] auto getVelocityVector() const -> Vec2 { return body_.velocity; }
|
||||
// Configuració activa (carregada al darrer init()). Vàlida mentre l'enemic
|
||||
// ha estat inicialitzat almenys un cop; abans és nullptr.
|
||||
[[nodiscard]] auto getConfig() const -> const EnemyConfig& { return *config_; }
|
||||
|
||||
// Set ship position reference for tracking behavior
|
||||
void setShipPosition(const Vec2* ship_pos) { ship_position_ = ship_pos; }
|
||||
// Referències als 2 ships per a AI de tracking/proximity/chase/flee.
|
||||
// nullptr = ship inexistent al match. El sistema d'IA filtra per ship->isActive().
|
||||
void setShips(const Ship* p1, const Ship* p2) { ships_ = {p1, p2}; }
|
||||
[[nodiscard]] auto getShips() const -> const std::array<const Ship*, 2>& { return ships_; }
|
||||
|
||||
// Accessors per al sistema d'IA (Systems::EnemyAi).
|
||||
[[nodiscard]] auto getAiState() -> EnemyAiState& { return ai_state_; }
|
||||
[[nodiscard]] auto getAiTickTimers() -> std::vector<float>& { return ai_tick_timers_; }
|
||||
[[nodiscard]] auto getRotationBase() const -> float { return animation_.rotation_delta_base; }
|
||||
void setRotationDelta(float rot) { rotation_delta_ = rot; }
|
||||
// Public: el sistema d'IA reorienta la velocitat des d'un angle.
|
||||
void setVelocityFromAngle(float angle_movement, float speed);
|
||||
|
||||
// Stage system API (base stats)
|
||||
[[nodiscard]] auto getBaseVelocity() const -> float;
|
||||
@@ -97,46 +118,73 @@ class Enemy : public Entities::Entity {
|
||||
void consumeWoundExpired() { wound_expired_this_frame_ = false; }
|
||||
[[nodiscard]] auto getLastHitBy() const -> uint8_t { return last_hit_by_; }
|
||||
|
||||
// Salut: decrementada per l'acció DECREASE_HEALTH al dispatcher d'events.
|
||||
// Quan arriba a 0 o menys, el dispatcher dispara ON_NO_HEALTH (que
|
||||
// típicament encadena SET_HURT o DESTROY al YAML). last_hit_by s'actualitza
|
||||
// al decrement perquè la mort posterior atribueixi correctament el kill.
|
||||
[[nodiscard]] auto getHealth() const -> int { return health_; }
|
||||
void decrementHealth(uint8_t shooter_id = 0xFF) {
|
||||
--health_;
|
||||
last_hit_by_ = shooter_id;
|
||||
}
|
||||
|
||||
// Flash visual: brief impacto-feedback quan rep un hit no letal (HP>1).
|
||||
// Disparat per l'acció FLASH; el render alça la lluminositat mentre dura.
|
||||
void triggerFlash() { flash_timer_ = Defaults::Enemies::Visual::FLASH_DURATION; }
|
||||
|
||||
// Aplica un impulso (cambio inmediato de velocidad mass-aware) al cuerpo físico.
|
||||
void applyImpulse(const Vec2& impulse);
|
||||
|
||||
private:
|
||||
// Miembros específicos (heredados: renderer_, shape_, center_, angle_, brightness_, body_).
|
||||
// Inicializados en la declaración: el ctor por defecto deja al enemy en estado "inactivo
|
||||
// como pentágono", coherente con lo que harán init() o el ctor con renderer al activarlo.
|
||||
float rotation_delta_{0.0F}; // Velocidad angular visual (rad/s) — solo decoración, separada de body_.angular_velocity
|
||||
float rotation_{0.0F}; // Rotación visual acumulada (no afecta movimiento)
|
||||
// Configuració carregada per tipus (apunta a una entrada de EnemyRegistry).
|
||||
// nullptr abans del primer init(); per això getConfig() només és vàlid post-init.
|
||||
const EnemyConfig* config_{nullptr};
|
||||
|
||||
// Cache local del radi (per evitar dereferenciar config_ a getCollisionRadius);
|
||||
// s'actualitza a init() segons el tipus.
|
||||
float collision_radius_{0.0F};
|
||||
|
||||
float rotation_delta_{0.0F}; // Velocidad angular visual (rad/s)
|
||||
float rotation_{0.0F}; // Rotación visual acumulada
|
||||
bool is_active_{false};
|
||||
|
||||
EnemyType type_{EnemyType::PENTAGON};
|
||||
EnemyAnimation animation_;
|
||||
|
||||
// Comportamiento type-specific
|
||||
float tracking_timer_{0.0F}; // Quadrat: tiempo desde último update de dirección
|
||||
const Vec2* ship_position_{nullptr}; // Puntero a posición de la nave (para tracking)
|
||||
float tracking_strength_{0.0F}; // Quadrat: intensidad de tracking (0.0-1.5), default 0.5
|
||||
float direction_change_timer_{0.0F}; // Pentagon: tiempo para próximo cambio de dirección
|
||||
// Estat per-instància que la primitiva de moviment manté entre frames.
|
||||
EnemyAiState ai_state_;
|
||||
|
||||
// Timers paral·lels a config_->ai.tick: timers_[i] és el temps restant
|
||||
// (en segons) fins a la pròxima execució de l'acció i. Re-dimensionat a
|
||||
// init() segons la mida de config_->ai.tick.
|
||||
std::vector<float> ai_tick_timers_;
|
||||
|
||||
// Referències als 2 ships per a AI de tracking/proximity/chase/flee.
|
||||
std::array<const Ship*, 2> ships_{nullptr, nullptr};
|
||||
|
||||
// Invulnerabilidad post-spawn
|
||||
float invulnerability_timer_{0.0F};
|
||||
|
||||
// Estado "herido": timer cuenta atrás; al cruzar 0 se marca expiración.
|
||||
// Estado "herido"
|
||||
float wounded_timer_{0.0F};
|
||||
bool wound_expired_this_frame_{false};
|
||||
uint8_t last_hit_by_{0xFF}; // 0xFF = sin atribución
|
||||
uint8_t last_hit_by_{0xFF};
|
||||
|
||||
// Salut per-instància. Reseteja a config_->health a init(); el dispatcher
|
||||
// d'events la decrementa via DECREASE_HEALTH i dispara ON_NO_HEALTH quan
|
||||
// creua zero. Permet enemics tough (HP>1) sense canvis al motor.
|
||||
int health_{1};
|
||||
|
||||
// Flash visual temporitzat per a feedback d'impacte parcial (HP>1).
|
||||
// L'acció FLASH el reseteja a FLASH_DURATION; draw() alça la lluminositat
|
||||
// mentre dura, i update() el decrementa.
|
||||
float flash_timer_{0.0F};
|
||||
|
||||
// Métodos privados
|
||||
void updateAnimation(float delta_time);
|
||||
void updatePulse(float delta_time);
|
||||
void updateRotationAcceleration(float delta_time);
|
||||
void behaviorPentagon(float delta_time);
|
||||
void behaviorSquare(float delta_time);
|
||||
void behaviorPinwheel(float delta_time);
|
||||
[[nodiscard]] auto computeCurrentScale() const -> float;
|
||||
// Estático: solo opera sobre ship_pos pasado; no consulta estado del enemy.
|
||||
static auto attemptSafeSpawn(const Vec2& ship_pos, float& out_x, float& out_y) -> bool;
|
||||
|
||||
// Helper: setear body_.velocity desde un ángulo y magnitud.
|
||||
// angle_movement=0 apunta hacia arriba (eje Y negativo SDL).
|
||||
void setVelocityFromAngle(float angle_movement, float speed);
|
||||
// Static: passa els paràmetres com a args per no acoblar a *this.
|
||||
static auto attemptSafeSpawn(const Vec2& ship_pos, float collision_radius, float safety_distance, float& out_x, float& out_y) -> bool;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
// enemy_ai.hpp - Sistema declaratiu d'IA per a enemics
|
||||
// © 2026 JailDesigner
|
||||
//
|
||||
// Cada enemic declara al seu YAML quin movement primitiu fa servir i, opcional-
|
||||
// ment, una llista d'accions periòdiques (tick). El motor només dispatcha; el
|
||||
// comportament viu a les dades. Patró paral·lel al d'events declaratius
|
||||
// (enemy_event.hpp).
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
// Primitiva de moviment activa per a un enemic. Substitueix el switch
|
||||
// hardcoded sobre EnemyType.
|
||||
enum class MovementType : uint8_t {
|
||||
ZIGZAG, // Canvi de direcció probabilístic agressiu (Pentagon/Star)
|
||||
TRACKING, // LERP discret cap al ship cada N segons (Square)
|
||||
RECTILINEAR_PROXIMITY, // Rectilini + boost rotació visual prop del ship (Pinwheel)
|
||||
WANDER, // Canvi de direcció probabilístic suau, sense target
|
||||
CHASE, // Steering continu cap al ship més proper
|
||||
FLEE, // Steering continu allunyant-se del ship més proper
|
||||
};
|
||||
|
||||
// Accions que s'executen periòdicament (un timer per acció). Futur (Fase C):
|
||||
// SHOOT amb aim_mode/jitter/bullet config.
|
||||
enum class AiActionType : uint8_t {
|
||||
SHOOT,
|
||||
};
|
||||
|
||||
enum class AimMode : uint8_t {
|
||||
RANDOM, // Angle uniformement aleatori
|
||||
AIMED, // atan2(nearest_ship - center) + soroll gaussià (jitter_rad)
|
||||
};
|
||||
|
||||
// Camps de tots els movements; només el subset rellevant per al type actiu
|
||||
// s'usa. Els altres queden a 0.0F. Mateixa filosofia que la BehaviorCfg
|
||||
// llegacy però amb el type explícit dins.
|
||||
struct MovementConfig {
|
||||
MovementType type{MovementType::ZIGZAG};
|
||||
|
||||
// ZIGZAG i WANDER (canvi de direcció probabilístic; comparteixen camps).
|
||||
float angle_change_max{0.0F};
|
||||
float zigzag_prob_per_second{0.0F};
|
||||
|
||||
// TRACKING
|
||||
float tracking_strength{0.0F};
|
||||
float tracking_interval{0.0F};
|
||||
|
||||
// RECTILINEAR_PROXIMITY
|
||||
float rotation_proximity_multiplier{0.0F};
|
||||
float proximity_distance{0.0F};
|
||||
|
||||
// CHASE / FLEE: força del steering per segon (LERP velocity ↔ direcció ideal).
|
||||
// 1.0 = en ~1s la velocitat queda totalment realineada cap al target.
|
||||
float chase_strength{0.0F};
|
||||
float flee_strength{0.0F};
|
||||
};
|
||||
|
||||
// Acció periòdica. interval = segons entre disparades; el dispatcher manté un
|
||||
// timer per acció (paral·lel a aquesta llista) i dispara quan arriba a 0.
|
||||
struct AiTickAction {
|
||||
AiActionType type{AiActionType::SHOOT};
|
||||
float interval{1.0F};
|
||||
AimMode aim_mode{AimMode::RANDOM};
|
||||
float jitter_rad{0.0F};
|
||||
float bullet_speed{200.0F}; // px/s; la magnitud la decideix l'enemic, no el bullet config
|
||||
std::string bullet_config_name; // bullet config a usar (lazy-load des de BulletRegistry)
|
||||
};
|
||||
|
||||
struct EnemyAiConfig {
|
||||
MovementConfig movement;
|
||||
std::vector<AiTickAction> tick;
|
||||
};
|
||||
|
||||
// Estat per-instància que la primitiva de moviment manté entre frames (timers
|
||||
// d'interval, contadors de canvi de direcció...). Es viu dins de Enemy i el
|
||||
// sistema d'IA hi escriu via getAiState().
|
||||
struct EnemyAiState {
|
||||
float direction_change_timer{0.0F}; // ZIGZAG
|
||||
float tracking_timer{0.0F}; // TRACKING
|
||||
float tracking_strength{0.0F}; // TRACKING (cau de cfg, mutable per dificultat)
|
||||
};
|
||||
@@ -0,0 +1,480 @@
|
||||
// enemy_config.cpp - Implementació del parser de EnemyConfig
|
||||
// © 2026 JailDesigner
|
||||
|
||||
#include "game/entities/enemy_config.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <exception>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
namespace {
|
||||
|
||||
auto parseColor(const fkyaml::node& node, SDL_Color& out) -> bool {
|
||||
if (!node.is_sequence() || node.size() != 3) {
|
||||
return false;
|
||||
}
|
||||
const auto R = node[0].get_value<uint32_t>();
|
||||
const auto G = node[1].get_value<uint32_t>();
|
||||
const auto B = node[2].get_value<uint32_t>();
|
||||
out = SDL_Color{
|
||||
.r = static_cast<uint8_t>(R),
|
||||
.g = static_cast<uint8_t>(G),
|
||||
.b = static_cast<uint8_t>(B),
|
||||
.a = 255};
|
||||
return true;
|
||||
}
|
||||
|
||||
auto aiTypeFromString(const std::string& s) -> std::optional<EnemyType> {
|
||||
if (s == "pentagon") { return EnemyType::PENTAGON; }
|
||||
if (s == "square") { return EnemyType::SQUARE; }
|
||||
if (s == "pinwheel") { return EnemyType::PINWHEEL; }
|
||||
if (s == "star") { return EnemyType::STAR; }
|
||||
if (s == "orb") { return EnemyType::ORB; }
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
// Cada parseXxx valida + omple la sub-struct corresponent. Retornen false
|
||||
// amb log si falta un camp requerit. Separar-los baixa la complexitat
|
||||
// cognitiva del fromYaml() principal.
|
||||
|
||||
auto parseAiType(const fkyaml::node& node, EnemyType expected, const std::string& name, EnemyType& out) -> bool {
|
||||
if (!node.contains("ai_type")) {
|
||||
std::cerr << "[EnemyConfig] Error: falta 'ai_type' a " << name << '\n';
|
||||
return false;
|
||||
}
|
||||
const auto AI_STR = node["ai_type"].get_value<std::string>();
|
||||
const auto PARSED = aiTypeFromString(AI_STR);
|
||||
if (!PARSED) {
|
||||
std::cerr << "[EnemyConfig] Error: ai_type desconegut '" << AI_STR << "' a " << name << '\n';
|
||||
return false;
|
||||
}
|
||||
if (*PARSED != expected) {
|
||||
std::cerr << "[EnemyConfig] Error: ai_type '" << AI_STR
|
||||
<< "' no coincideix amb el tipus esperat (per directori) a " << name << '\n';
|
||||
return false;
|
||||
}
|
||||
out = *PARSED;
|
||||
return true;
|
||||
}
|
||||
|
||||
auto parseShape(const fkyaml::node& node, const std::string& name, EnemyConfig::ShapeCfg& out) -> bool {
|
||||
if (!node.contains("shape") || !node["shape"].contains("path")) {
|
||||
std::cerr << "[EnemyConfig] Error: falta 'shape.path' a " << name << '\n';
|
||||
return false;
|
||||
}
|
||||
const auto& shape = node["shape"];
|
||||
out.path = shape["path"].get_value<std::string>();
|
||||
out.scale = shape.contains("scale") ? shape["scale"].get_value<float>() : 1.0F;
|
||||
out.collision_factor = shape.contains("collision_factor")
|
||||
? shape["collision_factor"].get_value<float>()
|
||||
: 1.0F;
|
||||
return true;
|
||||
}
|
||||
|
||||
auto parsePhysics(const fkyaml::node& node, const std::string& name, EnemyConfig::PhysicsCfg& out) -> bool {
|
||||
if (!node.contains("physics")) {
|
||||
std::cerr << "[EnemyConfig] Error: falta 'physics' a " << name << '\n';
|
||||
return false;
|
||||
}
|
||||
const auto& p = node["physics"];
|
||||
out.mass = p["mass"].get_value<float>();
|
||||
out.speed = p["speed"].get_value<float>();
|
||||
out.rotation_delta_min = p["rotation_delta_min"].get_value<float>();
|
||||
out.rotation_delta_max = p["rotation_delta_max"].get_value<float>();
|
||||
out.restitution = p["restitution"].get_value<float>();
|
||||
out.linear_damping = p["linear_damping"].get_value<float>();
|
||||
out.angular_damping = p["angular_damping"].get_value<float>();
|
||||
return true;
|
||||
}
|
||||
|
||||
auto parseAnimation(const fkyaml::node& node, const std::string& name, EnemyConfig::AnimationCfg& out) -> bool {
|
||||
if (!node.contains("animation") ||
|
||||
!node["animation"].contains("pulse") ||
|
||||
!node["animation"].contains("rotation_accel")) {
|
||||
std::cerr << "[EnemyConfig] Error: falta 'animation.pulse' o 'animation.rotation_accel' a " << name << '\n';
|
||||
return false;
|
||||
}
|
||||
const auto& p = node["animation"]["pulse"];
|
||||
out.pulse.trigger_prob_per_second = p["trigger_prob_per_second"].get_value<float>();
|
||||
out.pulse.duration_min = p["duration_min"].get_value<float>();
|
||||
out.pulse.duration_max = p["duration_max"].get_value<float>();
|
||||
out.pulse.amplitude_min = p["amplitude_min"].get_value<float>();
|
||||
out.pulse.amplitude_max = p["amplitude_max"].get_value<float>();
|
||||
out.pulse.frequency_min = p["frequency_min"].get_value<float>();
|
||||
out.pulse.frequency_max = p["frequency_max"].get_value<float>();
|
||||
|
||||
const auto& r = node["animation"]["rotation_accel"];
|
||||
out.rotation_accel.trigger_prob_per_second = r["trigger_prob_per_second"].get_value<float>();
|
||||
out.rotation_accel.duration_min = r["duration_min"].get_value<float>();
|
||||
out.rotation_accel.duration_max = r["duration_max"].get_value<float>();
|
||||
out.rotation_accel.multiplier_min = r["multiplier_min"].get_value<float>();
|
||||
out.rotation_accel.multiplier_max = r["multiplier_max"].get_value<float>();
|
||||
return true;
|
||||
}
|
||||
|
||||
auto parseWounded(const fkyaml::node& node, const std::string& name, EnemyConfig::WoundedCfg& out) -> bool {
|
||||
if (!node.contains("wounded")) {
|
||||
std::cerr << "[EnemyConfig] Error: falta 'wounded' a " << name << '\n';
|
||||
return false;
|
||||
}
|
||||
const auto& w = node["wounded"];
|
||||
out.duration = w["duration"].get_value<float>();
|
||||
out.blink_hz = w["blink_hz"].get_value<float>();
|
||||
return true;
|
||||
}
|
||||
|
||||
auto parseSpawn(const fkyaml::node& node, const std::string& name, EnemyConfig::SpawnCfg& out) -> bool {
|
||||
if (!node.contains("spawn")) {
|
||||
std::cerr << "[EnemyConfig] Error: falta 'spawn' a " << name << '\n';
|
||||
return false;
|
||||
}
|
||||
const auto& s = node["spawn"];
|
||||
out.invulnerability_duration = s["invulnerability_duration"].get_value<float>();
|
||||
out.invulnerability_brightness_start = s["invulnerability_brightness_start"].get_value<float>();
|
||||
out.invulnerability_brightness_end = s["invulnerability_brightness_end"].get_value<float>();
|
||||
out.invulnerability_scale_start = s["invulnerability_scale_start"].get_value<float>();
|
||||
out.invulnerability_scale_end = s["invulnerability_scale_end"].get_value<float>();
|
||||
out.safety_distance = s["safety_distance"].get_value<float>();
|
||||
return true;
|
||||
}
|
||||
|
||||
// Tots els camps de behavior són opcionals; només l'AI corresponent els consumeix.
|
||||
void parseBehavior(const fkyaml::node& node, EnemyConfig::BehaviorCfg& out) {
|
||||
if (!node.contains("behavior")) {
|
||||
return;
|
||||
}
|
||||
const auto& b = node["behavior"];
|
||||
const auto READ_OPT = [&b](const char* key, float& dst) {
|
||||
if (b.contains(key)) {
|
||||
dst = b[key].get_value<float>();
|
||||
}
|
||||
};
|
||||
READ_OPT("zigzag_prob_per_second", out.zigzag_prob_per_second);
|
||||
READ_OPT("angle_change_max", out.angle_change_max);
|
||||
READ_OPT("tracking_strength", out.tracking_strength);
|
||||
READ_OPT("tracking_interval", out.tracking_interval);
|
||||
READ_OPT("rotation_proximity_multiplier", out.rotation_proximity_multiplier);
|
||||
READ_OPT("proximity_distance", out.proximity_distance);
|
||||
}
|
||||
|
||||
auto parseColors(const fkyaml::node& node, const std::string& name, EnemyConfig::ColorsCfg& out) -> bool {
|
||||
if (!node.contains("colors") ||
|
||||
!parseColor(node["colors"]["normal"], out.normal) ||
|
||||
!parseColor(node["colors"]["wounded"], out.wounded)) {
|
||||
std::cerr << "[EnemyConfig] Error: 'colors.normal' / 'colors.wounded' no són [r,g,b] a "
|
||||
<< name << '\n';
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
auto parseScore(const fkyaml::node& node, const std::string& name, int& out) -> bool {
|
||||
if (!node.contains("score")) {
|
||||
std::cerr << "[EnemyConfig] Error: falta 'score' a " << name << '\n';
|
||||
return false;
|
||||
}
|
||||
out = node["score"].get_value<int>();
|
||||
return true;
|
||||
}
|
||||
|
||||
// health és opcional: si el YAML no l'inclou, el default {1} de l'struct
|
||||
// ja cobreix el comportament de tots els enemics actuals (1 hit → mort).
|
||||
void parseHealth(const fkyaml::node& node, int& out) {
|
||||
if (node.contains("health")) {
|
||||
out = node["health"].get_value<int>();
|
||||
}
|
||||
}
|
||||
|
||||
// Forward-decl: aimModeFromString viu més avall (junt amb la resta de
|
||||
// helpers d'AI) però parseActionList el necessita per al payload de
|
||||
// FIRE_BULLET. Evita reordenar tot el bloc.
|
||||
auto aimModeFromString(const std::string& s) -> std::optional<AimMode>;
|
||||
|
||||
auto actionTypeFromString(const std::string& s) -> std::optional<EnemyActionType> {
|
||||
if (s == "set_hurt") { return EnemyActionType::SET_HURT; }
|
||||
if (s == "destroy") { return EnemyActionType::DESTROY; }
|
||||
if (s == "add_score") { return EnemyActionType::ADD_SCORE; }
|
||||
if (s == "create_debris") { return EnemyActionType::CREATE_DEBRIS; }
|
||||
if (s == "create_debris_partial") { return EnemyActionType::CREATE_DEBRIS_PARTIAL; }
|
||||
if (s == "create_fireworks") { return EnemyActionType::CREATE_FIREWORKS; }
|
||||
if (s == "create_fireworks_small") { return EnemyActionType::CREATE_FIREWORKS_SMALL; }
|
||||
if (s == "apply_impulse") { return EnemyActionType::APPLY_IMPULSE; }
|
||||
if (s == "decrease_health") { return EnemyActionType::DECREASE_HEALTH; }
|
||||
if (s == "flash") { return EnemyActionType::FLASH; }
|
||||
if (s == "fire_bullet") { return EnemyActionType::FIRE_BULLET; }
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
auto parseActionList(const fkyaml::node& list_node, const std::string& enemy_name, const char* event_name, std::vector<EnemyAction>& out) -> bool {
|
||||
if (!list_node.is_sequence()) {
|
||||
std::cerr << "[EnemyConfig] Error: '" << event_name << "' ha de ser una llista a "
|
||||
<< enemy_name << '\n';
|
||||
return false;
|
||||
}
|
||||
for (const auto& item : list_node) {
|
||||
if (!item.contains("action")) {
|
||||
std::cerr << "[EnemyConfig] Error: entrada sense 'action' a " << event_name
|
||||
<< " (" << enemy_name << ")\n";
|
||||
return false;
|
||||
}
|
||||
const auto STR = item["action"].get_value<std::string>();
|
||||
const auto PARSED = actionTypeFromString(STR);
|
||||
if (!PARSED) {
|
||||
std::cerr << "[EnemyConfig] Error: acció desconeguda '" << STR << "' a "
|
||||
<< event_name << " (" << enemy_name << ")\n";
|
||||
return false;
|
||||
}
|
||||
EnemyAction action;
|
||||
action.type = *PARSED;
|
||||
// Payload de FIRE_BULLET. Camps opcionals; els defaults són els del struct.
|
||||
if (action.type == EnemyActionType::FIRE_BULLET) {
|
||||
if (item.contains("bullet")) {
|
||||
action.bullet_config_name = item["bullet"].get_value<std::string>();
|
||||
}
|
||||
if (item.contains("bullet_speed")) {
|
||||
action.bullet_speed = item["bullet_speed"].get_value<float>();
|
||||
}
|
||||
if (item.contains("aim_mode")) {
|
||||
const auto AIM_STR = item["aim_mode"].get_value<std::string>();
|
||||
const auto AIM = aimModeFromString(AIM_STR);
|
||||
if (!AIM) {
|
||||
std::cerr << "[EnemyConfig] Error: aim_mode desconegut '" << AIM_STR
|
||||
<< "' a " << event_name << " (" << enemy_name << ")\n";
|
||||
return false;
|
||||
}
|
||||
action.aim_mode = *AIM;
|
||||
}
|
||||
if (item.contains("jitter_rad")) {
|
||||
action.jitter_rad = item["jitter_rad"].get_value<float>();
|
||||
}
|
||||
}
|
||||
out.push_back(action);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Defaults: replica el flux hardcoded actual (set_hurt → destroy → score+debris+fireworks).
|
||||
// Construïm via mutació per esquivar warnings de designated-init parcial sobre
|
||||
// l'EnemyAction (que té payload de FIRE_BULLET no rellevant ací).
|
||||
void fillLegacyDefaults(EnemyEventConfig& events) {
|
||||
const auto MAKE = [](EnemyActionType type) {
|
||||
EnemyAction a;
|
||||
a.type = type;
|
||||
return a;
|
||||
};
|
||||
events.on_hit = {MAKE(EnemyActionType::SET_HURT)};
|
||||
events.on_hurt_end = {MAKE(EnemyActionType::DESTROY)};
|
||||
events.on_destroy = {
|
||||
MAKE(EnemyActionType::ADD_SCORE),
|
||||
MAKE(EnemyActionType::CREATE_DEBRIS),
|
||||
MAKE(EnemyActionType::CREATE_FIREWORKS),
|
||||
};
|
||||
}
|
||||
|
||||
auto movementTypeFromString(const std::string& s) -> std::optional<MovementType> {
|
||||
if (s == "zigzag") { return MovementType::ZIGZAG; }
|
||||
if (s == "tracking") { return MovementType::TRACKING; }
|
||||
if (s == "rectilinear_proximity") { return MovementType::RECTILINEAR_PROXIMITY; }
|
||||
if (s == "wander") { return MovementType::WANDER; }
|
||||
if (s == "chase") { return MovementType::CHASE; }
|
||||
if (s == "flee") { return MovementType::FLEE; }
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
auto aiActionTypeFromString(const std::string& s) -> std::optional<AiActionType> {
|
||||
if (s == "shoot") { return AiActionType::SHOOT; }
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
auto aimModeFromString(const std::string& s) -> std::optional<AimMode> {
|
||||
if (s == "random") { return AimMode::RANDOM; }
|
||||
if (s == "aimed") { return AimMode::AIMED; }
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
auto parseMovement(const fkyaml::node& mv_node, const std::string& enemy_name, MovementConfig& out) -> bool {
|
||||
if (!mv_node.contains("type")) {
|
||||
std::cerr << "[EnemyConfig] Error: falta 'ai.movement.type' a " << enemy_name << '\n';
|
||||
return false;
|
||||
}
|
||||
const auto TYPE_STR = mv_node["type"].get_value<std::string>();
|
||||
const auto PARSED = movementTypeFromString(TYPE_STR);
|
||||
if (!PARSED) {
|
||||
std::cerr << "[EnemyConfig] Error: movement type desconegut '" << TYPE_STR
|
||||
<< "' a " << enemy_name << '\n';
|
||||
return false;
|
||||
}
|
||||
out.type = *PARSED;
|
||||
const auto READ_OPT = [&mv_node](const char* key, float& dst) {
|
||||
if (mv_node.contains(key)) {
|
||||
dst = mv_node[key].get_value<float>();
|
||||
}
|
||||
};
|
||||
READ_OPT("angle_change_max", out.angle_change_max);
|
||||
READ_OPT("zigzag_prob_per_second", out.zigzag_prob_per_second);
|
||||
READ_OPT("tracking_strength", out.tracking_strength);
|
||||
READ_OPT("tracking_interval", out.tracking_interval);
|
||||
READ_OPT("rotation_proximity_multiplier", out.rotation_proximity_multiplier);
|
||||
READ_OPT("proximity_distance", out.proximity_distance);
|
||||
READ_OPT("chase_strength", out.chase_strength);
|
||||
READ_OPT("flee_strength", out.flee_strength);
|
||||
return true;
|
||||
}
|
||||
|
||||
auto parseTickList(const fkyaml::node& list_node, const std::string& enemy_name, std::vector<AiTickAction>& out) -> bool {
|
||||
if (!list_node.is_sequence()) {
|
||||
std::cerr << "[EnemyConfig] Error: 'ai.tick' ha de ser una llista a " << enemy_name << '\n';
|
||||
return false;
|
||||
}
|
||||
for (const auto& item : list_node) {
|
||||
if (!item.contains("action")) {
|
||||
std::cerr << "[EnemyConfig] Error: entrada sense 'action' a ai.tick ("
|
||||
<< enemy_name << ")\n";
|
||||
return false;
|
||||
}
|
||||
const auto STR = item["action"].get_value<std::string>();
|
||||
const auto PARSED = aiActionTypeFromString(STR);
|
||||
if (!PARSED) {
|
||||
std::cerr << "[EnemyConfig] Error: acció d'ai desconeguda '" << STR
|
||||
<< "' a " << enemy_name << '\n';
|
||||
return false;
|
||||
}
|
||||
AiTickAction action;
|
||||
action.type = *PARSED;
|
||||
if (item.contains("interval")) {
|
||||
action.interval = item["interval"].get_value<float>();
|
||||
}
|
||||
if (item.contains("aim_mode")) {
|
||||
const auto AIM_STR = item["aim_mode"].get_value<std::string>();
|
||||
const auto AIM = aimModeFromString(AIM_STR);
|
||||
if (!AIM) {
|
||||
std::cerr << "[EnemyConfig] Error: aim_mode desconegut '" << AIM_STR
|
||||
<< "' a ai.tick (" << enemy_name << ")\n";
|
||||
return false;
|
||||
}
|
||||
action.aim_mode = *AIM;
|
||||
}
|
||||
if (item.contains("jitter_rad")) {
|
||||
action.jitter_rad = item["jitter_rad"].get_value<float>();
|
||||
}
|
||||
if (item.contains("bullet_speed")) {
|
||||
action.bullet_speed = item["bullet_speed"].get_value<float>();
|
||||
}
|
||||
if (item.contains("bullet")) {
|
||||
action.bullet_config_name = item["bullet"].get_value<std::string>();
|
||||
}
|
||||
out.push_back(action);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Migració progressiva: si el YAML no porta secció `ai:`, derivem el
|
||||
// movement a partir de l'ai_type i copiem els paràmetres de la BehaviorCfg
|
||||
// ja parsejada. Comportament idèntic al hardcoded actual.
|
||||
void fillLegacyAiDefaults(EnemyType ai_type, const EnemyConfig::BehaviorCfg& legacy, EnemyAiConfig& out) {
|
||||
switch (ai_type) {
|
||||
case EnemyType::PENTAGON:
|
||||
case EnemyType::STAR:
|
||||
out.movement.type = MovementType::ZIGZAG;
|
||||
out.movement.angle_change_max = legacy.angle_change_max;
|
||||
out.movement.zigzag_prob_per_second = legacy.zigzag_prob_per_second;
|
||||
break;
|
||||
case EnemyType::SQUARE:
|
||||
out.movement.type = MovementType::TRACKING;
|
||||
out.movement.tracking_strength = legacy.tracking_strength;
|
||||
out.movement.tracking_interval = legacy.tracking_interval;
|
||||
break;
|
||||
case EnemyType::PINWHEEL:
|
||||
out.movement.type = MovementType::RECTILINEAR_PROXIMITY;
|
||||
out.movement.rotation_proximity_multiplier = legacy.rotation_proximity_multiplier;
|
||||
out.movement.proximity_distance = legacy.proximity_distance;
|
||||
break;
|
||||
case EnemyType::ORB:
|
||||
// Sense legacy fallback: el YAML de l'orb ha de definir
|
||||
// ai.movement explícitament. Default chase lent perquè el switch
|
||||
// siga exhaustiu i no falli si algú omet el bloc ai.
|
||||
out.movement.type = MovementType::CHASE;
|
||||
out.movement.chase_strength = 0.3F;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
auto parseAi(const fkyaml::node& node, const std::string& name, EnemyType ai_type, const EnemyConfig::BehaviorCfg& legacy, EnemyAiConfig& out) -> bool {
|
||||
if (!node.contains("ai")) {
|
||||
fillLegacyAiDefaults(ai_type, legacy, out);
|
||||
return true;
|
||||
}
|
||||
const auto& ai = node["ai"];
|
||||
if (!ai.contains("movement")) {
|
||||
std::cerr << "[EnemyConfig] Error: falta 'ai.movement' a " << name << '\n';
|
||||
return false;
|
||||
}
|
||||
if (!parseMovement(ai["movement"], name, out.movement)) {
|
||||
return false;
|
||||
}
|
||||
if (ai.contains("tick") && !parseTickList(ai["tick"], name, out.tick)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
auto parseEvents(const fkyaml::node& node, const std::string& name, EnemyEventConfig& out) -> bool {
|
||||
if (!node.contains("events")) {
|
||||
fillLegacyDefaults(out);
|
||||
return true;
|
||||
}
|
||||
const auto& e = node["events"];
|
||||
if (e.contains("on_hit") && !parseActionList(e["on_hit"], name, "on_hit", out.on_hit)) {
|
||||
return false;
|
||||
}
|
||||
if (e.contains("on_no_health") &&
|
||||
!parseActionList(e["on_no_health"], name, "on_no_health", out.on_no_health)) {
|
||||
return false;
|
||||
}
|
||||
if (e.contains("on_hurt_end") &&
|
||||
!parseActionList(e["on_hurt_end"], name, "on_hurt_end", out.on_hurt_end)) {
|
||||
return false;
|
||||
}
|
||||
if (e.contains("on_destroy") &&
|
||||
!parseActionList(e["on_destroy"], name, "on_destroy", out.on_destroy)) {
|
||||
return false;
|
||||
}
|
||||
// Validació: destroy no pot aparèixer dins on_destroy (recursió infinita).
|
||||
for (const auto& a : out.on_destroy) {
|
||||
if (a.type == EnemyActionType::DESTROY) {
|
||||
std::cerr << "[EnemyConfig] Error: 'destroy' no pot aparèixer dins 'on_destroy' a "
|
||||
<< name << " (recursió infinita)\n";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
auto EnemyConfig::fromYaml(const fkyaml::node& node, EnemyType expected_ai_type)
|
||||
-> std::optional<EnemyConfig> {
|
||||
try {
|
||||
EnemyConfig cfg;
|
||||
cfg.name = node.contains("name") ? node["name"].get_value<std::string>() : "enemy";
|
||||
|
||||
if (!parseAiType(node, expected_ai_type, cfg.name, cfg.ai_type)) { return std::nullopt; }
|
||||
if (!parseShape(node, cfg.name, cfg.shape)) { return std::nullopt; }
|
||||
if (!parsePhysics(node, cfg.name, cfg.physics)) { return std::nullopt; }
|
||||
parseBehavior(node, cfg.behavior);
|
||||
if (!parseAnimation(node, cfg.name, cfg.animation)) { return std::nullopt; }
|
||||
if (!parseWounded(node, cfg.name, cfg.wounded)) { return std::nullopt; }
|
||||
if (!parseSpawn(node, cfg.name, cfg.spawn)) { return std::nullopt; }
|
||||
if (!parseColors(node, cfg.name, cfg.colors)) { return std::nullopt; }
|
||||
if (!parseScore(node, cfg.name, cfg.score)) { return std::nullopt; }
|
||||
parseHealth(node, cfg.health);
|
||||
if (!parseEvents(node, cfg.name, cfg.events)) { return std::nullopt; }
|
||||
if (!parseAi(node, cfg.name, cfg.ai_type, cfg.behavior, cfg.ai)) { return std::nullopt; }
|
||||
|
||||
return cfg;
|
||||
} catch (const std::exception& e) {
|
||||
std::cerr << "[EnemyConfig] Excepció parsejant: " << e.what() << '\n';
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
// enemy_config.hpp - Configuració d'un tipus d'enemic carregada des de YAML
|
||||
// © 2026 JailDesigner
|
||||
//
|
||||
// Una instància per tipus (Pentagon/Square/Pinwheel), carregada un cop al
|
||||
// startup per EnemyRegistry i compartida entre totes les instàncies d'aquell
|
||||
// tipus. Estructura paral·lela a PlayerConfig.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <optional>
|
||||
#include <string>
|
||||
|
||||
#include "external/fkyaml_node.hpp"
|
||||
#include "game/entities/enemy.hpp" // EnemyType
|
||||
#include "game/entities/enemy_ai.hpp"
|
||||
#include "game/entities/enemy_event.hpp"
|
||||
|
||||
struct EnemyConfig {
|
||||
struct ShapeCfg {
|
||||
std::string path;
|
||||
float scale; // multiplicador visual + hitbox sobre la mida nativa del .shp
|
||||
float collision_factor; // ajust opcional del hitbox respecte el cercle circumscrit (default 1.0)
|
||||
};
|
||||
|
||||
struct PhysicsCfg {
|
||||
float mass;
|
||||
float speed;
|
||||
float rotation_delta_min;
|
||||
float rotation_delta_max;
|
||||
float restitution; // rebot contra parets (1.0 = perfectament elàstic)
|
||||
float linear_damping; // fricció lineal (s^-1)
|
||||
float angular_damping;
|
||||
};
|
||||
|
||||
// Camps específics de cada AI. Els no aplicables a un tipus queden a 0.0F
|
||||
// i no s'usen — el dispatch viu a Enemy::behaviorXxx.
|
||||
struct BehaviorCfg {
|
||||
// Pentagon
|
||||
float zigzag_prob_per_second{0.0F};
|
||||
float angle_change_max{0.0F};
|
||||
// Square
|
||||
float tracking_strength{0.0F};
|
||||
float tracking_interval{0.0F};
|
||||
// Pinwheel
|
||||
float rotation_proximity_multiplier{0.0F};
|
||||
float proximity_distance{0.0F};
|
||||
};
|
||||
|
||||
// Animacions decoratives. Compartides estructuralment entre tots els tipus
|
||||
// però amb valors propis per personalitzar la "personalitat" visual de cada un.
|
||||
struct AnimationCfg {
|
||||
struct PulseCfg {
|
||||
float trigger_prob_per_second; // probabilitat per segon d'iniciar un pulse
|
||||
float duration_min;
|
||||
float duration_max;
|
||||
float amplitude_min; // amplitud d'escala (±)
|
||||
float amplitude_max;
|
||||
float frequency_min; // Hz
|
||||
float frequency_max;
|
||||
};
|
||||
struct RotationAccelCfg {
|
||||
float trigger_prob_per_second;
|
||||
float duration_min; // segons de transició al nou speed
|
||||
float duration_max;
|
||||
float multiplier_min; // multiplicador sobre rotation_delta_base
|
||||
float multiplier_max;
|
||||
};
|
||||
PulseCfg pulse;
|
||||
RotationAccelCfg rotation_accel;
|
||||
};
|
||||
|
||||
struct WoundedCfg {
|
||||
float duration; // segons en estat ferit abans d'explotar
|
||||
float blink_hz; // freqüència del parpelleig color normal ↔ wounded
|
||||
};
|
||||
|
||||
struct SpawnCfg {
|
||||
float invulnerability_duration; // segons d'invulnerabilitat post-spawn
|
||||
float invulnerability_brightness_start; // brightness inicial (corba LERP)
|
||||
float invulnerability_brightness_end; // brightness final
|
||||
float invulnerability_scale_start; // escala inicial (corba LERP, 0 = invisible)
|
||||
float invulnerability_scale_end; // escala final (1 = mida nativa)
|
||||
float safety_distance; // px mínim respecte al player al spawn
|
||||
};
|
||||
|
||||
struct ColorsCfg {
|
||||
SDL_Color normal;
|
||||
SDL_Color wounded;
|
||||
};
|
||||
|
||||
std::string name;
|
||||
EnemyType ai_type;
|
||||
ShapeCfg shape;
|
||||
PhysicsCfg physics;
|
||||
BehaviorCfg behavior;
|
||||
AnimationCfg animation;
|
||||
WoundedCfg wounded;
|
||||
SpawnCfg spawn;
|
||||
ColorsCfg colors;
|
||||
int score;
|
||||
// Salut inicial: per defecte 1 (un balazo → on_no_health). Els YAMLs poden
|
||||
// pujar-lo (p.ex. 10 per a un enemic tough). El sistema d'events és qui
|
||||
// decideix què passa quan la salut arriba a 0 via on_no_health.
|
||||
int health{1};
|
||||
EnemyEventConfig events;
|
||||
EnemyAiConfig ai;
|
||||
|
||||
// Parseja un descriptor d'enemic. expected_ai_type valida que ai_type del
|
||||
// YAML coincideix amb el tipus que el caller espera (segons el directori).
|
||||
static auto fromYaml(const fkyaml::node& node, EnemyType expected_ai_type)
|
||||
-> std::optional<EnemyConfig>;
|
||||
};
|
||||
@@ -0,0 +1,67 @@
|
||||
// enemy_event.hpp - Sistema declaratiu d'events i accions per a enemics
|
||||
// © 2026 JailDesigner
|
||||
//
|
||||
// Cada enemic descriu al seu YAML què passa quan rep un event (on_hit,
|
||||
// on_hurt_end, on_destroy) com a llista d'accions. El motor només dispatcha;
|
||||
// el comportament viu a les dades.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "game/entities/enemy_ai.hpp" // AimMode
|
||||
|
||||
enum class EnemyEventType : uint8_t {
|
||||
ON_HIT, // Impactat per una bala
|
||||
ON_NO_HEALTH, // health ha arribat a 0 o menys aquest frame (via DECREASE_HEALTH)
|
||||
ON_HURT_END, // Timer wounded ha expirat aquest frame
|
||||
ON_DESTROY, // L'acció destroy s'està executant (efectes col·laterals)
|
||||
};
|
||||
|
||||
enum class EnemyActionType : uint8_t {
|
||||
SET_HURT, // Entra estat wounded (o destrueix si ja era wounded)
|
||||
DESTROY, // Dispara on_destroy + desactiva físicament
|
||||
ADD_SCORE, // Suma config.score al shooter + floating score
|
||||
CREATE_DEBRIS, // Explosió de debris amb herència de velocitat
|
||||
CREATE_DEBRIS_PARTIAL, // Debris de xip parcial (trossos a escala 0.3, per hits HP>1)
|
||||
CREATE_FIREWORKS, // Burst radial de firework
|
||||
CREATE_FIREWORKS_SMALL, // Burst petit (pocs punts, poca velocitat) — feedback per hit
|
||||
APPLY_IMPULSE, // Aplica l'impuls de la bala impactant
|
||||
DECREASE_HEALTH, // Decrementa health_; si <=0, dispatcha ON_NO_HEALTH
|
||||
FLASH, // Flash visual breu (feedback per impacte parcial)
|
||||
FIRE_BULLET, // Dispara una bala (config per nom) dirigida o aleatòria
|
||||
};
|
||||
|
||||
struct EnemyAction {
|
||||
EnemyActionType type;
|
||||
|
||||
// Payload de FIRE_BULLET (ignorat per altres tipus). Paral·lel a AiTickAction
|
||||
// perquè un futur refactor pugui compartir doShoot/doFireBullet si val la pena.
|
||||
std::string bullet_config_name;
|
||||
float bullet_speed{200.0F};
|
||||
AimMode aim_mode{AimMode::RANDOM};
|
||||
float jitter_rad{0.0F};
|
||||
};
|
||||
|
||||
struct EnemyEventConfig {
|
||||
std::vector<EnemyAction> on_hit;
|
||||
std::vector<EnemyAction> on_no_health;
|
||||
std::vector<EnemyAction> on_hurt_end;
|
||||
std::vector<EnemyAction> on_destroy;
|
||||
|
||||
[[nodiscard]] auto getActions(EnemyEventType event) const -> const std::vector<EnemyAction>& {
|
||||
switch (event) {
|
||||
case EnemyEventType::ON_HIT:
|
||||
return on_hit;
|
||||
case EnemyEventType::ON_NO_HEALTH:
|
||||
return on_no_health;
|
||||
case EnemyEventType::ON_HURT_END:
|
||||
return on_hurt_end;
|
||||
case EnemyEventType::ON_DESTROY:
|
||||
return on_destroy;
|
||||
}
|
||||
return on_hit; // unreachable
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,70 @@
|
||||
// enemy_registry.cpp - Implementació del registre estàtic d'enemics
|
||||
// © 2026 JailDesigner
|
||||
|
||||
#include "game/entities/enemy_registry.hpp"
|
||||
|
||||
#include <cstdlib>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
#include "core/entities/entity_loader.hpp"
|
||||
|
||||
EnemyConfig EnemyRegistry::pentagon_config;
|
||||
EnemyConfig EnemyRegistry::square_config;
|
||||
EnemyConfig EnemyRegistry::pinwheel_config;
|
||||
EnemyConfig EnemyRegistry::star_config;
|
||||
EnemyConfig EnemyRegistry::orb_config;
|
||||
bool EnemyRegistry::loaded = false;
|
||||
|
||||
namespace {
|
||||
|
||||
auto loadOne(const std::string& name, EnemyType expected_type, EnemyConfig& out) -> bool {
|
||||
auto yaml = Entities::EntityLoader::load(name);
|
||||
if (!yaml) {
|
||||
std::cerr << "[EnemyRegistry] Error: no s'ha pogut carregar " << name << ".yaml\n";
|
||||
return false;
|
||||
}
|
||||
auto cfg = EnemyConfig::fromYaml(*yaml, expected_type);
|
||||
if (!cfg) {
|
||||
std::cerr << "[EnemyRegistry] Error: format invàlid a " << name << ".yaml\n";
|
||||
return false;
|
||||
}
|
||||
out = *cfg;
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
auto EnemyRegistry::loadAll() -> bool {
|
||||
const bool OK = loadOne("pentagon", EnemyType::PENTAGON, pentagon_config) &&
|
||||
loadOne("square", EnemyType::SQUARE, square_config) &&
|
||||
loadOne("pinwheel", EnemyType::PINWHEEL, pinwheel_config) &&
|
||||
loadOne("star", EnemyType::STAR, star_config) &&
|
||||
loadOne("orb", EnemyType::ORB, orb_config);
|
||||
loaded = OK;
|
||||
if (OK) {
|
||||
std::cout << "[EnemyRegistry] 5 configuracions d'enemic carregades.\n";
|
||||
}
|
||||
return OK;
|
||||
}
|
||||
|
||||
auto EnemyRegistry::get(EnemyType type) -> const EnemyConfig& {
|
||||
if (!loaded) {
|
||||
std::cerr << "[EnemyRegistry] FATAL: get() abans de loadAll()\n";
|
||||
std::exit(EXIT_FAILURE);
|
||||
}
|
||||
switch (type) {
|
||||
case EnemyType::PENTAGON:
|
||||
return pentagon_config;
|
||||
case EnemyType::SQUARE:
|
||||
return square_config;
|
||||
case EnemyType::PINWHEEL:
|
||||
return pinwheel_config;
|
||||
case EnemyType::STAR:
|
||||
return star_config;
|
||||
case EnemyType::ORB:
|
||||
return orb_config;
|
||||
}
|
||||
std::cerr << "[EnemyRegistry] FATAL: tipus desconegut\n";
|
||||
std::exit(EXIT_FAILURE);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// enemy_registry.hpp - Registre estàtic de configuracions d'enemics per tipus
|
||||
// © 2026 JailDesigner
|
||||
//
|
||||
// Carrega els 3 fitxers YAML (pentagon, square, pinwheel) un cop al startup
|
||||
// i exposa el lookup per EnemyType. Pensat per a ser invocat des de
|
||||
// GameScene; si la càrrega falla, el caller decideix avortar.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "game/entities/enemy.hpp"
|
||||
#include "game/entities/enemy_config.hpp"
|
||||
|
||||
class EnemyRegistry {
|
||||
public:
|
||||
EnemyRegistry() = delete; // tot estàtic
|
||||
|
||||
// Carrega els 3 descriptors. Retorna true si tots tres s'han carregat
|
||||
// i parsejat correctament. Cridar abans del primer get().
|
||||
static auto loadAll() -> bool;
|
||||
|
||||
// Lookup. Cal haver cridat loadAll() abans. Si el tipus no s'ha carregat
|
||||
// (loadAll fallida o no cridada), avorta amb log fatal.
|
||||
static auto get(EnemyType type) -> const EnemyConfig&;
|
||||
|
||||
private:
|
||||
static EnemyConfig pentagon_config;
|
||||
static EnemyConfig square_config;
|
||||
static EnemyConfig pinwheel_config;
|
||||
static EnemyConfig star_config;
|
||||
static EnemyConfig orb_config;
|
||||
static bool loaded;
|
||||
};
|
||||
@@ -0,0 +1,111 @@
|
||||
// player_config.cpp - Implementació del parser de PlayerConfig
|
||||
// © 2026 JailDesigner
|
||||
|
||||
#include "game/entities/player_config.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <exception>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
namespace {
|
||||
|
||||
// Helper: extreu un SDL_Color d'una seqüència de 3 enters [r, g, b] del YAML.
|
||||
// Retorna true si el format és vàlid.
|
||||
auto parseColor(const fkyaml::node& node, SDL_Color& out) -> bool {
|
||||
if (!node.is_sequence() || node.size() != 3) {
|
||||
return false;
|
||||
}
|
||||
const auto R = node[0].get_value<uint32_t>();
|
||||
const auto G = node[1].get_value<uint32_t>();
|
||||
const auto B = node[2].get_value<uint32_t>();
|
||||
out = SDL_Color{
|
||||
.r = static_cast<uint8_t>(R),
|
||||
.g = static_cast<uint8_t>(G),
|
||||
.b = static_cast<uint8_t>(B),
|
||||
.a = 255};
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
auto PlayerConfig::fromYaml(const fkyaml::node& node) -> std::optional<PlayerConfig> {
|
||||
try {
|
||||
PlayerConfig cfg;
|
||||
|
||||
cfg.name = node.contains("name") ? node["name"].get_value<std::string>() : "player";
|
||||
|
||||
// shape
|
||||
if (!node.contains("shape") || !node["shape"].contains("path")) {
|
||||
std::cerr << "[PlayerConfig] Error: falta 'shape.path'" << '\n';
|
||||
return std::nullopt;
|
||||
}
|
||||
const auto& shape = node["shape"];
|
||||
cfg.shape.path = shape["path"].get_value<std::string>();
|
||||
cfg.shape.scale = shape.contains("scale") ? shape["scale"].get_value<float>() : 1.0F;
|
||||
cfg.shape.collision_factor = shape.contains("collision_factor")
|
||||
? shape["collision_factor"].get_value<float>()
|
||||
: 1.0F;
|
||||
|
||||
// physics
|
||||
if (!node.contains("physics")) {
|
||||
std::cerr << "[PlayerConfig] Error: falta 'physics'" << '\n';
|
||||
return std::nullopt;
|
||||
}
|
||||
const auto& physics = node["physics"];
|
||||
cfg.physics.mass = physics["mass"].get_value<float>();
|
||||
cfg.physics.restitution = physics["restitution"].get_value<float>();
|
||||
cfg.physics.linear_damping = physics["linear_damping"].get_value<float>();
|
||||
cfg.physics.angular_damping = physics["angular_damping"].get_value<float>();
|
||||
cfg.physics.rotation_speed = physics["rotation_speed"].get_value<float>();
|
||||
cfg.physics.acceleration = physics["acceleration"].get_value<float>();
|
||||
cfg.physics.max_velocity = physics["max_velocity"].get_value<float>();
|
||||
cfg.physics.death_impact_factor = physics["death_impact_factor"].get_value<float>();
|
||||
|
||||
// invulnerability
|
||||
if (!node.contains("invulnerability")) {
|
||||
std::cerr << "[PlayerConfig] Error: falta 'invulnerability'" << '\n';
|
||||
return std::nullopt;
|
||||
}
|
||||
const auto& invul = node["invulnerability"];
|
||||
cfg.invulnerability.duration = invul["duration"].get_value<float>();
|
||||
cfg.invulnerability.blink_visible = invul["blink_visible"].get_value<float>();
|
||||
cfg.invulnerability.blink_invisible = invul["blink_invisible"].get_value<float>();
|
||||
|
||||
// hurt
|
||||
if (!node.contains("hurt")) {
|
||||
std::cerr << "[PlayerConfig] Error: falta 'hurt'" << '\n';
|
||||
return std::nullopt;
|
||||
}
|
||||
cfg.hurt.duration = node["hurt"]["duration"].get_value<float>();
|
||||
cfg.hurt.blink_hz = node["hurt"]["blink_hz"].get_value<float>();
|
||||
|
||||
// visual_thrust
|
||||
if (!node.contains("visual_thrust")) {
|
||||
std::cerr << "[PlayerConfig] Error: falta 'visual_thrust'" << '\n';
|
||||
return std::nullopt;
|
||||
}
|
||||
cfg.visual_thrust.push_divisor = node["visual_thrust"]["push_divisor"].get_value<float>();
|
||||
cfg.visual_thrust.scale_divisor = node["visual_thrust"]["scale_divisor"].get_value<float>();
|
||||
|
||||
// colors
|
||||
if (!node.contains("colors") ||
|
||||
!parseColor(node["colors"]["normal"], cfg.colors.normal) ||
|
||||
!parseColor(node["colors"]["hurt"], cfg.colors.hurt)) {
|
||||
std::cerr << "[PlayerConfig] Error: 'colors.normal' / 'colors.hurt' no són seqüències [r,g,b]" << '\n';
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
// weapon
|
||||
if (!node.contains("weapon")) {
|
||||
std::cerr << "[PlayerConfig] Error: falta 'weapon'" << '\n';
|
||||
return std::nullopt;
|
||||
}
|
||||
cfg.weapon.bullet_speed = node["weapon"]["bullet_speed"].get_value<float>();
|
||||
|
||||
return cfg;
|
||||
} catch (const std::exception& e) {
|
||||
std::cerr << "[PlayerConfig] Excepció parsejant: " << e.what() << '\n';
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
// player_config.hpp - Configuració de la nau del player carregada des de YAML
|
||||
// © 2026 JailDesigner
|
||||
//
|
||||
// POD struct amb sub-structs per organitzar els paràmetres del jugador
|
||||
// (física, invulnerabilitat, hurt, empenta visual, colors, weapon). Es
|
||||
// construeix a partir d'un node fkyaml carregat per EntityLoader.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <optional>
|
||||
#include <string>
|
||||
|
||||
#include "external/fkyaml_node.hpp"
|
||||
|
||||
struct PlayerConfig {
|
||||
struct ShapeCfg {
|
||||
std::string path;
|
||||
float scale; // multiplicador visual + hitbox sobre la mida nativa del .shp
|
||||
float collision_factor; // ajust opcional del hitbox respecte el cercle circumscrit (default 1.0)
|
||||
};
|
||||
|
||||
struct PhysicsCfg {
|
||||
float mass;
|
||||
float restitution;
|
||||
float linear_damping;
|
||||
float angular_damping;
|
||||
float rotation_speed; // rad/s
|
||||
float acceleration; // px/s^2 multiplicat per la massa
|
||||
float max_velocity; // px/s (clamp post-integració)
|
||||
float death_impact_factor; // [0..1] moment transferit a l'enemic al morir
|
||||
};
|
||||
|
||||
struct InvulnerabilityCfg {
|
||||
float duration;
|
||||
float blink_visible;
|
||||
float blink_invisible;
|
||||
};
|
||||
|
||||
struct HurtCfg {
|
||||
float duration;
|
||||
float blink_hz;
|
||||
};
|
||||
|
||||
struct VisualThrustCfg {
|
||||
float push_divisor;
|
||||
float scale_divisor;
|
||||
};
|
||||
|
||||
struct ColorsCfg {
|
||||
SDL_Color normal;
|
||||
SDL_Color hurt;
|
||||
};
|
||||
|
||||
struct WeaponCfg {
|
||||
float bullet_speed;
|
||||
};
|
||||
|
||||
std::string name;
|
||||
ShapeCfg shape;
|
||||
PhysicsCfg physics;
|
||||
InvulnerabilityCfg invulnerability;
|
||||
HurtCfg hurt;
|
||||
VisualThrustCfg visual_thrust;
|
||||
ColorsCfg colors;
|
||||
WeaponCfg weapon;
|
||||
|
||||
// Construeix un PlayerConfig a partir del node YAML. Retorna std::nullopt
|
||||
// si falten camps requerits o el format no és vàlid (el caller decideix
|
||||
// si abortar).
|
||||
static auto fromYaml(const fkyaml::node& node) -> std::optional<PlayerConfig>;
|
||||
};
|
||||
@@ -9,6 +9,7 @@
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <iostream>
|
||||
#include <utility>
|
||||
|
||||
#include "core/audio/audio.hpp"
|
||||
#include "core/defaults.hpp"
|
||||
@@ -20,27 +21,30 @@
|
||||
#include "core/types.hpp"
|
||||
#include "game/constants.hpp"
|
||||
|
||||
Ship::Ship(Rendering::Renderer* renderer, const char* shape_file)
|
||||
: Entity(renderer) {
|
||||
// Brightness específico para naves
|
||||
Ship::Ship(Rendering::Renderer* renderer, PlayerConfig config, const char* shape_override)
|
||||
: Entity(renderer),
|
||||
config_(std::move(config)) {
|
||||
brightness_ = Defaults::Brightness::NAU;
|
||||
|
||||
// Configuración del cuerpo físico
|
||||
body_.setMass(Defaults::Ship::MASS);
|
||||
body_.radius = Defaults::Entities::SHIP_RADIUS;
|
||||
body_.restitution = Defaults::Ship::RESTITUTION;
|
||||
body_.linear_damping = Defaults::Ship::LINEAR_DAMPING;
|
||||
body_.angular_damping = Defaults::Ship::ANGULAR_DAMPING;
|
||||
|
||||
// Cargar shape compartida desde archivo
|
||||
shape_ = Graphics::ShapeLoader::load(shape_file);
|
||||
// El shape pot venir del YAML o ser overridden (ex: P2 amb "ship/wedge.shp").
|
||||
const std::string SHAPE_PATH = (shape_override != nullptr) ? shape_override : config_.shape.path;
|
||||
shape_ = Graphics::ShapeLoader::load(SHAPE_PATH);
|
||||
if (!shape_ || !shape_->isValid()) {
|
||||
std::cerr << "[Ship] Error: no se ha podido cargar " << shape_file << '\n';
|
||||
std::cerr << "[Ship] Error: no se ha podido cargar " << SHAPE_PATH << '\n';
|
||||
}
|
||||
|
||||
// Radi de col·lisió derivat del cercle circumscrit de la shape * scale * collision_factor.
|
||||
const float BOUNDING = (shape_ != nullptr) ? shape_->getBoundingRadius() : 0.0F;
|
||||
collision_radius_ = BOUNDING * config_.shape.scale * config_.shape.collision_factor;
|
||||
|
||||
body_.setMass(config_.physics.mass);
|
||||
body_.radius = collision_radius_;
|
||||
body_.restitution = config_.physics.restitution;
|
||||
body_.linear_damping = config_.physics.linear_damping;
|
||||
body_.angular_damping = config_.physics.angular_damping;
|
||||
}
|
||||
|
||||
void Ship::init(const Vec2* spawn_point, bool activar_invulnerabilitat) {
|
||||
// Posición inicial
|
||||
if (spawn_point != nullptr) {
|
||||
center_ = *spawn_point;
|
||||
} else {
|
||||
@@ -50,34 +54,27 @@ void Ship::init(const Vec2* spawn_point, bool activar_invulnerabilitat) {
|
||||
center_ = {.x = center_x, .y = center_y};
|
||||
}
|
||||
|
||||
// Reset orientación
|
||||
angle_ = 0.0F;
|
||||
|
||||
// Sincronizar cuerpo físico con la posición/orientación inicial
|
||||
body_.position = center_;
|
||||
body_.angle = angle_;
|
||||
body_.velocity = Vec2{};
|
||||
body_.angular_velocity = 0.0F;
|
||||
body_.clearAccumulators();
|
||||
|
||||
// Activar invulnerabilidad solo si es respawn
|
||||
invulnerable_timer_ = activar_invulnerabilitat ? Defaults::Ship::INVULNERABILITY_DURATION : 0.0F;
|
||||
invulnerable_timer_ = activar_invulnerabilitat ? config_.invulnerability.duration : 0.0F;
|
||||
is_hit_ = false;
|
||||
hurt_timer_ = 0.0F;
|
||||
touching_enemy_prev_frame_ = false;
|
||||
}
|
||||
|
||||
void Ship::processInput(float delta_time, uint8_t player_id) {
|
||||
// Solo procesa input si la nave está viva
|
||||
if (is_hit_) {
|
||||
return;
|
||||
}
|
||||
|
||||
auto* input = Input::get();
|
||||
|
||||
// Rotación: control directo del ángulo (no física, no inercial).
|
||||
// Se actualiza también body_.angle para que el dibujado tras
|
||||
// postUpdate refleje el cambio inmediatamente.
|
||||
const bool ROTATE_RIGHT = (player_id == 0)
|
||||
? input->checkActionPlayer1(InputAction::RIGHT, Input::ALLOW_REPEAT)
|
||||
: input->checkActionPlayer2(InputAction::RIGHT, Input::ALLOW_REPEAT);
|
||||
@@ -88,56 +85,56 @@ void Ship::processInput(float delta_time, uint8_t player_id) {
|
||||
? input->checkActionPlayer1(InputAction::THRUST, Input::ALLOW_REPEAT)
|
||||
: input->checkActionPlayer2(InputAction::THRUST, Input::ALLOW_REPEAT);
|
||||
|
||||
if (ROTATE_RIGHT) {
|
||||
body_.angle += Defaults::Physics::ROTATION_SPEED * delta_time;
|
||||
applyMovement(ROTATE_LEFT, ROTATE_RIGHT, THRUST, delta_time);
|
||||
}
|
||||
if (ROTATE_LEFT) {
|
||||
body_.angle -= Defaults::Physics::ROTATION_SPEED * delta_time;
|
||||
|
||||
void Ship::applyMovement(bool rotate_left, bool rotate_right, bool thrust, float delta_time) {
|
||||
if (is_hit_) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (rotate_right) {
|
||||
body_.angle += config_.physics.rotation_speed * delta_time;
|
||||
}
|
||||
if (rotate_left) {
|
||||
body_.angle -= config_.physics.rotation_speed * delta_time;
|
||||
}
|
||||
|
||||
// Thrust: fuerza vectorial en la dirección de la nariz.
|
||||
// angle - PI/2 porque angle=0 apunta hacia arriba (eje Y negativo SDL).
|
||||
if (THRUST) {
|
||||
if (thrust) {
|
||||
const float DIR_X = std::cos(body_.angle - (Constants::PI / 2.0F));
|
||||
const float DIR_Y = std::sin(body_.angle - (Constants::PI / 2.0F));
|
||||
// Fuerza = masa * aceleración: 10 kg * 400 px/s² = 4000 (unidades arcade)
|
||||
const float MAGNITUDE = body_.mass * Defaults::Physics::ACCELERATION;
|
||||
const float MAGNITUDE = body_.mass * config_.physics.acceleration;
|
||||
body_.applyForce(Vec2{.x = DIR_X * MAGNITUDE, .y = DIR_Y * MAGNITUDE});
|
||||
}
|
||||
}
|
||||
|
||||
void Ship::update(float delta_time) {
|
||||
// Solo update si la nave está viva
|
||||
if (is_hit_) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Decrementar timer de invulnerabilidad
|
||||
if (invulnerable_timer_ > 0.0F) {
|
||||
invulnerable_timer_ -= delta_time;
|
||||
invulnerable_timer_ = std::max(invulnerable_timer_, 0.0F);
|
||||
}
|
||||
|
||||
// Decrementar timer d'estat HURT (a 0 → torna a normal sense efecte extern)
|
||||
if (hurt_timer_ > 0.0F) {
|
||||
hurt_timer_ -= delta_time;
|
||||
hurt_timer_ = std::max(hurt_timer_, 0.0F);
|
||||
}
|
||||
|
||||
// El movimiento real lo hace PhysicsWorld::update().
|
||||
// Aquí solo lógica de estado.
|
||||
|
||||
// Cap de velocidad: el thrust acumula fuerza sin límite; limitamos
|
||||
// la magnitud de body_.velocity tras aplicar fuerzas para preservar
|
||||
// el feel arcade del MAX_VELOCITY original.
|
||||
const float CURRENT_SPEED = body_.velocity.length();
|
||||
if (CURRENT_SPEED > Defaults::Physics::MAX_VELOCITY) {
|
||||
body_.velocity = body_.velocity * (Defaults::Physics::MAX_VELOCITY / CURRENT_SPEED);
|
||||
if (CURRENT_SPEED > config_.physics.max_velocity) {
|
||||
body_.velocity = body_.velocity * (config_.physics.max_velocity / CURRENT_SPEED);
|
||||
}
|
||||
}
|
||||
|
||||
void Ship::postUpdate(float /*delta_time*/) {
|
||||
// Sincronizar mirror desde body_ tras la integración del world.
|
||||
center_ = body_.position;
|
||||
angle_ = body_.angle;
|
||||
}
|
||||
@@ -147,11 +144,10 @@ void Ship::draw() const {
|
||||
return;
|
||||
}
|
||||
|
||||
// Parpadeo si invulnerable
|
||||
if (isInvulnerable()) {
|
||||
const float BLINK_CYCLE = Defaults::Ship::BLINK_VISIBLE_TIME + Defaults::Ship::BLINK_INVISIBLE_TIME;
|
||||
const float BLINK_CYCLE = config_.invulnerability.blink_visible + config_.invulnerability.blink_invisible;
|
||||
const float TIME_IN_CYCLE = std::fmod(invulnerable_timer_, BLINK_CYCLE);
|
||||
if (TIME_IN_CYCLE < Defaults::Ship::BLINK_INVISIBLE_TIME) {
|
||||
if (TIME_IN_CYCLE < config_.invulnerability.blink_invisible) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -160,20 +156,19 @@ void Ship::draw() const {
|
||||
return;
|
||||
}
|
||||
|
||||
// Efecto visual de empuje: escala proporcional a la velocidad.
|
||||
// 0..200 px/s → escala 1.0..1.5 (manteniendo la sensación del Pascal original).
|
||||
// Efecte visual d'empenta (modulador sobre l'escala base del YAML).
|
||||
const float SPEED = getSpeed();
|
||||
const float VISUAL_PUSH = SPEED / Defaults::Ship::VISUAL_PUSH_DIVISOR;
|
||||
const float SCALE = 1.0F + (VISUAL_PUSH / Defaults::Ship::VISUAL_SCALE_DIVISOR);
|
||||
const float VISUAL_PUSH = SPEED / config_.visual_thrust.push_divisor;
|
||||
const float THRUST_MODULATOR = 1.0F + (VISUAL_PUSH / config_.visual_thrust.scale_divisor);
|
||||
const float SCALE = config_.shape.scale * THRUST_MODULATOR;
|
||||
|
||||
// Parpelleig daurat mentre està ferida: alterna color normal ↔ color hurt
|
||||
// a Hurt::BLINK_HZ (mateixa estètica que el wounded dels enemics).
|
||||
SDL_Color color = color_normal_;
|
||||
// Parpelleig mentre està ferida: alterna color normal ↔ color hurt.
|
||||
SDL_Color color = config_.colors.normal;
|
||||
if (hurt_timer_ > 0.0F) {
|
||||
const float CYCLE = 1.0F / Defaults::Ship::Hurt::BLINK_HZ;
|
||||
const float CYCLE = 1.0F / config_.hurt.blink_hz;
|
||||
const float T = std::fmod(hurt_timer_, CYCLE);
|
||||
if (T < (CYCLE / 2.0F)) {
|
||||
color = color_hurt_;
|
||||
color = config_.colors.hurt;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -181,6 +176,6 @@ void Ship::draw() const {
|
||||
}
|
||||
|
||||
void Ship::hurt() {
|
||||
hurt_timer_ = Defaults::Ship::Hurt::DURATION;
|
||||
hurt_timer_ = config_.hurt.duration;
|
||||
Audio::get()->playSound(Defaults::Sound::HURT, Audio::Group::GAME);
|
||||
}
|
||||
|
||||
@@ -6,19 +6,25 @@
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
#include "core/defaults.hpp"
|
||||
#include "core/entities/entity.hpp"
|
||||
#include "core/types.hpp"
|
||||
#include "game/entities/player_config.hpp"
|
||||
|
||||
class Ship : public Entities::Entity {
|
||||
public:
|
||||
Ship()
|
||||
: Entity(nullptr) {}
|
||||
explicit Ship(Rendering::Renderer* renderer, const char* shape_file = "ship.shp");
|
||||
// shape_override: si no és nullptr, substitueix config.shape.path
|
||||
// (utilitzat per donar al P2 un model visual diferent compartint la
|
||||
// mateixa configuració del player).
|
||||
explicit Ship(Rendering::Renderer* renderer, PlayerConfig config, const char* shape_override = nullptr);
|
||||
|
||||
void init() override { init(nullptr, false); }
|
||||
void init(const Vec2* spawn_point, bool activar_invulnerabilitat = false);
|
||||
void processInput(float delta_time, uint8_t player_id);
|
||||
// Aplica rotació/empenta des de booleans de control (mateixa física que
|
||||
// processInput, però sense llegir Input). Usat pel pilot IA del mode demo.
|
||||
void applyMovement(bool rotate_left, bool rotate_right, bool thrust, float delta_time);
|
||||
void update(float delta_time) override;
|
||||
void postUpdate(float delta_time) override;
|
||||
void draw() const override;
|
||||
@@ -26,20 +32,18 @@ class Ship : public Entities::Entity {
|
||||
// Override: Interfaz de Entity
|
||||
[[nodiscard]] auto isActive() const -> bool override { return !is_hit_; }
|
||||
|
||||
// Override: Interfaz de colisión
|
||||
[[nodiscard]] auto getCollisionRadius() const -> float override {
|
||||
return Defaults::Entities::SHIP_RADIUS;
|
||||
}
|
||||
// Override: Interfaz de colisión. Derivat al ctor del bounding_radius del
|
||||
// shape carregat × scale × collision_factor.
|
||||
[[nodiscard]] auto getCollisionRadius() const -> float override { return collision_radius_; }
|
||||
[[nodiscard]] auto isCollidable() const -> bool override {
|
||||
return !is_hit_ && invulnerable_timer_ <= 0.0F;
|
||||
}
|
||||
|
||||
// Getters
|
||||
[[nodiscard]] auto isInvulnerable() const -> bool { return invulnerable_timer_ > 0.0F; }
|
||||
// Velocidad como vector cartesiano (ahora viene directa del body_).
|
||||
[[nodiscard]] auto getVelocityVector() const -> Vec2 { return body_.velocity; }
|
||||
// Velocidad escalar (utilidad para draw y debugging).
|
||||
[[nodiscard]] auto getSpeed() const -> float { return body_.velocity.length(); }
|
||||
[[nodiscard]] auto getConfig() const -> const PlayerConfig& { return config_; }
|
||||
|
||||
// Setters
|
||||
void setCenter(const Vec2& nou_centre) {
|
||||
@@ -65,17 +69,18 @@ class Ship : public Entities::Entity {
|
||||
void setTouchingEnemyPrevFrame(bool touching) { touching_enemy_prev_frame_ = touching; }
|
||||
|
||||
private:
|
||||
// Miembros específicos de Ship (heredados: renderer_, shape_, center_, angle_, brightness_, body_).
|
||||
// Inicializados en la declaración: el ctor por defecto deja la nave "viva y sin invulnerabilidad",
|
||||
// que es el estado coherente al que llevan tanto init() como el ctor con renderer.
|
||||
// Configuració carregada des de YAML. Default-init zero permet el ctor
|
||||
// per defecte (necessari per a `std::array<Ship, N>`); s'omple via
|
||||
// copy/move-assignment quan GameScene crea la nau real.
|
||||
PlayerConfig config_{};
|
||||
|
||||
// Radi de col·lisió derivat: shape.bounding_radius × shape.scale × shape.collision_factor.
|
||||
float collision_radius_{0.0F};
|
||||
|
||||
bool is_hit_{false};
|
||||
float invulnerable_timer_{0.0F}; // 0.0f = vulnerable, >0.0f = invulnerable
|
||||
|
||||
// Colors de la nau (propietats, prep per migració a YAML).
|
||||
SDL_Color color_normal_{Defaults::Palette::SHIP};
|
||||
SDL_Color color_hurt_{Defaults::Palette::WOUNDED};
|
||||
|
||||
// >0 → estat HURT (parpelleig color_normal_ ↔ color_hurt_).
|
||||
// >0 → estat HURT (parpelleig color normal ↔ color hurt).
|
||||
float hurt_timer_{0.0F};
|
||||
|
||||
// Edge-trigger: true si el frame anterior la nau ja estava en contacte amb un enemic.
|
||||
|
||||
@@ -4,19 +4,26 @@
|
||||
#include "game_scene.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <ctime>
|
||||
#include <iostream>
|
||||
|
||||
#include "core/audio/audio.hpp"
|
||||
#include "core/entities/entity_loader.hpp"
|
||||
#include "core/input/input.hpp"
|
||||
#include "core/input/input_types.hpp"
|
||||
#include "core/locale/locale.hpp"
|
||||
#include "core/system/scene_context.hpp"
|
||||
#include "core/system/service_menu.hpp"
|
||||
#include "game/entities/bullet_registry.hpp"
|
||||
#include "game/entities/enemy_registry.hpp"
|
||||
#include "game/entities/player_config.hpp"
|
||||
#include "game/stage_system/stage_loader.hpp"
|
||||
#include "game/systems/collision_system.hpp"
|
||||
#include "game/systems/continue_system.hpp"
|
||||
#include "game/systems/enemy_ai_system.hpp"
|
||||
#include "game/systems/init_hud_animator.hpp"
|
||||
|
||||
// Using declarations per simplificar el codi
|
||||
@@ -24,6 +31,20 @@ using SceneManager::SceneContext;
|
||||
using SceneType = SceneContext::SceneType;
|
||||
using Option = SceneContext::Option;
|
||||
|
||||
namespace {
|
||||
// Attract mode: durada fixa de la demo. Amb vides infinites, sempre dura
|
||||
// això (les morts respawnegen); només input o aquest timeout la tallen.
|
||||
constexpr float DEMO_DURATION = 35.0F;
|
||||
|
||||
// Qualsevol d'aquestes accions trenca la demo i torna al títol.
|
||||
constexpr std::array<InputAction, 5> DEMO_EXIT_ACTIONS = {
|
||||
InputAction::LEFT,
|
||||
InputAction::RIGHT,
|
||||
InputAction::THRUST,
|
||||
InputAction::SHOOT,
|
||||
InputAction::START};
|
||||
} // namespace
|
||||
|
||||
GameScene::GameScene(SDLManager& sdl, SceneContext& context)
|
||||
: sdl_(sdl),
|
||||
context_(context),
|
||||
@@ -34,7 +55,8 @@ GameScene::GameScene(SDLManager& sdl, SceneContext& context)
|
||||
text_(sdl.getRenderer()),
|
||||
starfield_parallax_(sdl.getRenderer()),
|
||||
playfield_(sdl.getRenderer()),
|
||||
border_(sdl.getRenderer()) {
|
||||
border_(sdl.getRenderer()),
|
||||
curtain_(sdl.getRenderer()) {
|
||||
// Recuperar configuración de match des del context
|
||||
match_config_ = context_.getMatchConfig();
|
||||
|
||||
@@ -49,9 +71,36 @@ GameScene::GameScene(SDLManager& sdl, SceneContext& context)
|
||||
auto option = context_.consumeOption();
|
||||
(void)option; // Suprimir warning de variable no usada
|
||||
|
||||
// Inicialitzar naves con renderer (P1=ship.shp, P2=ship2.shp)
|
||||
ships_[0] = Ship(sdl.getRenderer(), "ship.shp"); // Jugador 1: nave estàndar
|
||||
ships_[1] = Ship(sdl.getRenderer(), "ship2.shp"); // Jugador 2: interceptor con ales
|
||||
// Carregar la configuració del player des de YAML. Sense fallback: si
|
||||
// falla, abortem (la nau no és construïble sense paràmetres).
|
||||
auto player_yaml = Entities::EntityLoader::load("player");
|
||||
if (!player_yaml) {
|
||||
std::cerr << "[GameScene] FATAL: no s'ha pogut carregar data/entities/player/player.yaml\n";
|
||||
std::exit(EXIT_FAILURE);
|
||||
}
|
||||
auto player_config = PlayerConfig::fromYaml(*player_yaml);
|
||||
if (!player_config) {
|
||||
std::cerr << "[GameScene] FATAL: player.yaml mal format\n";
|
||||
std::exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
// Carregar les configuracions dels 3 enemics. Sense fallback: si falla,
|
||||
// abortem (els enemics no es poden construir sense els seus paràmetres).
|
||||
if (!EnemyRegistry::loadAll()) {
|
||||
std::cerr << "[GameScene] FATAL: no s'han pogut carregar els enemics YAML\n";
|
||||
std::exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
// Carregar la configuració de la bala. Cal abans de construir el pool de
|
||||
// bullets, ja que cada Bullet llegeix el registry al seu ctor.
|
||||
if (!BulletRegistry::load()) {
|
||||
std::cerr << "[GameScene] FATAL: no s'ha pogut carregar bullet.yaml\n";
|
||||
std::exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
// Inicialitzar naves: P1 amb el shape del YAML, P2 amb override visual.
|
||||
ships_[0] = Ship(sdl.getRenderer(), *player_config); // Jugador 1: nau estàndard
|
||||
ships_[1] = Ship(sdl.getRenderer(), *player_config, "ship/wedge.shp"); // Jugador 2: triangle amb cercle central
|
||||
|
||||
// Inicialitzar balas con renderer
|
||||
std::ranges::fill(bullets_, Bullet(sdl.getRenderer()));
|
||||
@@ -107,10 +156,30 @@ GameScene::GameScene(SDLManager& sdl, SceneContext& context)
|
||||
|
||||
// Initialize stage manager
|
||||
stage_manager_ = std::make_unique<StageSystem::StageManager>(stage_config_.get());
|
||||
if (match_config_.mode == GameConfig::Mode::DEMO) {
|
||||
// Attract mode: arrencar directament en PLAYING a l'escenari curat
|
||||
// actual (partida "ja començada") i avançar l'índex perquè la pròxima
|
||||
// demo mostri un escenari diferent. El nombre de jugadors ja l'ha fixat
|
||||
// TitleScene al match_config llegint el mateix escenari.
|
||||
const Systems::Demo::Scenario SC = Systems::Demo::scenario(context_.demoScenarioIndex());
|
||||
context_.advanceDemoScenario();
|
||||
stage_manager_->initDemo(SC.stage);
|
||||
demo_timer_ = DEMO_DURATION;
|
||||
// Silenciar els SFX durant la demo (la música segueix). Guardem l'estat
|
||||
// previ per restaurar-lo al destructor sense xafar la preferència de l'usuari.
|
||||
sound_was_enabled_ = Audio::get()->isSoundEnabled();
|
||||
Audio::get()->enableSound(false);
|
||||
// El fons (graella) ha d'aparèixer ja muntat: la demo és una partida en marxa.
|
||||
playfield_.completeBuild();
|
||||
// La cortinilla arrenca tapant i cau per destapar la demo (continua el
|
||||
// moviment iniciat al títol, que va acabar amb la pantalla negra).
|
||||
curtain_.reveal(Defaults::Game::Curtain::REVEAL_DURATION);
|
||||
} else {
|
||||
stage_manager_->init();
|
||||
}
|
||||
|
||||
// Set ship position reference for safe spawn (P1 for now, TODO: dual tracking)
|
||||
stage_manager_->getSpawnController().setShipPosition(&ships_[0].getCenter());
|
||||
stage_manager_->getWaveRunner().setShipPosition(&ships_[0].getCenter());
|
||||
|
||||
// Inicialitzar timers de muerte per player
|
||||
hit_timer_per_player_[0] = 0.0F;
|
||||
@@ -154,7 +223,7 @@ GameScene::GameScene(SDLManager& sdl, SceneContext& context)
|
||||
// Registramos el body al world incluso inactivo: con radius=0 no colisiona
|
||||
// ni se mueve, y al init() del stage system se activa sin re-registrar.
|
||||
for (auto& enemy : enemies_) {
|
||||
enemy.setShipPosition(&ships_[0].getCenter()); // Set ship reference (P1 for now)
|
||||
enemy.setShips(ships_.data(), &ships_[1]);
|
||||
physics_world_.addBody(&enemy.getBody());
|
||||
// DON'T call enemy.init() here - stage system handles spawning
|
||||
}
|
||||
@@ -172,6 +241,13 @@ GameScene::GameScene(SDLManager& sdl, SceneContext& context)
|
||||
init_hud_rect_sound_played_ = false;
|
||||
}
|
||||
|
||||
GameScene::~GameScene() {
|
||||
// Si la demo havia silenciat els SFX, restaurar l'estat previ en sortir.
|
||||
if (match_config_.mode == GameConfig::Mode::DEMO) {
|
||||
Audio::get()->enableSound(sound_was_enabled_);
|
||||
}
|
||||
}
|
||||
|
||||
auto GameScene::isFinished() const -> bool {
|
||||
return context_.nextScene() != SceneType::GAME;
|
||||
}
|
||||
@@ -194,7 +270,12 @@ void GameScene::update(float delta_time) {
|
||||
// mantener update() legible y reducir complejidad cognitiva.
|
||||
stepPhysics(delta_time);
|
||||
|
||||
if (game_over_state_ == GameOverState::NONE) {
|
||||
if (match_config_.mode == GameConfig::Mode::DEMO) {
|
||||
// Mode demo (attract): salida por input/timeout/muerte + control del pilot.
|
||||
if (stepDemo(delta_time)) {
|
||||
return;
|
||||
}
|
||||
} else if (game_over_state_ == GameOverState::NONE) {
|
||||
stepShootingInput();
|
||||
stepMidGameJoin();
|
||||
}
|
||||
@@ -267,6 +348,66 @@ void GameScene::stepShootingInput() {
|
||||
}
|
||||
}
|
||||
|
||||
void GameScene::updateShipsControl(float delta_time) {
|
||||
const bool DEMO = (match_config_.mode == GameConfig::Mode::DEMO);
|
||||
for (uint8_t i = 0; i < 2; i++) {
|
||||
const bool ACTIU = (i == 0) ? match_config_.player1_active : match_config_.player2_active;
|
||||
if (!ACTIU || hit_timer_per_player_[i] != 0.0F) {
|
||||
continue;
|
||||
}
|
||||
// En demo, cada nau activa es mou amb el seu pilot IA (control calculat
|
||||
// a stepDemo); la resta de casos llegeixen Input com sempre.
|
||||
if (DEMO) {
|
||||
ships_[i].applyMovement(demo_ctrls_[i].left, demo_ctrls_[i].right, demo_ctrls_[i].thrust, delta_time);
|
||||
} else {
|
||||
ships_[i].processInput(delta_time, i);
|
||||
}
|
||||
ships_[i].update(delta_time);
|
||||
}
|
||||
}
|
||||
|
||||
auto GameScene::stepDemo(float delta_time) -> bool {
|
||||
curtain_.update(delta_time); // cortinilla que destapa la demo
|
||||
|
||||
// Qualsevol input trenca la demo i torna al títol (música intacta).
|
||||
if (Input::get()->checkAnyPlayerAction(DEMO_EXIT_ACTIONS)) {
|
||||
context_.setNextScene(SceneType::TITLE, Option::JUMP_TO_TITLE_MAIN);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Vides infinites: la demo dura sempre el temps fix; en morir, stepDeathSequence
|
||||
// respawneja (no acaba ni passa per CONTINUE/GAME_OVER).
|
||||
demo_timer_ -= delta_time;
|
||||
if (demo_timer_ <= 0.0F) {
|
||||
endDemo();
|
||||
return true;
|
||||
}
|
||||
|
||||
// Control de cada nau activa per al frame; el disparo el dispara GameScene.
|
||||
for (uint8_t i = 0; i < 2; i++) {
|
||||
const bool ACTIU = (i == 0) ? match_config_.player1_active : match_config_.player2_active;
|
||||
if (!ACTIU || hit_timer_per_player_[i] != 0.0F) {
|
||||
demo_ctrls_[i] = {}; // nau inactiva/morta: sense control
|
||||
continue;
|
||||
}
|
||||
demo_ctrls_[i] = demo_pilots_[i].compute(
|
||||
ships_[i],
|
||||
enemies_,
|
||||
bullets_,
|
||||
Defaults::Zones::PLAYAREA,
|
||||
delta_time);
|
||||
if (demo_ctrls_[i].shoot) {
|
||||
fireBullet(i);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void GameScene::endDemo() {
|
||||
// No parem la música: title.ogg segueix sonant durant el cicle atrae.
|
||||
context_.setNextScene(SceneType::LOGO);
|
||||
}
|
||||
|
||||
void GameScene::stepMidGameJoin() {
|
||||
// Permitir join solo durante PLAYING.
|
||||
if (stage_manager_->getState() != StageSystem::EstatStage::PLAYING) {
|
||||
@@ -322,6 +463,7 @@ auto GameScene::stepContinueScreen(float delta_time) -> bool {
|
||||
|
||||
// Enemies, bullets y efectos siguen moviéndose en background.
|
||||
for (auto& enemy : enemies_) {
|
||||
Systems::EnemyAi::move(enemy, delta_time);
|
||||
enemy.update(delta_time);
|
||||
}
|
||||
for (auto& bullet : bullets_) {
|
||||
@@ -342,12 +484,13 @@ auto GameScene::stepGameOver(float delta_time) -> bool {
|
||||
game_over_timer_ -= delta_time;
|
||||
if (game_over_timer_ <= 0.0F) {
|
||||
Audio::get()->stopMusic();
|
||||
context_.setNextScene(SceneType::TITLE);
|
||||
context_.setNextScene(SceneType::LOGO);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Enemies, bullets y efectos siguen moviéndose como fondo.
|
||||
for (auto& enemy : enemies_) {
|
||||
Systems::EnemyAi::move(enemy, delta_time);
|
||||
enemy.update(delta_time);
|
||||
}
|
||||
for (auto& bullet : bullets_) {
|
||||
@@ -374,6 +517,15 @@ void GameScene::stepDeathSequence(float delta_time) {
|
||||
}
|
||||
|
||||
// *** PHASE 3: RESPAWN OR GAME OVER ***
|
||||
// Mode demo: vides infinites. Respawn sempre, sense decrementar vides ni
|
||||
// passar mai per CONTINUE/GAME_OVER — la demo dura el seu temps fix.
|
||||
if (match_config_.mode == GameConfig::Mode::DEMO) {
|
||||
Vec2 spawn_pos = getSpawnPoint(i);
|
||||
ships_[i].init(&spawn_pos, /*activar_invulnerabilitat=*/true);
|
||||
hit_timer_per_player_[i] = 0.0F;
|
||||
continue;
|
||||
}
|
||||
|
||||
lives_per_player_[i]--;
|
||||
if (lives_per_player_[i] > 0) {
|
||||
Vec2 spawn_pos = getSpawnPoint(i);
|
||||
@@ -397,6 +549,7 @@ void GameScene::stepDeathSequence(float delta_time) {
|
||||
// aunque otros jugadores aún jueguen.
|
||||
if (algun_mort) {
|
||||
for (auto& enemy : enemies_) {
|
||||
Systems::EnemyAi::move(enemy, delta_time);
|
||||
enemy.update(delta_time);
|
||||
}
|
||||
for (auto& bullet : bullets_) {
|
||||
@@ -461,13 +614,7 @@ void GameScene::runStageLevelStart(float delta_time) {
|
||||
stage_manager_->update(delta_time);
|
||||
|
||||
// Ambas naves pueden moverse y disparar durante el intro.
|
||||
for (uint8_t i = 0; i < 2; i++) {
|
||||
const bool ACTIU = (i == 0) ? match_config_.player1_active : match_config_.player2_active;
|
||||
if (ACTIU && hit_timer_per_player_[i] == 0.0F) {
|
||||
ships_[i].processInput(delta_time, i);
|
||||
ships_[i].update(delta_time);
|
||||
}
|
||||
}
|
||||
updateShipsControl(delta_time);
|
||||
for (auto& bullet : bullets_) {
|
||||
bullet.update(delta_time);
|
||||
}
|
||||
@@ -478,26 +625,22 @@ void GameScene::runStageLevelStart(float delta_time) {
|
||||
|
||||
void GameScene::runStagePlaying(float delta_time) {
|
||||
const bool PAUSE_SPAWN = (hit_timer_per_player_[0] > 0.0F && hit_timer_per_player_[1] > 0.0F);
|
||||
stage_manager_->getSpawnController().update(delta_time, enemies_, PAUSE_SPAWN);
|
||||
stage_manager_->getWaveRunner().update(delta_time, enemies_, PAUSE_SPAWN);
|
||||
|
||||
// Stage completado: cuando al menos un jugador está vivo y todos los enemies muertos.
|
||||
// Stage completado: cuando al menos un jugador está vivo y todas las onades emeses y arena buida.
|
||||
const bool ALGU_VIU = (hit_timer_per_player_[0] == 0.0F || hit_timer_per_player_[1] == 0.0F);
|
||||
if (ALGU_VIU && stage_manager_->getSpawnController().allEnemiesDestroyed(enemies_)) {
|
||||
if (ALGU_VIU && stage_manager_->getWaveRunner().stageComplete(enemies_)) {
|
||||
stage_manager_->markStageCompleted();
|
||||
Audio::get()->playSound(Defaults::Sound::GOOD_JOB_COMMANDER, Audio::Group::GAME);
|
||||
return;
|
||||
}
|
||||
|
||||
// Gameplay normal: ships activos + entidades + colisiones + efectos.
|
||||
for (uint8_t i = 0; i < 2; i++) {
|
||||
const bool ACTIU = (i == 0) ? match_config_.player1_active : match_config_.player2_active;
|
||||
if (ACTIU && hit_timer_per_player_[i] == 0.0F) {
|
||||
ships_[i].processInput(delta_time, i);
|
||||
ships_[i].update(delta_time);
|
||||
}
|
||||
}
|
||||
for (auto& enemy : enemies_) {
|
||||
enemy.update(delta_time);
|
||||
updateShipsControl(delta_time);
|
||||
auto ai_ctx = buildCollisionContext();
|
||||
for (std::size_t i = 0; i < enemies_.size(); ++i) {
|
||||
Systems::EnemyAi::tick(ai_ctx, enemies_[i], i, delta_time);
|
||||
enemies_[i].update(delta_time);
|
||||
}
|
||||
|
||||
// Col·lisions primer, després desactivació per fora-de-zone: així una bala que
|
||||
@@ -515,13 +658,7 @@ void GameScene::runStagePlaying(float delta_time) {
|
||||
|
||||
void GameScene::runStageLevelCompleted(float delta_time) {
|
||||
stage_manager_->update(delta_time);
|
||||
for (uint8_t i = 0; i < 2; i++) {
|
||||
const bool ACTIU = (i == 0) ? match_config_.player1_active : match_config_.player2_active;
|
||||
if (ACTIU && hit_timer_per_player_[i] == 0.0F) {
|
||||
ships_[i].processInput(delta_time, i);
|
||||
ships_[i].update(delta_time);
|
||||
}
|
||||
}
|
||||
updateShipsControl(delta_time);
|
||||
for (auto& bullet : bullets_) {
|
||||
bullet.update(delta_time);
|
||||
}
|
||||
@@ -531,8 +668,8 @@ void GameScene::runStageLevelCompleted(float delta_time) {
|
||||
floating_score_manager_.update(delta_time);
|
||||
}
|
||||
|
||||
void GameScene::runCollisionDetections() {
|
||||
Systems::Collision::Context col_ctx{
|
||||
auto GameScene::buildCollisionContext() -> Systems::Collision::Context {
|
||||
return Systems::Collision::Context{
|
||||
.ships = ships_,
|
||||
.enemies = enemies_,
|
||||
.bullets = bullets_,
|
||||
@@ -543,8 +680,12 @@ void GameScene::runCollisionDetections() {
|
||||
.firework_manager = firework_manager_,
|
||||
.floating_score_manager = floating_score_manager_,
|
||||
.match_config = match_config_,
|
||||
.on_player_hit = [this](uint8_t pid) { tocado(pid); },
|
||||
.on_player_hit = [this](uint8_t pid, const Vec2& bv) { tocado(pid, bv); },
|
||||
};
|
||||
}
|
||||
|
||||
void GameScene::runCollisionDetections() {
|
||||
auto col_ctx = buildCollisionContext();
|
||||
Systems::Collision::detectAll(col_ctx);
|
||||
}
|
||||
|
||||
@@ -573,6 +714,10 @@ void GameScene::draw() {
|
||||
drawLevelCompletedState();
|
||||
break;
|
||||
}
|
||||
|
||||
// Cortinilla d'entrada de la demo: per damunt de tot. No-op fora del mode
|
||||
// DEMO (curtain_ mai s'arrenca) i quan ja ha sortit per baix.
|
||||
curtain_.draw();
|
||||
}
|
||||
|
||||
void GameScene::drawEnemies() const {
|
||||
@@ -669,7 +814,7 @@ void GameScene::drawInitHudState() {
|
||||
}
|
||||
|
||||
if (score_progress > 0.0F) {
|
||||
Systems::InitHud::drawScoreboardAnimated(text_, buildScoreboard(), score_progress);
|
||||
Systems::InitHud::drawScoreboardAnimated(text_, buildScoreboardSegments(), score_progress);
|
||||
}
|
||||
|
||||
if (ship1_progress > 0.0F && match_config_.player1_active && ships_[0].isActive()) {
|
||||
@@ -723,7 +868,7 @@ void GameScene::drawLevelCompletedState() {
|
||||
drawScoreboard();
|
||||
}
|
||||
|
||||
void GameScene::tocado(uint8_t player_id) {
|
||||
void GameScene::tocado(uint8_t player_id, const Vec2& bullet_velocity) {
|
||||
// Death sequence: 3 phases
|
||||
// Phase 1: First call (hit_timer_per_player_[player_id] == 0) - trigger explosion
|
||||
// Phase 2: Animation (0 < itocado_ < 3.0s) - debris animation
|
||||
@@ -747,6 +892,9 @@ void GameScene::tocado(uint8_t player_id) {
|
||||
|
||||
// Mateixa dispersió i efecte que els debris d'enemic (lifetime,
|
||||
// friction, segment_multiplier alineats); només canvien sound i color.
|
||||
// bullet_velocity arriba a explode() com a impuls extra independent
|
||||
// de la inèrcia del cos del ship — els trossos volen amb la força
|
||||
// de la bala encara que el ship estiga quiet.
|
||||
debris_manager_.explode(
|
||||
ships_[player_id].getShape(),
|
||||
SHIP_POS,
|
||||
@@ -757,11 +905,12 @@ void GameScene::tocado(uint8_t player_id) {
|
||||
INHERITED_VEL,
|
||||
0.0F, // sense herència angular
|
||||
0.0F, // sin herencia visual
|
||||
Defaults::Sound::EXPLOSION2,
|
||||
Defaults::Palette::SHIP,
|
||||
Defaults::Sound::PLAYER_EXPLOSION,
|
||||
ships_[player_id].getConfig().colors.normal,
|
||||
Defaults::Physics::Debris::ENEMY_LIFETIME,
|
||||
Defaults::Physics::Debris::ENEMY_FRICTION,
|
||||
Defaults::Physics::Debris::ENEMY_SEGMENT_MULTIPLIER);
|
||||
Defaults::Physics::Debris::ENEMY_SEGMENT_MULTIPLIER,
|
||||
bullet_velocity);
|
||||
|
||||
// Start death timer (non-zero to avoid re-triggering)
|
||||
hit_timer_per_player_[player_id] = Defaults::Game::HIT_TIMER_TRIGGER_DEATH;
|
||||
@@ -771,59 +920,55 @@ void GameScene::tocado(uint8_t player_id) {
|
||||
}
|
||||
|
||||
void GameScene::drawScoreboard() {
|
||||
// Construir text del marcador
|
||||
std::string text = buildScoreboard();
|
||||
|
||||
// Parámetros de renderització
|
||||
const float SCALE = Defaults::Hud::SCOREBOARD_TEXT_SCALE;
|
||||
const float SPACING = Defaults::Hud::SCOREBOARD_TEXT_SPACING;
|
||||
|
||||
// Calcular centro de la zone del marcador
|
||||
const SDL_FRect& scoreboard_zone = Defaults::Zones::SCOREBOARD;
|
||||
float center_x = scoreboard_zone.w / 2.0F;
|
||||
float center_y = scoreboard_zone.y + (scoreboard_zone.h / 2.0F);
|
||||
|
||||
// Renderizar centrat
|
||||
text_.renderCentered(text, {.x = center_x, .y = center_y}, SCALE, SPACING);
|
||||
const Vec2 CENTER = {
|
||||
.x = scoreboard_zone.w / 2.0F,
|
||||
.y = scoreboard_zone.y + (scoreboard_zone.h / 2.0F),
|
||||
};
|
||||
// En mode demo (attract) el marcador no té sentit: substituïm puntuacions i
|
||||
// vides per un rètol que indica que és una demo i convida a jugar.
|
||||
if (match_config_.mode == GameConfig::Mode::DEMO) {
|
||||
text_.renderCentered(Locale::get().text("demo.banner"), CENTER, SCALE, SPACING);
|
||||
return;
|
||||
}
|
||||
Systems::InitHud::drawScoreboardSegmentsAt(text_, buildScoreboardSegments(), CENTER, SCALE, SPACING);
|
||||
}
|
||||
|
||||
auto GameScene::buildScoreboard() const -> std::string {
|
||||
// Puntuación P1 (6 dígits) - mostrar zeros si inactiu
|
||||
std::string score_p1;
|
||||
std::string vides_p1;
|
||||
auto GameScene::buildScoreboardSegments() const -> Systems::InitHud::ScoreboardSegments {
|
||||
Systems::InitHud::ScoreboardSegments out;
|
||||
|
||||
// Puntuació P1 (6 dígits) - zeros si inactiu
|
||||
if (match_config_.player1_active) {
|
||||
score_p1 = std::to_string(score_per_player_[0]);
|
||||
score_p1 = std::string(6 - std::min(6, static_cast<int>(score_p1.length())), '0') + score_p1;
|
||||
vides_p1 = (lives_per_player_[0] < 10)
|
||||
std::string s = std::to_string(score_per_player_[0]);
|
||||
out.score_p1 = std::string(6 - std::min(6, static_cast<int>(s.length())), '0') + s;
|
||||
out.lives_p1 = (lives_per_player_[0] < 10)
|
||||
? "0" + std::to_string(lives_per_player_[0])
|
||||
: std::to_string(lives_per_player_[0]);
|
||||
} else {
|
||||
score_p1 = "000000";
|
||||
vides_p1 = "00";
|
||||
out.score_p1 = "000000";
|
||||
out.lives_p1 = "00";
|
||||
}
|
||||
|
||||
// Nivel (2 dígits)
|
||||
uint8_t stage_num = stage_manager_->getCurrentStage();
|
||||
std::string stage_str = (stage_num < 10) ? "0" + std::to_string(stage_num)
|
||||
: std::to_string(stage_num);
|
||||
// Nivell (2 dígits) amb label localitzat
|
||||
const uint8_t STAGE_NUM = stage_manager_->getCurrentStage();
|
||||
const std::string STAGE_STR = (STAGE_NUM < 10) ? "0" + std::to_string(STAGE_NUM)
|
||||
: std::to_string(STAGE_NUM);
|
||||
out.level = Locale::get().text("hud.level") + STAGE_STR;
|
||||
|
||||
// Puntuación P2 (6 dígits) - mostrar zeros si inactiu
|
||||
std::string score_p2;
|
||||
std::string vides_p2;
|
||||
// Puntuació P2 (6 dígits) - zeros si inactiu
|
||||
if (match_config_.player2_active) {
|
||||
score_p2 = std::to_string(score_per_player_[1]);
|
||||
score_p2 = std::string(6 - std::min(6, static_cast<int>(score_p2.length())), '0') + score_p2;
|
||||
vides_p2 = (lives_per_player_[1] < 10)
|
||||
std::string s = std::to_string(score_per_player_[1]);
|
||||
out.score_p2 = std::string(6 - std::min(6, static_cast<int>(s.length())), '0') + s;
|
||||
out.lives_p2 = (lives_per_player_[1] < 10)
|
||||
? "0" + std::to_string(lives_per_player_[1])
|
||||
: std::to_string(lives_per_player_[1]);
|
||||
} else {
|
||||
score_p2 = "000000";
|
||||
vides_p2 = "00";
|
||||
out.score_p2 = "000000";
|
||||
out.lives_p2 = "00";
|
||||
}
|
||||
|
||||
// Format: "123456 03 LEVEL 01 654321 02"
|
||||
// Nota: dos espais entre seccions, mantenir ambdós slots siempre visibles
|
||||
return score_p1 + " " + vides_p1 + " " + Locale::get().text("hud.level") + stage_str + " " + score_p2 + " " + vides_p2;
|
||||
return out;
|
||||
}
|
||||
|
||||
// [NEW] Stage system helper methods
|
||||
@@ -944,7 +1089,7 @@ void GameScene::fireBullet(uint8_t player_id) {
|
||||
const int START_IDX = player_id * SLOTS_PER_PLAYER;
|
||||
for (int i = START_IDX; i < START_IDX + SLOTS_PER_PLAYER; i++) {
|
||||
if (!bullets_[i].isActive()) {
|
||||
bullets_[i].fire(fire_position, ship_angle, player_id);
|
||||
bullets_[i].fire(fire_position, ship_angle, player_id, ships_[player_id].getConfig().weapon.bullet_speed);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
#include <string>
|
||||
|
||||
#include "core/graphics/border.hpp"
|
||||
#include "core/graphics/curtain.hpp"
|
||||
#include "core/graphics/playfield.hpp"
|
||||
#include "core/graphics/starfield_parallax.hpp"
|
||||
#include "core/graphics/vector_text.hpp"
|
||||
@@ -28,6 +29,9 @@
|
||||
#include "game/entities/ship.hpp"
|
||||
#include "game/stage_system/stage_config.hpp"
|
||||
#include "game/stage_system/stage_manager.hpp"
|
||||
#include "game/systems/collision_system.hpp"
|
||||
#include "game/systems/demo_pilot.hpp"
|
||||
#include "game/systems/init_hud_animator.hpp"
|
||||
|
||||
// Game over state machine
|
||||
enum class GameOverState : uint8_t {
|
||||
@@ -40,7 +44,7 @@ enum class GameOverState : uint8_t {
|
||||
class GameScene final : public Scene {
|
||||
public:
|
||||
explicit GameScene(SDLManager& sdl, SceneManager::SceneContext& context);
|
||||
~GameScene() override = default;
|
||||
~GameScene() override; // Restaura l'estat dels SFX si la demo els ha silenciat
|
||||
|
||||
// Scene interface
|
||||
void handleEvent(const SDL_Event& event) override;
|
||||
@@ -67,7 +71,7 @@ class GameScene final : public Scene {
|
||||
std::array<Enemy, Constants::MAX_ORNIS> enemies_;
|
||||
// 6 balas: P1=[0,1,2], P2=[3,4,5]. El cast a size_t evita la
|
||||
// widening conversion implícita que detecta clang-tidy.
|
||||
std::array<Bullet, static_cast<std::size_t>(Constants::MAX_BULLETS) * 2> bullets_;
|
||||
std::array<Bullet, static_cast<std::size_t>(Defaults::Entities::MAX_BULLETS_TOTAL)> bullets_;
|
||||
std::array<float, 2> hit_timer_per_player_; // Death timers per player (seconds)
|
||||
|
||||
// Lives and game over system
|
||||
@@ -92,6 +96,9 @@ class GameScene final : public Scene {
|
||||
// Border del playfield (4 línies amb desplaçaments i flash per impactes)
|
||||
Graphics::Border border_;
|
||||
|
||||
// Cortinilla que destapa en entrar a la demo (només mode DEMO; inactiva en partida normal).
|
||||
Graphics::Curtain curtain_;
|
||||
|
||||
// [NEW] Stage system
|
||||
std::unique_ptr<StageSystem::StageSystemConfig> stage_config_;
|
||||
std::unique_ptr<StageSystem::StageManager> stage_manager_;
|
||||
@@ -99,8 +106,17 @@ class GameScene final : public Scene {
|
||||
// Control de sons de animación INIT_HUD
|
||||
bool init_hud_rect_sound_played_{false}; // Flag para evitar repetir sonido del rectángulo
|
||||
|
||||
// Attract mode (mode DEMO): un pilot IA per nau activa (1 o 2 jugadors).
|
||||
std::array<Systems::Demo::DemoPilot, 2> demo_pilots_;
|
||||
std::array<Systems::Demo::Control, 2> demo_ctrls_{}; // Control per nau al frame actual
|
||||
float demo_timer_{0.0F}; // Temps restant de la demo (→ LOGO)
|
||||
bool sound_was_enabled_{true}; // Estat dels SFX abans de la demo (per restaurar-lo)
|
||||
|
||||
// Funciones privades
|
||||
void tocado(uint8_t player_id);
|
||||
// bullet_velocity: velocitat de la bala que ha causat la mort (Vec2{} si no
|
||||
// ve d'una bala). Es passa al debris perquè els fragments volin en direcció
|
||||
// de la bala (independent de la inèrcia del cos del ship).
|
||||
void tocado(uint8_t player_id, const Vec2& bullet_velocity = {.x = 0.0F, .y = 0.0F});
|
||||
void drawScoreboard(); // Dibuixar marcador de puntuación
|
||||
void fireBullet(uint8_t player_id); // Shoot bullet from player
|
||||
[[nodiscard]] auto getSpawnPoint(uint8_t player_id) const -> Vec2; // Get spawn position for player
|
||||
@@ -124,14 +140,22 @@ class GameScene final : public Scene {
|
||||
void drawPlayingState();
|
||||
void drawLevelCompletedState();
|
||||
|
||||
// [NEW] Función helper del marcador
|
||||
[[nodiscard]] auto buildScoreboard() const -> std::string;
|
||||
// [NEW] Helper del marcador: construeix els 5 segments (score_p1, vides_p1,
|
||||
// level, score_p2, vides_p2) per a render colorit per segment.
|
||||
[[nodiscard]] auto buildScoreboardSegments() const -> Systems::InitHud::ScoreboardSegments;
|
||||
|
||||
// Sub-pasos de update() (descompuestos en Fase 9d para reducir
|
||||
// complejidad cognitiva; cada uno es responsable de una sección).
|
||||
void stepPhysics(float delta_time);
|
||||
void stepShootingInput();
|
||||
void stepMidGameJoin();
|
||||
// Mueve las naves activas: en mode DEMO cada nau usa su pilot IA (demo_ctrls_),
|
||||
// el resto usa processInput (Input). Compartido por los 3 estados jugables.
|
||||
void updateShipsControl(float delta_time);
|
||||
// Mode DEMO: gestiona salida (input→título, timeout/muerte→logo) y calcula
|
||||
// el control + disparo del pilot. Devuelve true si la escena transiciona.
|
||||
[[nodiscard]] auto stepDemo(float delta_time) -> bool;
|
||||
void endDemo();
|
||||
// Devuelven true si el frame debe salir tras esta sección.
|
||||
[[nodiscard]] auto stepContinueScreen(float delta_time) -> bool;
|
||||
[[nodiscard]] auto stepGameOver(float delta_time) -> bool;
|
||||
@@ -144,6 +168,10 @@ class GameScene final : public Scene {
|
||||
void runStageLevelStart(float delta_time);
|
||||
void runStagePlaying(float delta_time);
|
||||
void runStageLevelCompleted(float delta_time);
|
||||
// Construeix el Collision::Context del frame actual (referències a tots els
|
||||
// pools/managers + on_player_hit). Reutilitzat tant per al tick d'IA com
|
||||
// per a runCollisionDetections.
|
||||
[[nodiscard]] auto buildCollisionContext() -> Systems::Collision::Context;
|
||||
// Helper: ejecuta colisiones de gameplay con el Context preparado.
|
||||
void runCollisionDetections();
|
||||
};
|
||||
|
||||
@@ -55,6 +55,11 @@ LogoScene::LogoScene(SDLManager& sdl, SceneContext& context)
|
||||
(void)option; // Suprimir warning
|
||||
|
||||
sound_played_.fill(false); // Inicialitzar seguiment de sons
|
||||
|
||||
// Si ja sona música (venim de la demo del cicle d'atracció), operar en
|
||||
// silenci: ni sons de lletres ni reinici de title.ogg.
|
||||
attract_silent_ = (Audio::getMusicState() == Audio::MusicState::PLAYING);
|
||||
|
||||
initLetters();
|
||||
}
|
||||
|
||||
@@ -171,8 +176,11 @@ void LogoScene::changeState(AnimationState nou_estat) {
|
||||
std::mt19937 g(rd());
|
||||
std::shuffle(explosion_order_.begin(), explosion_order_.end(), g);
|
||||
} else if (nou_estat == AnimationState::POST_EXPLOSION) {
|
||||
// En el cicle d'atracció la música ja sona; no la reiniciem.
|
||||
if (!attract_silent_) {
|
||||
Audio::get()->playMusic("title.ogg");
|
||||
}
|
||||
}
|
||||
|
||||
std::cout << "[LogoScene] Canvi a state: " << static_cast<int>(nou_estat)
|
||||
<< "\n";
|
||||
@@ -200,8 +208,12 @@ void LogoScene::updateExplosions(float delta_time) {
|
||||
FINAL_SCALE, // Escala (lletres a scale final)
|
||||
SPEED_EXPLOSIO, // Velocidad base
|
||||
1.0F, // Brightness màxim (per defecte)
|
||||
{.x = 0.0F, .y = 0.0F} // Sin velocity (per defecte)
|
||||
);
|
||||
{.x = 0.0F, .y = 0.0F}, // Sin velocity (per defecte)
|
||||
0.0F, // Velocitat angular (per defecte)
|
||||
0.0F, // Factor herència visual (per defecte)
|
||||
// Dins el cicle d'atracció les explosions són mudes; fora, so
|
||||
// d'explosió per defecte.
|
||||
attract_silent_ ? "" : Defaults::Sound::ENEMY_EXPLOSION);
|
||||
|
||||
std::cout << "[LogoScene] Explota letter " << letter_explosion_index_ << "\n";
|
||||
|
||||
@@ -237,9 +249,13 @@ void LogoScene::update(float delta_time) {
|
||||
global_progress,
|
||||
LETTER_THRESHOLD);
|
||||
|
||||
// Reproduir so cuando la letter comença a aparèixer (progress > 0)
|
||||
// Reproduir so cuando la letter comença a aparèixer (progress > 0).
|
||||
// En mode silenciós (cicle d'atracció) saltem el so però igualment
|
||||
// marquem la letter per no acumular pendents.
|
||||
if (letter_progress > 0.0F) {
|
||||
if (!attract_silent_) {
|
||||
Audio::get()->playSound(Defaults::Sound::LOGO, Audio::Group::GAME);
|
||||
}
|
||||
sound_played_[i] = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,6 +67,11 @@ class LogoScene final : public Scene {
|
||||
// Seguiment de sons de lletres (evitar reproduccions repetides)
|
||||
std::array<bool, 9> sound_played_; // Track si cada letter ya ha reproduit el so
|
||||
|
||||
// Cicle d'atracció: si en entrar al logo ja hi ha música sonant (venim de la
|
||||
// demo amb title.ogg en marxa), el logo no ha d'emetre sons ni reiniciar la
|
||||
// música — només repintar-se en silenci.
|
||||
bool attract_silent_{false};
|
||||
|
||||
// Constants de animación
|
||||
static constexpr float DURATION_PRE = 1.5F; // Duració PRE_ANIMATION (pantalla negra)
|
||||
static constexpr float DURATION_ZOOM = 4.0F; // Duració del zoom (segons)
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
#include "core/rendering/shape_renderer.hpp"
|
||||
#include "core/system/scene_context.hpp"
|
||||
#include "core/system/service_menu.hpp"
|
||||
#include "game/systems/demo_pilot.hpp"
|
||||
#include "project.h"
|
||||
|
||||
using SceneManager::SceneContext;
|
||||
@@ -36,7 +37,8 @@ namespace {
|
||||
TitleScene::TitleScene(SDLManager& sdl, SceneContext& context)
|
||||
: sdl_(sdl),
|
||||
context_(context),
|
||||
text_(sdl.getRenderer()) {
|
||||
text_(sdl.getRenderer()),
|
||||
curtain_(sdl.getRenderer()) {
|
||||
std::cout << "SceneType Titol: Inicialitzant...\n";
|
||||
|
||||
match_config_.player1_active = false;
|
||||
@@ -78,7 +80,7 @@ TitleScene::TitleScene(SDLManager& sdl, SceneContext& context)
|
||||
|
||||
// Flash que tapa el "pop" final de la nau al VP. Es spawneja al centre
|
||||
// de pantalla (= projecció del VP) quan ship_animator avisa.
|
||||
flash_shape_ = Graphics::ShapeLoader::load("title_flash.shp");
|
||||
flash_shape_ = Graphics::ShapeLoader::load("effect/title_flash.shp");
|
||||
ship_animator_->setOnShipDisappear([this](int /*player_id*/) {
|
||||
triggerFlash(Vec2{
|
||||
.x = static_cast<float>(Defaults::Window::WIDTH) / 2.0F,
|
||||
@@ -94,8 +96,16 @@ TitleScene::TitleScene(SDLManager& sdl, SceneContext& context)
|
||||
}
|
||||
|
||||
TitleScene::~TitleScene() {
|
||||
// Attract mode: si saltem a la demo, NO parem la música — ha de seguir
|
||||
// sonant durant tot el cicle TÍTOL→DEMO→LOGO→TÍTOL. La resta de sortides
|
||||
// (partida normal, EXIT) sí paren.
|
||||
const bool ENTERING_DEMO =
|
||||
context_.nextScene() == SceneType::GAME &&
|
||||
context_.getMatchConfig().mode == GameConfig::Mode::DEMO;
|
||||
if (!ENTERING_DEMO) {
|
||||
Audio::get()->stopMusic();
|
||||
}
|
||||
}
|
||||
|
||||
void TitleScene::initTitle() {
|
||||
using namespace Graphics;
|
||||
@@ -267,8 +277,9 @@ void TitleScene::dibuixarPeuTitol(float spacing) const {
|
||||
// a 1.0 (a la mida i posició finals, "lluny" al VP).
|
||||
const float SCREEN_CENTRE_X = Defaults::Game::WIDTH / 2.0F;
|
||||
const float SCREEN_CENTRE_Y = Defaults::Game::HEIGHT / 2.0F;
|
||||
const float JAILGAMES_S = std::lerp(S::FOOTER_INTRO_SCALE_START, 1.0F, Easing::easeOutQuad(intro_jailgames_progress_));
|
||||
const float COPYRIGHT_S = std::lerp(S::FOOTER_INTRO_SCALE_START, 1.0F, Easing::easeOutQuad(intro_copyright_progress_));
|
||||
// dive_zoom_ (attract) afegeix el zoom del dive per travessar el peu.
|
||||
const float JAILGAMES_S = dive_zoom_ * std::lerp(S::FOOTER_INTRO_SCALE_START, 1.0F, Easing::easeOutQuad(intro_jailgames_progress_));
|
||||
const float COPYRIGHT_S = dive_zoom_ * std::lerp(S::FOOTER_INTRO_SCALE_START, 1.0F, Easing::easeOutQuad(intro_copyright_progress_));
|
||||
|
||||
const float JAILGAMES_RENDER_SCALE = Defaults::Title::Layout::JAILGAMES_SCALE * JAILGAMES_S;
|
||||
for (const auto& letter : letters_jailgames_) {
|
||||
@@ -324,6 +335,12 @@ void TitleScene::update(float delta_time) {
|
||||
case TitleState::BLACK_SCREEN:
|
||||
updateBlackScreenState(delta_time);
|
||||
break;
|
||||
case TitleState::DEMO_DIVE:
|
||||
updateDemoDiveState(delta_time);
|
||||
break;
|
||||
case TitleState::DEMO_CURTAIN:
|
||||
updateDemoCurtainState(delta_time);
|
||||
break;
|
||||
}
|
||||
|
||||
// Les animacions segueixen pero els inputs es bloquegen mentre el menu
|
||||
@@ -340,6 +357,36 @@ void TitleScene::update(float delta_time) {
|
||||
handleSkipInput();
|
||||
handleStartInput();
|
||||
}
|
||||
|
||||
// Attract mode: al state MAIN, acumular inactivitat; qualsevol botó
|
||||
// arcade la reseteja. En esgotar el timeout, saltar a la demo (mode DEMO,
|
||||
// P1 actiu) sense fer fadeOut de la música (a diferència del START real).
|
||||
if (current_state_ == TitleState::MAIN && !INPUT_BLOCKED) {
|
||||
if (Input::get()->checkAnyPlayerAction(ARCADE_BUTTONS, Input::ALLOW_REPEAT)) {
|
||||
idle_timer_ = 0.0F;
|
||||
} else {
|
||||
idle_timer_ += delta_time;
|
||||
}
|
||||
if (idle_timer_ >= TITLE_DEMO_TIMEOUT) {
|
||||
// L'escenari curat (mateix índex que llegirà GameScene) decideix
|
||||
// quants jugadors IA hi ha. No avancem l'índex ací: ho fa GameScene.
|
||||
const Systems::Demo::Scenario SC = Systems::Demo::scenario(context_.demoScenarioIndex());
|
||||
GameConfig::MatchConfig demo_cfg;
|
||||
demo_cfg.player1_active = true;
|
||||
demo_cfg.player2_active = (SC.players >= 2);
|
||||
demo_cfg.mode = GameConfig::Mode::DEMO;
|
||||
context_.setMatchConfig(demo_cfg);
|
||||
// No saltem en sec: primer un "dive" de càmera cap al punt de fuga
|
||||
// (deixa enrere títol/naus/logo) i després la cortinilla. L'estat
|
||||
// deixa de ser MAIN, així que ni es re-dispara la demo ni s'accepta
|
||||
// START durant la transició. Amaguem ja el "PREMEU START".
|
||||
press_start_visible_ = false;
|
||||
current_state_ = TitleState::DEMO_DIVE;
|
||||
dive_time_ = 0.0F;
|
||||
dive_zoom_ = 1.0F;
|
||||
temps_acumulat_ = 0.0F;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void TitleScene::updateStarfieldFadeInState(float delta_time) {
|
||||
@@ -442,6 +489,50 @@ void TitleScene::updateBlackScreenState(float delta_time) {
|
||||
}
|
||||
}
|
||||
|
||||
void TitleScene::advanceDive(float delta_time) {
|
||||
namespace D = Defaults::Game::Dive;
|
||||
dive_time_ += delta_time;
|
||||
// T SENSE topall: easeInQuad (=T²) fa que la posició creixi quadràticament,
|
||||
// és a dir, la velocitat creix linealment → acceleració constant que no
|
||||
// s'atura. CAMERA_DISTANCE i ZOOM_MAX deixen de ser límits: són el valor
|
||||
// assolit en l'instant de referència (T=1, quan cau la cortinilla) i a
|
||||
// partir d'ací el moviment continua accelerant (std::lerp extrapola).
|
||||
const float T = dive_time_ / D::DURATION;
|
||||
const float EASED = Easing::easeInQuad(T);
|
||||
|
||||
// Càmera 3D real cap a +Z: starfield i naus es projecten amb la càmera, així
|
||||
// que les estrelles es rasguen i les naus creixen i s'escapen pels costats.
|
||||
// IMPORTANT: cal moure posició I target alhora; si només es mou la posició,
|
||||
// forward = (target - position) s'inverteix en passar el target i la càmera
|
||||
// gira cap enrere (tot apareix invertit i mirant a l'espectador).
|
||||
if (camera_ != nullptr) {
|
||||
const float Z = EASED * D::CAMERA_DISTANCE;
|
||||
camera_->setPosition(Vec3{.x = 0.0F, .y = 0.0F, .z = Z});
|
||||
camera_->setTarget(Vec3{.x = 0.0F, .y = 0.0F, .z = Z + 1.0F});
|
||||
}
|
||||
// Logo i peu són 2D: els fakegem el dive amb un zoom des del centre.
|
||||
dive_zoom_ = std::lerp(1.0F, D::ZOOM_MAX, EASED);
|
||||
}
|
||||
|
||||
void TitleScene::updateDemoDiveState(float delta_time) {
|
||||
advanceDive(delta_time);
|
||||
|
||||
// En l'instant de referència (dive_time_ == DURATION) cau la cortinilla,
|
||||
// però la càmera NO s'atura: segueix accelerant a DEMO_CURTAIN.
|
||||
if (dive_time_ >= Defaults::Game::Dive::DURATION) {
|
||||
current_state_ = TitleState::DEMO_CURTAIN;
|
||||
curtain_.cover(Defaults::Game::Curtain::COVER_DURATION);
|
||||
}
|
||||
}
|
||||
|
||||
void TitleScene::updateDemoCurtainState(float delta_time) {
|
||||
advanceDive(delta_time); // la càmera continua accelerant sota la tela
|
||||
curtain_.update(delta_time);
|
||||
if (curtain_.isDone()) {
|
||||
context_.setNextScene(SceneType::GAME);
|
||||
}
|
||||
}
|
||||
|
||||
void TitleScene::handleSkipInput() {
|
||||
if (current_state_ != TitleState::STARFIELD_FADE_IN && current_state_ != TitleState::STARFIELD) {
|
||||
return;
|
||||
@@ -546,7 +637,9 @@ void TitleScene::draw() {
|
||||
(current_state_ == TitleState::STARFIELD_FADE_IN ||
|
||||
current_state_ == TitleState::STARFIELD ||
|
||||
current_state_ == TitleState::MAIN ||
|
||||
current_state_ == TitleState::PLAYER_JOIN_PHASE)) {
|
||||
current_state_ == TitleState::PLAYER_JOIN_PHASE ||
|
||||
current_state_ == TitleState::DEMO_DIVE ||
|
||||
current_state_ == TitleState::DEMO_CURTAIN)) {
|
||||
ship_animator_->draw();
|
||||
}
|
||||
drawFlashes();
|
||||
@@ -555,14 +648,21 @@ void TitleScene::draw() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (current_state_ != TitleState::MAIN && current_state_ != TitleState::PLAYER_JOIN_PHASE) {
|
||||
// DEMO_DIVE/DEMO_CURTAIN es pinten com MAIN (logo + peu) perquè el títol
|
||||
// segueixi visible sota el dive i la cortinilla.
|
||||
if (current_state_ != TitleState::MAIN &&
|
||||
current_state_ != TitleState::PLAYER_JOIN_PHASE &&
|
||||
current_state_ != TitleState::DEMO_DIVE &&
|
||||
current_state_ != TitleState::DEMO_CURTAIN) {
|
||||
curtain_.draw(); // BLACK_SCREEN i altres: només la cortinilla (si activa)
|
||||
return;
|
||||
}
|
||||
|
||||
// Factor d'escala+posició per simular un moviment 3D des de l'usuari (prop,
|
||||
// sprite gran i posició projectada extrema) cap al VP (lluny, sprite a la
|
||||
// seva mida i posició finals). Pivot: centre de pantalla (= projecció VP).
|
||||
const float LOGO_S = std::lerp(Defaults::Title::Sequence::LOGO_INTRO_SCALE_START, 1.0F, Easing::easeOutQuad(intro_logo_progress_));
|
||||
// El dive (attract) hi afegeix un zoom extra (dive_zoom_) per travessar-los.
|
||||
const float LOGO_S = dive_zoom_ * std::lerp(Defaults::Title::Sequence::LOGO_INTRO_SCALE_START, 1.0F, Easing::easeOutQuad(intro_logo_progress_));
|
||||
const float SCREEN_CENTRE_X = Defaults::Game::WIDTH / 2.0F;
|
||||
const float SCREEN_CENTRE_Y = Defaults::Game::HEIGHT / 2.0F;
|
||||
const float LOGO_RENDER_SCALE = Defaults::Title::Layout::LOGO_SCALE * LOGO_S;
|
||||
@@ -626,6 +726,9 @@ void TitleScene::draw() {
|
||||
}
|
||||
|
||||
dibuixarPeuTitol(SPACING);
|
||||
|
||||
// Cortinilla negra (attract): per damunt de tot. No-op si no està activa.
|
||||
curtain_.draw();
|
||||
}
|
||||
|
||||
auto TitleScene::checkSkipButtonPressed() -> bool {
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
#include <vector>
|
||||
|
||||
#include "core/graphics/camera3d.hpp"
|
||||
#include "core/graphics/curtain.hpp"
|
||||
#include "core/graphics/shape.hpp"
|
||||
#include "core/graphics/starfield.hpp"
|
||||
#include "core/graphics/vector_text.hpp"
|
||||
@@ -46,6 +47,8 @@ class TitleScene final : public Scene {
|
||||
MAIN,
|
||||
PLAYER_JOIN_PHASE,
|
||||
BLACK_SCREEN,
|
||||
DEMO_DIVE, // Attract: dive de càmera cap al punt de fuga
|
||||
DEMO_CURTAIN, // Attract: cortinilla negra que cau i tapa abans del salt
|
||||
};
|
||||
|
||||
struct LogoLetter {
|
||||
@@ -60,6 +63,7 @@ class TitleScene final : public Scene {
|
||||
SceneManager::SceneContext& context_;
|
||||
GameConfig::MatchConfig match_config_;
|
||||
Graphics::VectorText text_;
|
||||
Graphics::Curtain curtain_; // Cortinilla negra en saltar a la demo (attract)
|
||||
std::unique_ptr<Graphics::Camera3D> camera_;
|
||||
std::unique_ptr<Graphics::Starfield> starfield_;
|
||||
std::unique_ptr<Title::ShipAnimator> ship_animator_;
|
||||
@@ -79,6 +83,12 @@ class TitleScene final : public Scene {
|
||||
void drawFlashes();
|
||||
TitleState current_state_{TitleState::STARFIELD_FADE_IN};
|
||||
float temps_acumulat_{0.0F};
|
||||
float idle_timer_{0.0F}; // Attract mode: inactivitat acumulada al state MAIN
|
||||
|
||||
// Dive (attract): temps transcorregut i zoom aplicat als elements 2D
|
||||
// (logo + peu) mentre la càmera avança cap al punt de fuga.
|
||||
float dive_time_{0.0F};
|
||||
float dive_zoom_{1.0F};
|
||||
|
||||
std::vector<LogoLetter> letters_orni_;
|
||||
std::vector<LogoLetter> letters_attack_;
|
||||
@@ -110,6 +120,10 @@ class TitleScene final : public Scene {
|
||||
static constexpr float DURATION_BLACK_SCREEN = 2.0F;
|
||||
static constexpr int MUSIC_FADE = 1500;
|
||||
|
||||
// Attract mode: temps d'inactivitat al títol (state MAIN) abans de saltar
|
||||
// a la demo. Qualsevol input el reseteja.
|
||||
static constexpr float TITLE_DEMO_TIMEOUT = 20.0F;
|
||||
|
||||
static constexpr float ORBIT_AMPLITUDE_X = 4.0F;
|
||||
static constexpr float ORBIT_AMPLITUDE_Y = 3.0F;
|
||||
static constexpr float ORBIT_FREQUENCY_X = 0.8F;
|
||||
@@ -138,6 +152,13 @@ class TitleScene final : public Scene {
|
||||
void updateMainState(float delta_time);
|
||||
void updatePlayerJoinPhaseState(float delta_time);
|
||||
void updateBlackScreenState(float delta_time);
|
||||
void updateDemoDiveState(float delta_time);
|
||||
void updateDemoCurtainState(float delta_time);
|
||||
// Integra el dive (attract): avança la càmera cap a +Z i puja el zoom dels
|
||||
// elements 2D amb acceleració (easeInQuad), sense topall. Es crida tant a
|
||||
// DEMO_DIVE com a DEMO_CURTAIN perquè la càmera no pare mai un cop comença:
|
||||
// segueix accelerant fins i tot sota la cortinilla, fins al salt a la demo.
|
||||
void advanceDive(float delta_time);
|
||||
void handleSkipInput();
|
||||
void handleStartInput();
|
||||
void triggerExitForJoinedPlayers(bool p1_was_active, bool p2_was_active, const char* log_prefix);
|
||||
|
||||
@@ -1,167 +0,0 @@
|
||||
// spawn_controller.cpp - Implementació del controlador de spawn
|
||||
// © 2026 JailDesigner
|
||||
|
||||
#include "spawn_controller.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <iostream>
|
||||
#include <utility>
|
||||
|
||||
#include "core/types.hpp"
|
||||
#include "game/entities/enemy.hpp"
|
||||
#include "stage_config.hpp"
|
||||
|
||||
namespace StageSystem {
|
||||
|
||||
SpawnController::SpawnController() = default;
|
||||
|
||||
void SpawnController::configure(const StageConfig* config) {
|
||||
config_ = config;
|
||||
}
|
||||
|
||||
void SpawnController::start() {
|
||||
if (config_ == nullptr) {
|
||||
std::cerr << "[SpawnController] Error: config_ es null" << '\n';
|
||||
return;
|
||||
}
|
||||
|
||||
reset();
|
||||
generateSpawnEvents();
|
||||
|
||||
std::cout << "[SpawnController] Stage " << static_cast<int>(config_->stage_id)
|
||||
<< ": generats " << spawn_queue_.size() << " spawn events" << '\n';
|
||||
}
|
||||
|
||||
void SpawnController::reset() {
|
||||
spawn_queue_.clear();
|
||||
temps_transcorregut_ = 0.0F;
|
||||
index_spawn_actual_ = 0;
|
||||
}
|
||||
|
||||
void SpawnController::update(float delta_time, std::array<Enemy, 15>& orni_array, bool pausar) {
|
||||
if ((config_ == nullptr) || spawn_queue_.empty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Increment timer only when not paused
|
||||
if (!pausar) {
|
||||
temps_transcorregut_ += delta_time;
|
||||
}
|
||||
|
||||
// Process spawn events
|
||||
while (index_spawn_actual_ < spawn_queue_.size()) {
|
||||
SpawnEvent& event = spawn_queue_[index_spawn_actual_];
|
||||
|
||||
if (event.spawnejat) {
|
||||
index_spawn_actual_++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (temps_transcorregut_ >= event.temps_spawn) {
|
||||
// Find first inactive enemy
|
||||
for (auto& enemy : orni_array) {
|
||||
if (!enemy.isActive()) {
|
||||
spawnEnemy(enemy, event.type, ship_position_);
|
||||
event.spawnejat = true;
|
||||
index_spawn_actual_++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// If no slot available, try next frame
|
||||
if (!event.spawnejat) {
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
// Not yet time for this spawn
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
auto SpawnController::allEnemiesSpawned() const -> bool {
|
||||
return index_spawn_actual_ >= spawn_queue_.size();
|
||||
}
|
||||
|
||||
auto SpawnController::allEnemiesDestroyed(const std::array<Enemy, 15>& orni_array) const -> bool {
|
||||
if (!allEnemiesSpawned()) {
|
||||
return false;
|
||||
}
|
||||
return std::ranges::all_of(orni_array, [](const Enemy& enemy) { return !enemy.isActive(); });
|
||||
}
|
||||
|
||||
auto SpawnController::getAliveEnemyCount(const std::array<Enemy, 15>& orni_array) -> uint8_t {
|
||||
uint8_t count = 0;
|
||||
for (const auto& enemy : orni_array) {
|
||||
if (enemy.isActive()) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
auto SpawnController::countSpawnedEnemies() const -> uint8_t {
|
||||
return static_cast<uint8_t>(index_spawn_actual_);
|
||||
}
|
||||
|
||||
void SpawnController::generateSpawnEvents() {
|
||||
if (config_ == nullptr) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (uint8_t i = 0; i < config_->total_enemies; i++) {
|
||||
float spawn_time = config_->config_spawn.delay_inicial +
|
||||
(i * config_->config_spawn.interval_spawn);
|
||||
|
||||
EnemyType type = selectRandomType();
|
||||
|
||||
spawn_queue_.push_back({spawn_time, type, false});
|
||||
}
|
||||
}
|
||||
|
||||
auto SpawnController::selectRandomType() const -> EnemyType {
|
||||
if (config_ == nullptr) {
|
||||
return EnemyType::PENTAGON;
|
||||
}
|
||||
|
||||
// Weighted random selection based on distribution
|
||||
int rand_val = std::rand() % 100;
|
||||
|
||||
if (std::cmp_less(rand_val, config_->distribucio.pentagon)) {
|
||||
return EnemyType::PENTAGON;
|
||||
}
|
||||
if (rand_val < config_->distribucio.pentagon + config_->distribucio.cuadrado) {
|
||||
return EnemyType::SQUARE;
|
||||
}
|
||||
return EnemyType::PINWHEEL;
|
||||
}
|
||||
|
||||
void SpawnController::spawnEnemy(Enemy& enemy, EnemyType type, const Vec2* ship_pos) {
|
||||
// Initialize enemy (with safe spawn if ship_pos provided)
|
||||
enemy.init(type, ship_pos);
|
||||
|
||||
// Apply difficulty multipliers
|
||||
applyMultipliers(enemy);
|
||||
}
|
||||
|
||||
void SpawnController::applyMultipliers(Enemy& enemy) const {
|
||||
if (config_ == nullptr) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Apply velocity multiplier
|
||||
float base_vel = enemy.getBaseVelocity();
|
||||
enemy.setVelocity(base_vel * config_->multiplicadors.velocity);
|
||||
|
||||
// Apply rotation multiplier
|
||||
float base_rot = enemy.getBaseRotation();
|
||||
enemy.setRotation(base_rot * config_->multiplicadors.rotation);
|
||||
|
||||
// Apply tracking strength (only affects SQUARE)
|
||||
enemy.setTrackingStrength(config_->multiplicadors.tracking_strength);
|
||||
}
|
||||
|
||||
} // namespace StageSystem
|
||||
@@ -1,59 +0,0 @@
|
||||
// spawn_controller.hpp - Controlador de spawn de enemigos
|
||||
// © 2026 JailDesigner
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
#include "core/types.hpp"
|
||||
#include "game/entities/enemy.hpp"
|
||||
#include "stage_config.hpp"
|
||||
|
||||
namespace StageSystem {
|
||||
|
||||
// Informació de spawn planificat
|
||||
struct SpawnEvent {
|
||||
float temps_spawn; // Temps absolut (segons) per spawnejar
|
||||
EnemyType type; // Tipo de enemy
|
||||
bool spawnejat; // Ya s'ha processat?
|
||||
};
|
||||
|
||||
class SpawnController {
|
||||
public:
|
||||
SpawnController();
|
||||
|
||||
// Configuration
|
||||
void configure(const StageConfig* config); // Set stage config
|
||||
void start(); // Generate spawn schedule
|
||||
void reset(); // Clear all pending spawns
|
||||
|
||||
// Update
|
||||
void update(float delta_time, std::array<Enemy, 15>& orni_array, bool pausar = false);
|
||||
|
||||
// Status queries
|
||||
[[nodiscard]] auto allEnemiesSpawned() const -> bool;
|
||||
[[nodiscard]] auto allEnemiesDestroyed(const std::array<Enemy, 15>& orni_array) const -> bool;
|
||||
// Estático: solo recorre el array pasado; no consulta estado del controller.
|
||||
[[nodiscard]] static auto getAliveEnemyCount(const std::array<Enemy, 15>& orni_array) -> uint8_t;
|
||||
[[nodiscard]] auto countSpawnedEnemies() const -> uint8_t;
|
||||
|
||||
// [NEW] Set ship position reference for safe spawn
|
||||
void setShipPosition(const Vec2* ship_pos) { ship_position_ = ship_pos; }
|
||||
|
||||
private:
|
||||
const StageConfig* config_{nullptr}; // Non-owning pointer to current stage config
|
||||
std::vector<SpawnEvent> spawn_queue_;
|
||||
float temps_transcorregut_{0.0F}; // Elapsed time since stage start
|
||||
uint8_t index_spawn_actual_{0}; // Next spawn to process
|
||||
|
||||
// Spawn generation
|
||||
void generateSpawnEvents();
|
||||
[[nodiscard]] auto selectRandomType() const -> EnemyType;
|
||||
void spawnEnemy(Enemy& enemy, EnemyType type, const Vec2* ship_pos = nullptr);
|
||||
void applyMultipliers(Enemy& enemy) const;
|
||||
const Vec2* ship_position_{nullptr}; // [NEW] Non-owning pointer to ship position
|
||||
};
|
||||
|
||||
} // namespace StageSystem
|
||||
@@ -1,4 +1,4 @@
|
||||
// stage_config.hpp - Estructures de dades per configuración de stages
|
||||
// stage_config.hpp - Estructures de dades per configuració de stages
|
||||
// © 2026 JailDesigner
|
||||
|
||||
#pragma once
|
||||
@@ -7,68 +7,68 @@
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "game/entities/enemy.hpp"
|
||||
|
||||
namespace StageSystem {
|
||||
|
||||
// Tipo de mode de spawn
|
||||
enum class ModeSpawn : std::uint8_t {
|
||||
PROGRESSIVE, // Spawn progressiu con intervals
|
||||
IMMEDIATE, // Todos los enemigos de cop
|
||||
WAVE // Onades de 3-5 enemigos (futura extensió)
|
||||
};
|
||||
|
||||
// Configuración de spawn
|
||||
struct ConfigSpawn {
|
||||
ModeSpawn mode;
|
||||
float delay_inicial; // Segons antes del primer spawn
|
||||
float interval_spawn; // Segons entre spawns consecutius
|
||||
};
|
||||
|
||||
// Distribució de type de enemigos (percentatges)
|
||||
struct DistribucioEnemics {
|
||||
uint8_t pentagon; // 0-100
|
||||
uint8_t cuadrado; // 0-100
|
||||
uint8_t molinillo; // 0-100
|
||||
// Suma ha de ser 100, validat en StageLoader
|
||||
};
|
||||
|
||||
// Multiplicadors de dificultat
|
||||
// Multiplicadors de dificultat aplicats a tots els enemics del stage.
|
||||
struct MultiplicadorsDificultat {
|
||||
float velocity; // 0.5-2.0 típic
|
||||
float rotation; // 0.5-2.0 típic
|
||||
float tracking_strength; // 0.0-1.5 (aplicat a Square)
|
||||
float velocity{1.0F};
|
||||
float rotation{1.0F};
|
||||
float tracking_strength{0.0F};
|
||||
};
|
||||
|
||||
// Condició de transició a la següent onada.
|
||||
// Pot ser una OR de "tots morts" i "timeout"; en falta tots dos cas, la
|
||||
// wave no avança mai (invàlid: validat al loader).
|
||||
struct WaveNext {
|
||||
bool on_all_dead{false};
|
||||
bool has_timeout{false};
|
||||
float timeout{0.0F};
|
||||
|
||||
[[nodiscard]] auto isValid() const -> bool {
|
||||
return on_all_dead || has_timeout;
|
||||
}
|
||||
};
|
||||
|
||||
// Una onada: llista d'enemics a spawnejar i regla per passar a la següent.
|
||||
struct WaveConfig {
|
||||
std::vector<EnemyType> spawn; // Ordre i tipus dels spawns
|
||||
float spawn_interval{0.0F}; // Segons entre spawns interns (0 = simultanis)
|
||||
WaveNext next;
|
||||
};
|
||||
|
||||
// Metadades del file YAML
|
||||
struct MetadataStages {
|
||||
std::string version;
|
||||
uint8_t total_stages;
|
||||
uint8_t total_stages{0};
|
||||
std::string descripcio;
|
||||
};
|
||||
|
||||
// Configuración completa de un stage
|
||||
// Configuració completa d'un stage
|
||||
struct StageConfig {
|
||||
uint8_t stage_id; // 1-10
|
||||
uint8_t total_enemies; // 1-200 (el cap simultani en pantalla el marca MAX_ORNIS)
|
||||
ConfigSpawn config_spawn;
|
||||
DistribucioEnemics distribucio;
|
||||
uint8_t stage_id{0};
|
||||
MultiplicadorsDificultat multiplicadors;
|
||||
std::vector<WaveConfig> waves;
|
||||
|
||||
// Validació
|
||||
[[nodiscard]] auto isValid() const -> bool {
|
||||
// stage_id es uint8_t: el rango superior (<=255) está garantizado por
|
||||
// el tipo; basta con confirmar que no es 0 (sentinela "sin asignar").
|
||||
return stage_id >= 1 &&
|
||||
total_enemies > 0 && total_enemies <= 200 &&
|
||||
distribucio.pentagon + distribucio.cuadrado + distribucio.molinillo == 100;
|
||||
if (stage_id == 0 || waves.empty()) {
|
||||
return false;
|
||||
}
|
||||
for (const auto& w : waves) {
|
||||
if (!w.next.isValid() || w.spawn.empty()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
// Configuración completa del sistema (carregada desde YAML)
|
||||
// Configuració completa del sistema (carregada des de YAML)
|
||||
struct StageSystemConfig {
|
||||
MetadataStages metadata;
|
||||
std::vector<StageConfig> stages; // Índex [0] = stage 1
|
||||
|
||||
// Obtenir configuración de un stage específic
|
||||
[[nodiscard]] auto findStage(uint8_t stage_id) const -> const StageConfig* {
|
||||
if (stage_id < 1 || stage_id > stages.size()) {
|
||||
return nullptr;
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
// stage_loader.cpp - Implementació del carregador de configuración YAML
|
||||
// stage_loader.cpp - Implementació del carregador de configuració YAML
|
||||
// © 2026 JailDesigner
|
||||
|
||||
#include "stage_loader.hpp"
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <exception>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
@@ -15,6 +14,7 @@
|
||||
|
||||
#include "core/resources/resource_helper.hpp"
|
||||
#include "external/fkyaml_node.hpp"
|
||||
#include "game/entities/enemy.hpp"
|
||||
#include "stage_config.hpp"
|
||||
|
||||
namespace StageSystem {
|
||||
@@ -27,22 +27,18 @@ auto StageLoader::load(const std::string& path) -> std::unique_ptr<StageSystemCo
|
||||
normalized = normalized.substr(5);
|
||||
}
|
||||
|
||||
// Load from resource system
|
||||
std::vector<uint8_t> data = Resource::Helper::loadFile(normalized);
|
||||
if (data.empty()) {
|
||||
std::cerr << "[StageLoader] Error: no es pot load " << normalized << '\n';
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Convert to string
|
||||
std::string yaml_content(data.begin(), data.end());
|
||||
std::stringstream stream(yaml_content);
|
||||
|
||||
// Parse YAML
|
||||
fkyaml::node yaml = fkyaml::node::deserialize(stream);
|
||||
auto config = std::make_unique<StageSystemConfig>();
|
||||
|
||||
// Parse metadata
|
||||
if (!yaml.contains("metadata")) {
|
||||
std::cerr << "[StageLoader] Error: falta camp 'metadata'" << '\n';
|
||||
return nullptr;
|
||||
@@ -51,12 +47,10 @@ auto StageLoader::load(const std::string& path) -> std::unique_ptr<StageSystemCo
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Parse stages
|
||||
if (!yaml.contains("stages")) {
|
||||
std::cerr << "[StageLoader] Error: falta camp 'stages'" << '\n';
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (!yaml["stages"].is_sequence()) {
|
||||
std::cerr << "[StageLoader] Error: 'stages' ha de ser una list" << '\n';
|
||||
return nullptr;
|
||||
@@ -67,10 +61,9 @@ auto StageLoader::load(const std::string& path) -> std::unique_ptr<StageSystemCo
|
||||
if (!parseStage(stage_yaml, stage)) {
|
||||
return nullptr;
|
||||
}
|
||||
config->stages.push_back(stage);
|
||||
config->stages.push_back(std::move(stage));
|
||||
}
|
||||
|
||||
// Validar configuración
|
||||
if (!validateConfig(*config)) {
|
||||
return nullptr;
|
||||
}
|
||||
@@ -107,29 +100,35 @@ auto StageLoader::parseMetadata(const fkyaml::node& yaml, MetadataStages& meta)
|
||||
|
||||
auto StageLoader::parseStage(const fkyaml::node& yaml, StageConfig& stage) -> bool {
|
||||
try {
|
||||
if (!yaml.contains("stage_id") || !yaml.contains("total_enemies") ||
|
||||
!yaml.contains("spawn_config") || !yaml.contains("enemy_distribution") ||
|
||||
!yaml.contains("difficulty_multipliers")) {
|
||||
std::cerr << "[StageLoader] Error: stage incompleta" << '\n';
|
||||
if (!yaml.contains("stage_id") || !yaml.contains("waves")) {
|
||||
std::cerr << "[StageLoader] Error: stage incompleta (cal stage_id i waves)" << '\n';
|
||||
return false;
|
||||
}
|
||||
|
||||
stage.stage_id = yaml["stage_id"].get_value<uint8_t>();
|
||||
stage.total_enemies = yaml["total_enemies"].get_value<uint8_t>();
|
||||
|
||||
if (!parseSpawnConfig(yaml["spawn_config"], stage.config_spawn)) {
|
||||
// multipliers és opcional: si falta, queda als defaults (1.0/1.0/0.0).
|
||||
if (yaml.contains("multipliers")) {
|
||||
if (!parseMultipliers(yaml["multipliers"], stage.multiplicadors)) {
|
||||
return false;
|
||||
}
|
||||
if (!parseDistribution(yaml["enemy_distribution"], stage.distribucio)) {
|
||||
}
|
||||
|
||||
if (!yaml["waves"].is_sequence()) {
|
||||
std::cerr << "[StageLoader] Error: 'waves' ha de ser una list" << '\n';
|
||||
return false;
|
||||
}
|
||||
if (!parseMultipliers(yaml["difficulty_multipliers"], stage.multiplicadors)) {
|
||||
for (const auto& wave_yaml : yaml["waves"]) {
|
||||
WaveConfig wave;
|
||||
if (!parseWave(wave_yaml, wave)) {
|
||||
return false;
|
||||
}
|
||||
stage.waves.push_back(std::move(wave));
|
||||
}
|
||||
|
||||
if (!stage.isValid()) {
|
||||
std::cerr << "[StageLoader] Error: stage " << static_cast<int>(stage.stage_id)
|
||||
<< " no es vàlid" << '\n';
|
||||
<< " no és vàlid" << '\n';
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -140,73 +139,26 @@ auto StageLoader::parseStage(const fkyaml::node& yaml, StageConfig& stage) -> bo
|
||||
}
|
||||
}
|
||||
|
||||
auto StageLoader::parseSpawnConfig(const fkyaml::node& yaml, ConfigSpawn& config) -> bool {
|
||||
try {
|
||||
if (!yaml.contains("mode") || !yaml.contains("initial_delay") ||
|
||||
!yaml.contains("spawn_interval")) {
|
||||
std::cerr << "[StageLoader] Error: spawn_config incompleta" << '\n';
|
||||
return false;
|
||||
}
|
||||
|
||||
auto mode_str = yaml["mode"].get_value<std::string>();
|
||||
config.mode = parseSpawnMode(mode_str);
|
||||
config.delay_inicial = yaml["initial_delay"].get_value<float>();
|
||||
config.interval_spawn = yaml["spawn_interval"].get_value<float>();
|
||||
|
||||
return true;
|
||||
} catch (const std::exception& e) {
|
||||
std::cerr << "[StageLoader] Error parsing spawn_config: " << e.what() << '\n';
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
auto StageLoader::parseDistribution(const fkyaml::node& yaml, DistribucioEnemics& dist) -> bool {
|
||||
try {
|
||||
if (!yaml.contains("pentagon") || !yaml.contains("cuadrado") ||
|
||||
!yaml.contains("molinillo")) {
|
||||
std::cerr << "[StageLoader] Error: enemy_distribution incompleta" << '\n';
|
||||
return false;
|
||||
}
|
||||
|
||||
dist.pentagon = yaml["pentagon"].get_value<uint8_t>();
|
||||
dist.cuadrado = yaml["cuadrado"].get_value<uint8_t>();
|
||||
dist.molinillo = yaml["molinillo"].get_value<uint8_t>();
|
||||
|
||||
// Validar que suma 100
|
||||
int sum = dist.pentagon + dist.cuadrado + dist.molinillo;
|
||||
if (sum != 100) {
|
||||
std::cerr << "[StageLoader] Error: distribució no suma 100 (suma=" << sum << ")" << '\n';
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (const std::exception& e) {
|
||||
std::cerr << "[StageLoader] Error parsing distribution: " << e.what() << '\n';
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
auto StageLoader::parseMultipliers(const fkyaml::node& yaml, MultiplicadorsDificultat& mult) -> bool {
|
||||
try {
|
||||
if (!yaml.contains("speed_multiplier") || !yaml.contains("rotation_multiplier") ||
|
||||
!yaml.contains("tracking_strength")) {
|
||||
std::cerr << "[StageLoader] Error: difficulty_multipliers incompleta" << '\n';
|
||||
return false;
|
||||
if (yaml.contains("velocity")) {
|
||||
mult.velocity = yaml["velocity"].get_value<float>();
|
||||
}
|
||||
if (yaml.contains("rotation")) {
|
||||
mult.rotation = yaml["rotation"].get_value<float>();
|
||||
}
|
||||
if (yaml.contains("tracking")) {
|
||||
mult.tracking_strength = yaml["tracking"].get_value<float>();
|
||||
}
|
||||
|
||||
mult.velocity = yaml["speed_multiplier"].get_value<float>();
|
||||
mult.rotation = yaml["rotation_multiplier"].get_value<float>();
|
||||
mult.tracking_strength = yaml["tracking_strength"].get_value<float>();
|
||||
|
||||
// Validar rangs raonables
|
||||
if (mult.velocity < 0.1F || mult.velocity > 5.0F) {
|
||||
std::cerr << "[StageLoader] Warning: speed_multiplier fuera de rang (0.1-5.0)" << '\n';
|
||||
std::cerr << "[StageLoader] Warning: velocity fora de rang (0.1-5.0)" << '\n';
|
||||
}
|
||||
if (mult.rotation < 0.1F || mult.rotation > 5.0F) {
|
||||
std::cerr << "[StageLoader] Warning: rotation_multiplier fuera de rang (0.1-5.0)" << '\n';
|
||||
std::cerr << "[StageLoader] Warning: rotation fora de rang (0.1-5.0)" << '\n';
|
||||
}
|
||||
if (mult.tracking_strength < 0.0F || mult.tracking_strength > 2.0F) {
|
||||
std::cerr << "[StageLoader] Warning: tracking_strength fuera de rang (0.0-2.0)" << '\n';
|
||||
std::cerr << "[StageLoader] Warning: tracking fora de rang (0.0-2.0)" << '\n';
|
||||
}
|
||||
|
||||
return true;
|
||||
@@ -216,34 +168,110 @@ auto StageLoader::parseMultipliers(const fkyaml::node& yaml, MultiplicadorsDific
|
||||
}
|
||||
}
|
||||
|
||||
auto StageLoader::parseSpawnMode(const std::string& mode_str) -> ModeSpawn {
|
||||
if (mode_str == "progressive") {
|
||||
return ModeSpawn::PROGRESSIVE;
|
||||
auto StageLoader::parseWave(const fkyaml::node& yaml, WaveConfig& wave) -> bool {
|
||||
try {
|
||||
if (!yaml.contains("spawn") || !yaml.contains("next")) {
|
||||
std::cerr << "[StageLoader] Error: wave sense 'spawn' o 'next'" << '\n';
|
||||
return false;
|
||||
}
|
||||
if (mode_str == "immediate") {
|
||||
return ModeSpawn::IMMEDIATE;
|
||||
|
||||
if (!yaml["spawn"].is_sequence()) {
|
||||
std::cerr << "[StageLoader] Error: 'spawn' ha de ser una list" << '\n';
|
||||
return false;
|
||||
}
|
||||
if (mode_str == "wave") {
|
||||
return ModeSpawn::WAVE;
|
||||
for (const auto& type_node : yaml["spawn"]) {
|
||||
auto type_str = type_node.get_value<std::string>();
|
||||
EnemyType type{};
|
||||
if (!parseEnemyType(type_str, type)) {
|
||||
std::cerr << "[StageLoader] Error: tipus d'enemic desconegut '"
|
||||
<< type_str << "'" << '\n';
|
||||
return false;
|
||||
}
|
||||
wave.spawn.push_back(type);
|
||||
}
|
||||
|
||||
wave.spawn_interval = yaml.contains("spawn_interval")
|
||||
? yaml["spawn_interval"].get_value<float>()
|
||||
: 0.0F;
|
||||
|
||||
if (!parseNext(yaml["next"], wave.next)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!wave.next.isValid()) {
|
||||
std::cerr << "[StageLoader] Error: wave 'next' sense condició (cal all_dead o timeout)" << '\n';
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (const std::exception& e) {
|
||||
std::cerr << "[StageLoader] Error parsing wave: " << e.what() << '\n';
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
auto StageLoader::parseEnemyType(const std::string& type_str, EnemyType& out) -> bool {
|
||||
if (type_str == "pentagon") {
|
||||
out = EnemyType::PENTAGON;
|
||||
} else if (type_str == "cuadrado" || type_str == "square") {
|
||||
out = EnemyType::SQUARE;
|
||||
} else if (type_str == "molinillo" || type_str == "pinwheel") {
|
||||
out = EnemyType::PINWHEEL;
|
||||
} else if (type_str == "star") {
|
||||
out = EnemyType::STAR;
|
||||
} else if (type_str == "orb") {
|
||||
out = EnemyType::ORB;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
auto StageLoader::parseNext(const fkyaml::node& yaml, WaveNext& next) -> bool {
|
||||
try {
|
||||
// Forma curta: scalar string ("all_dead" o "end").
|
||||
if (yaml.is_string()) {
|
||||
const auto S = yaml.get_value<std::string>();
|
||||
if (S == "all_dead" || S == "end") {
|
||||
next.on_all_dead = true;
|
||||
return true;
|
||||
}
|
||||
std::cerr << "[StageLoader] Error: 'next' string desconegut '" << S << "'" << '\n';
|
||||
return false;
|
||||
}
|
||||
|
||||
// Forma llarga: mapping amb claus opcionals.
|
||||
if (yaml.is_mapping()) {
|
||||
if (yaml.contains("all_dead")) {
|
||||
next.on_all_dead = yaml["all_dead"].get_value<bool>();
|
||||
}
|
||||
if (yaml.contains("timeout")) {
|
||||
next.has_timeout = true;
|
||||
next.timeout = yaml["timeout"].get_value<float>();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::cerr << "[StageLoader] Error: 'next' ha de ser string o mapping" << '\n';
|
||||
return false;
|
||||
} catch (const std::exception& e) {
|
||||
std::cerr << "[StageLoader] Error parsing next: " << e.what() << '\n';
|
||||
return false;
|
||||
}
|
||||
std::cerr << "[StageLoader] Warning: mode de spawn desconegut '" << mode_str
|
||||
<< "', usant PROGRESSIVE" << '\n';
|
||||
return ModeSpawn::PROGRESSIVE;
|
||||
}
|
||||
|
||||
auto StageLoader::validateConfig(const StageSystemConfig& config) -> bool {
|
||||
if (config.stages.empty()) {
|
||||
std::cerr << "[StageLoader] Error: sin stage carregat" << '\n';
|
||||
std::cerr << "[StageLoader] Error: cap stage carregat" << '\n';
|
||||
return false;
|
||||
}
|
||||
|
||||
if (config.stages.size() != config.metadata.total_stages) {
|
||||
std::cerr << "[StageLoader] Warning: nombre de stages (" << config.stages.size()
|
||||
<< ") no coincideix con metadata.total_stages ("
|
||||
<< ") no coincideix amb metadata.total_stages ("
|
||||
<< static_cast<int>(config.metadata.total_stages) << ")" << '\n';
|
||||
}
|
||||
|
||||
// Validar stage_id consecutius
|
||||
for (size_t i = 0; i < config.stages.size(); i++) {
|
||||
if (config.stages[i].stage_id != i + 1) {
|
||||
std::cerr << "[StageLoader] Error: stage_id no consecutius (esperat "
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// stage_loader.hpp - Carregador de configuración YAML
|
||||
// stage_loader.hpp - Carregador de configuració YAML
|
||||
// © 2026 JailDesigner
|
||||
|
||||
#pragma once
|
||||
@@ -13,20 +13,18 @@ namespace StageSystem {
|
||||
|
||||
class StageLoader {
|
||||
public:
|
||||
// Carregar configuración desde file YAML
|
||||
// Retorna nullptr si hay errors
|
||||
// Carregar configuració des de file YAML.
|
||||
// Retorna nullptr si hi ha errors.
|
||||
static auto load(const std::string& path) -> std::unique_ptr<StageSystemConfig>;
|
||||
|
||||
private:
|
||||
// Parsing helpers (implementats en .cpp)
|
||||
static auto parseMetadata(const fkyaml::node& yaml, MetadataStages& meta) -> bool;
|
||||
static auto parseStage(const fkyaml::node& yaml, StageConfig& stage) -> bool;
|
||||
static auto parseSpawnConfig(const fkyaml::node& yaml, ConfigSpawn& config) -> bool;
|
||||
static auto parseDistribution(const fkyaml::node& yaml, DistribucioEnemics& dist) -> bool;
|
||||
static auto parseMultipliers(const fkyaml::node& yaml, MultiplicadorsDificultat& mult) -> bool;
|
||||
static auto parseSpawnMode(const std::string& mode_str) -> ModeSpawn;
|
||||
static auto parseWave(const fkyaml::node& yaml, WaveConfig& wave) -> bool;
|
||||
static auto parseEnemyType(const std::string& type_str, EnemyType& out) -> bool;
|
||||
static auto parseNext(const fkyaml::node& yaml, WaveNext& next) -> bool;
|
||||
|
||||
// Validació
|
||||
static auto validateConfig(const StageSystemConfig& config) -> bool;
|
||||
};
|
||||
|
||||
|
||||
@@ -31,6 +31,23 @@ namespace StageSystem {
|
||||
<< '\n';
|
||||
}
|
||||
|
||||
void StageManager::initDemo(uint8_t stage_id) {
|
||||
if (config_ == nullptr) {
|
||||
std::cerr << "[StageManager] Error: config es null, no es pot iniciar la demo\n";
|
||||
return;
|
||||
}
|
||||
// Clamp al rang vàlid: si l'escenari demana un stage inexistent, cau a 1.
|
||||
if (config_->findStage(stage_id) == nullptr) {
|
||||
stage_id = 1;
|
||||
}
|
||||
stage_actual_ = stage_id;
|
||||
loadStage(stage_actual_);
|
||||
changeState(EstatStage::PLAYING);
|
||||
|
||||
std::cout << "[StageManager] Demo inicialitzada a stage "
|
||||
<< static_cast<int>(stage_actual_) << '\n';
|
||||
}
|
||||
|
||||
void StageManager::update(float delta_time, bool pause_spawn) {
|
||||
switch (estat_) {
|
||||
case EstatStage::INIT_HUD:
|
||||
@@ -127,11 +144,10 @@ namespace StageSystem {
|
||||
}
|
||||
|
||||
void StageManager::processPlaying(float delta_time, bool pause_spawn) {
|
||||
// Update spawn controller (pauses when pause_spawn = true)
|
||||
// Note: The actual enemy array update happens in GameScene::update()
|
||||
// This is just for internal timekeeping
|
||||
(void)delta_time; // Spawn controller is updated externally
|
||||
(void)pause_spawn; // Passed to spawn_controller_.update() by GameScene
|
||||
// No-op: el WaveRunner s'actualitza des de GameScene::runStagePlaying,
|
||||
// no des d'ací. La signatura es manté per simetria amb les altres process*.
|
||||
(void)delta_time;
|
||||
(void)pause_spawn;
|
||||
}
|
||||
|
||||
void StageManager::processLevelCompleted(float delta_time) {
|
||||
@@ -162,12 +178,11 @@ namespace StageSystem {
|
||||
return;
|
||||
}
|
||||
|
||||
// Configure spawn controller
|
||||
spawn_controller_.configure(stage_config);
|
||||
spawn_controller_.start();
|
||||
wave_runner_.configure(stage_config);
|
||||
wave_runner_.start();
|
||||
|
||||
std::cout << "[StageManager] Carregat stage " << static_cast<int>(stage_id) << ": "
|
||||
<< static_cast<int>(stage_config->total_enemies) << " enemigos" << '\n';
|
||||
<< stage_config->waves.size() << " onades" << '\n';
|
||||
}
|
||||
|
||||
} // namespace StageSystem
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
#include "spawn_controller.hpp"
|
||||
#include "stage_config.hpp"
|
||||
#include "wave_runner.hpp"
|
||||
|
||||
namespace StageSystem {
|
||||
|
||||
@@ -25,6 +25,11 @@ class StageManager {
|
||||
|
||||
// Lifecycle
|
||||
void init(); // Reset to stage 1
|
||||
// Arranque para el mode demo (attract): carga stage_id y entra directamente
|
||||
// en PLAYING, saltando INIT_HUD y "ENEMY INCOMING" para mostrar una partida
|
||||
// ya en marcha. No reproduce game.ogg (changeState solo lo hace en LEVEL_START),
|
||||
// así la música del título sigue sonando durante el ciclo atrae.
|
||||
void initDemo(uint8_t stage_id);
|
||||
void update(float delta_time, bool pause_spawn = false);
|
||||
|
||||
// Stage progression
|
||||
@@ -38,13 +43,13 @@ class StageManager {
|
||||
[[nodiscard]] auto getTransitionTimer() const -> float { return timer_transicio_; }
|
||||
[[nodiscard]] auto getLevelStartMessage() const -> const std::string& { return missatge_level_start_actual_; }
|
||||
|
||||
// Spawn control (delegate to SpawnController)
|
||||
auto getSpawnController() -> SpawnController& { return spawn_controller_; }
|
||||
[[nodiscard]] auto getSpawnController() const -> const SpawnController& { return spawn_controller_; }
|
||||
// Wave execution (delegated)
|
||||
auto getWaveRunner() -> WaveRunner& { return wave_runner_; }
|
||||
[[nodiscard]] auto getWaveRunner() const -> const WaveRunner& { return wave_runner_; }
|
||||
|
||||
private:
|
||||
const StageSystemConfig* config_; // Non-owning pointer
|
||||
SpawnController spawn_controller_;
|
||||
WaveRunner wave_runner_;
|
||||
|
||||
EstatStage estat_{EstatStage::LEVEL_START};
|
||||
uint8_t stage_actual_{1}; // 1-10
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
// wave_runner.cpp - Implementació de l'executor d'onades
|
||||
// © 2026 JailDesigner
|
||||
|
||||
#include "wave_runner.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <iostream>
|
||||
|
||||
#include "core/types.hpp"
|
||||
#include "game/entities/enemy.hpp"
|
||||
#include "stage_config.hpp"
|
||||
|
||||
namespace StageSystem {
|
||||
|
||||
void WaveRunner::configure(const StageConfig* config) {
|
||||
config_ = config;
|
||||
}
|
||||
|
||||
void WaveRunner::start() {
|
||||
reset();
|
||||
if ((config_ == nullptr) || config_->waves.empty()) {
|
||||
std::cerr << "[WaveRunner] Error: config null o sense onades" << '\n';
|
||||
all_waves_emitted_ = true;
|
||||
return;
|
||||
}
|
||||
std::cout << "[WaveRunner] Stage " << static_cast<int>(config_->stage_id)
|
||||
<< ": " << config_->waves.size() << " onades" << '\n';
|
||||
}
|
||||
|
||||
void WaveRunner::reset() {
|
||||
wave_index_ = 0;
|
||||
wave_elapsed_ = 0.0F;
|
||||
spawns_emitted_ = 0;
|
||||
all_waves_emitted_ = false;
|
||||
}
|
||||
|
||||
void WaveRunner::update(float delta_time, std::array<Enemy, 15>& orni_array, bool pausar) {
|
||||
if (pausar || config_ == nullptr || all_waves_emitted_) {
|
||||
// Si ja s'han emès totes, encara hem de poder avaluar stageComplete.
|
||||
return;
|
||||
}
|
||||
|
||||
const WaveConfig* wave = currentWave();
|
||||
if (wave == nullptr) {
|
||||
all_waves_emitted_ = true;
|
||||
return;
|
||||
}
|
||||
|
||||
wave_elapsed_ += delta_time;
|
||||
|
||||
emitPendingSpawns(orni_array);
|
||||
|
||||
if (shouldAdvance(orni_array)) {
|
||||
advanceWave();
|
||||
}
|
||||
}
|
||||
|
||||
auto WaveRunner::stageComplete(const std::array<Enemy, 15>& orni_array) const -> bool {
|
||||
return all_waves_emitted_ && getAliveEnemyCount(orni_array) == 0;
|
||||
}
|
||||
|
||||
auto WaveRunner::getAliveEnemyCount(const std::array<Enemy, 15>& orni_array) -> uint8_t {
|
||||
uint8_t count = 0;
|
||||
for (const auto& enemy : orni_array) {
|
||||
if (enemy.isActive()) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
auto WaveRunner::currentWave() const -> const WaveConfig* {
|
||||
if (config_ == nullptr || wave_index_ >= config_->waves.size()) {
|
||||
return nullptr;
|
||||
}
|
||||
return &config_->waves[wave_index_];
|
||||
}
|
||||
|
||||
void WaveRunner::emitPendingSpawns(std::array<Enemy, 15>& orni_array) {
|
||||
const WaveConfig* wave = currentWave();
|
||||
if (wave == nullptr) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Spawn[i] toca a t = i * spawn_interval (i=0 → t=0).
|
||||
while (spawns_emitted_ < wave->spawn.size()) {
|
||||
const float SPAWN_T = static_cast<float>(spawns_emitted_) * wave->spawn_interval;
|
||||
if (wave_elapsed_ < SPAWN_T) {
|
||||
break;
|
||||
}
|
||||
|
||||
// Busca un slot lliure a l'arena. Si no n'hi ha, ho intentem el següent frame.
|
||||
bool emitted = false;
|
||||
for (auto& enemy : orni_array) {
|
||||
if (!enemy.isActive()) {
|
||||
spawnEnemy(enemy, wave->spawn[spawns_emitted_]);
|
||||
emitted = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!emitted) {
|
||||
break;
|
||||
}
|
||||
spawns_emitted_++;
|
||||
}
|
||||
}
|
||||
|
||||
void WaveRunner::spawnEnemy(Enemy& enemy, EnemyType type) {
|
||||
enemy.init(type, ship_position_);
|
||||
applyMultipliers(enemy);
|
||||
}
|
||||
|
||||
void WaveRunner::applyMultipliers(Enemy& enemy) const {
|
||||
if (config_ == nullptr) {
|
||||
return;
|
||||
}
|
||||
enemy.setVelocity(enemy.getBaseVelocity() * config_->multiplicadors.velocity);
|
||||
enemy.setRotation(enemy.getBaseRotation() * config_->multiplicadors.rotation);
|
||||
enemy.setTrackingStrength(config_->multiplicadors.tracking_strength);
|
||||
}
|
||||
|
||||
auto WaveRunner::shouldAdvance(const std::array<Enemy, 15>& orni_array) const -> bool {
|
||||
const WaveConfig* wave = currentWave();
|
||||
if (wave == nullptr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Una wave només pot avançar després d'haver emès tots els seus spawns.
|
||||
const bool ALL_SPAWNED = spawns_emitted_ >= wave->spawn.size();
|
||||
|
||||
if (wave->next.has_timeout && wave_elapsed_ >= wave->next.timeout) {
|
||||
// El timeout NO requereix all_spawned: si la wave triga més que el seu
|
||||
// propi timeout (cas patològic amb spawn_interval massa gran), forcem
|
||||
// avançar igualment per no encallar-nos.
|
||||
return true;
|
||||
}
|
||||
|
||||
if (wave->next.on_all_dead) {
|
||||
return ALL_SPAWNED && getAliveEnemyCount(orni_array) == 0;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void WaveRunner::advanceWave() {
|
||||
wave_index_++;
|
||||
wave_elapsed_ = 0.0F;
|
||||
spawns_emitted_ = 0;
|
||||
|
||||
if (config_ == nullptr || wave_index_ >= config_->waves.size()) {
|
||||
all_waves_emitted_ = true;
|
||||
std::cout << "[WaveRunner] Totes les onades emeses" << '\n';
|
||||
return;
|
||||
}
|
||||
std::cout << "[WaveRunner] Avança a onada " << static_cast<int>(wave_index_ + 1)
|
||||
<< "/" << config_->waves.size() << '\n';
|
||||
}
|
||||
|
||||
} // namespace StageSystem
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user