Compare commits
8 Commits
v0.8.0
...
5fb6c68df4
| Author | SHA1 | Date | |
|---|---|---|---|
| 5fb6c68df4 | |||
| 866a057704 | |||
| da8eab330d | |||
| 39bda0775e | |||
| ed4d3a3915 | |||
| 6447932212 | |||
| 9f278772bb | |||
| 2d073b6055 |
+4
-1
@@ -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,24 @@
|
||||
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
|
||||
|
||||
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
|
||||
|
||||
colors:
|
||||
normal: [0, 255, 255] # Cyan pur "esquivador"
|
||||
wounded: [255, 220, 60] # Daurat (parpelleig al rebre impacte)
|
||||
|
||||
score: 100
|
||||
@@ -0,0 +1,24 @@
|
||||
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
|
||||
|
||||
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)
|
||||
|
||||
colors:
|
||||
normal: [255, 0, 255] # Magenta pur "agressiu"
|
||||
wounded: [255, 220, 60]
|
||||
|
||||
score: 200
|
||||
@@ -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 ("ship2.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.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, 220, 60] # daurat (estat ferit)
|
||||
|
||||
weapon:
|
||||
bullet_speed: 700.0 # velocitat escalar de la bullet (px/s)
|
||||
@@ -0,0 +1,24 @@
|
||||
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
|
||||
|
||||
behavior:
|
||||
# Square: tracking discret cap a la nau cada N segons.
|
||||
tracking_strength: 0.5 # Interpolació LERP cap a la direcció desitjada (0..1)
|
||||
tracking_interval: 1.0 # segons entre updates d'angle
|
||||
|
||||
colors:
|
||||
normal: [255, 0, 0] # Roig pur "tanc"
|
||||
wounded: [255, 220, 60]
|
||||
|
||||
score: 150
|
||||
@@ -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"
|
||||
|
||||
@@ -3,8 +3,6 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "core/defaults/entities.hpp"
|
||||
|
||||
namespace Defaults::Enemies {
|
||||
|
||||
// Cuerpo físico común (valores por defecto del constructor)
|
||||
@@ -15,41 +13,10 @@ namespace Defaults::Enemies {
|
||||
constexpr float ANGULAR_DAMPING = 0.0F;
|
||||
} // namespace Body
|
||||
|
||||
// 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
|
||||
|
||||
// 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
|
||||
|
||||
// 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
|
||||
// NOTA: els paràmetres per tipus (Pentagon/Square/Pinwheel) i el Scoring
|
||||
// viuen ara a data/entities/{pentagon,square,pinwheel}/*.yaml i s'accedeixen
|
||||
// via EnemyRegistry::get(EnemyType). Aquí només queden els paràmetres
|
||||
// compartits entre tots els tipus (animació, wounded, spawn).
|
||||
|
||||
// Animation parameters (shared)
|
||||
namespace Animation {
|
||||
@@ -78,9 +45,12 @@ namespace Defaults::Enemies {
|
||||
|
||||
// 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
|
||||
// Safe spawn distance from player. Antic: SHIP_RADIUS(12) * 3 = 36 px.
|
||||
// SHIP_RADIUS ha migrat al YAML del player; aquesta constant es
|
||||
// mantindrà fixa fins al PR de migració dels enemics a YAML, on
|
||||
// passarà a derivar-se en runtime del player_config.
|
||||
constexpr float SAFETY_DISTANCE_MULTIPLIER = 3.0F;
|
||||
constexpr float SAFETY_DISTANCE = 36.0F;
|
||||
constexpr int MAX_SPAWN_ATTEMPTS = 50; // Max attempts to find safe position
|
||||
|
||||
// Invulnerability system
|
||||
@@ -91,11 +61,4 @@ namespace Defaults::Enemies {
|
||||
constexpr float INVULNERABILITY_SCALE_END = 1.0F; // Full size
|
||||
} // namespace Spawn
|
||||
|
||||
// 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
|
||||
|
||||
@@ -8,8 +8,8 @@ namespace Defaults::Entities {
|
||||
constexpr int MAX_ORNIS = 15;
|
||||
constexpr int MAX_BULLETS = 50;
|
||||
|
||||
constexpr float SHIP_RADIUS = 12.0F;
|
||||
constexpr float ENEMY_RADIUS = 20.0F;
|
||||
// SHIP_RADIUS migrat a data/entities/player/player.yaml (physics.collision_radius).
|
||||
// ENEMY_RADIUS migrat a data/entities/<type>/<type>.yaml (physics.collision_radius).
|
||||
constexpr float BULLET_RADIUS = 3.0F;
|
||||
|
||||
} // 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
|
||||
|
||||
@@ -14,11 +14,10 @@ namespace Defaults::Palette {
|
||||
// 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
|
||||
// SHIP s'ha migrat a data/entities/player/player.yaml (colors.normal).
|
||||
// PENTAGON, SQUARE, PINWHEEL i WOUNDED han migrat a cada enemy YAML
|
||||
// (colors.normal i colors.wounded).
|
||||
// BULLET es queda compartit fins a la migració del bullet a YAML.
|
||||
|
||||
} // namespace Defaults::Palette
|
||||
|
||||
@@ -5,10 +5,10 @@
|
||||
|
||||
namespace Defaults::Physics {
|
||||
|
||||
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²
|
||||
// NOTA: els paràmetres específics de la nau del player (rotation_speed,
|
||||
// acceleration, max_velocity, death_impact_factor) viuen ara a
|
||||
// data/entities/player/player.yaml. La migració d'aquests fitxers va
|
||||
// començar amb la nau; els enemics i les bales són els següents.
|
||||
|
||||
// Bullet — impacto físico contra enemigo (impulse mass-aware).
|
||||
// Model: el impulse és el moment lineal de la bala (m·v) multiplicat per
|
||||
@@ -18,14 +18,6 @@ namespace Defaults::Physics {
|
||||
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)
|
||||
|
||||
@@ -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
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -53,7 +53,7 @@ void Bullet::init() {
|
||||
body_.clearAccumulators();
|
||||
}
|
||||
|
||||
void Bullet::fire(const Vec2& position, float angle, uint8_t owner_id) {
|
||||
void Bullet::fire(const Vec2& position, float angle, uint8_t owner_id, float bullet_speed) {
|
||||
// Activar bullet
|
||||
is_active_ = true;
|
||||
|
||||
@@ -71,7 +71,7 @@ void Bullet::fire(const Vec2& position, float angle, uint8_t owner_id) {
|
||||
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();
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ class Bullet : public Entities::Entity {
|
||||
explicit Bullet(Rendering::Renderer* renderer);
|
||||
|
||||
void init() override;
|
||||
void fire(const Vec2& position, float angle, uint8_t owner_id);
|
||||
void fire(const Vec2& position, float angle, uint8_t owner_id, float bullet_speed);
|
||||
void update(float delta_time) override;
|
||||
void postUpdate(float delta_time) override;
|
||||
void draw() const override;
|
||||
|
||||
+40
-118
@@ -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 {
|
||||
|
||||
@@ -27,25 +29,20 @@ 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;
|
||||
}
|
||||
// El movimiento (vx, vy) corresponde a angle - PI/2; invertimos.
|
||||
return std::atan2(velocity.y, velocity.x) + (Constants::PI / 2.0F);
|
||||
}
|
||||
|
||||
} // 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).
|
||||
// Cuerpo físico — defaults comuns; init() ajusta mass/radius segons el tipus.
|
||||
body_.setMass(Defaults::Enemies::Body::DEFAULT_MASS);
|
||||
body_.radius = 0.0F; // 0 hasta spawn (no colisiona inactivo)
|
||||
body_.restitution = Defaults::Enemies::Body::RESTITUTION;
|
||||
@@ -55,71 +52,40 @@ Enemy::Enemy(Rendering::Renderer* renderer)
|
||||
|
||||
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;
|
||||
|
||||
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;
|
||||
// Cas Square: resetejar tracking timer al spawn.
|
||||
if (type_ == EnemyType::SQUARE) {
|
||||
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;
|
||||
tracking_strength_ = cfg.behavior.tracking_strength;
|
||||
}
|
||||
|
||||
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';
|
||||
}
|
||||
|
||||
// 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 * cfg.shape.scale * cfg.shape.collision_factor;
|
||||
|
||||
body_.setMass(cfg.physics.mass);
|
||||
body_.radius = collision_radius_;
|
||||
|
||||
// Posición aleatoria con comprobación de seguridad
|
||||
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_, candidate_x, candidate_y)) {
|
||||
center_.x = candidate_x;
|
||||
center_.y = candidate_y;
|
||||
found_safe_position = true;
|
||||
@@ -143,30 +109,27 @@ void Enemy::init(EnemyType type, const Vec2* ship_pos) {
|
||||
|
||||
// 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);
|
||||
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ón visual aleatoria dins del rang del tipus
|
||||
const float ROTATION_RANGE = cfg.physics.rotation_delta_max - cfg.physics.rotation_delta_min;
|
||||
rotation_delta_ = cfg.physics.rotation_delta_min +
|
||||
((static_cast<float>(std::rand()) / static_cast<float>(RAND_MAX)) * ROTATION_RANGE);
|
||||
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;
|
||||
|
||||
// Timer para próximo cambio de dirección (Pentagon)
|
||||
direction_change_timer_ = 0.0F;
|
||||
|
||||
is_active_ = true;
|
||||
@@ -177,8 +140,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,7 +149,6 @@ void Enemy::update(float delta_time) {
|
||||
}
|
||||
}
|
||||
|
||||
// Decremento de invulnerabilidad + LERP de brightness
|
||||
if (invulnerability_timer_ > 0.0F) {
|
||||
invulnerability_timer_ -= delta_time;
|
||||
invulnerability_timer_ = std::max(invulnerability_timer_, 0.0F);
|
||||
@@ -201,9 +161,6 @@ void Enemy::update(float delta_time) {
|
||||
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:
|
||||
@@ -218,15 +175,12 @@ void Enemy::update(float delta_time) {
|
||||
}
|
||||
}
|
||||
|
||||
// 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,27 +190,16 @@ 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;
|
||||
}
|
||||
// El SCALE final = escala base del YAML * modulador dinàmic (spawn/pulse).
|
||||
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).
|
||||
// Parpadeo dorado mientras está herido.
|
||||
if (wounded_timer_ > 0.0F) {
|
||||
const float CYCLE = 1.0F / Defaults::Enemies::Wounded::BLINK_HZ;
|
||||
const float T = std::fmod(wounded_timer_, CYCLE);
|
||||
if (T < (CYCLE / 2.0F)) {
|
||||
color = Defaults::Palette::WOUNDED;
|
||||
color = config_->colors.wounded;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -267,7 +210,7 @@ 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;
|
||||
@@ -276,8 +219,6 @@ void Enemy::destroy() {
|
||||
void Enemy::hurt(uint8_t shooter_id) {
|
||||
wounded_timer_ = Defaults::Enemies::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,12 +226,10 @@ 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;
|
||||
setVelocityFromAngle(A, speed);
|
||||
}
|
||||
@@ -306,13 +245,11 @@ void Enemy::setVelocityFromAngle(float angle_movement, float speed) {
|
||||
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) {
|
||||
if (RAND_VAL < config_->behavior.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;
|
||||
config_->behavior.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);
|
||||
@@ -320,12 +257,12 @@ void Enemy::behaviorPentagon(float delta_time) {
|
||||
}
|
||||
}
|
||||
|
||||
// SQUARE: tracking discreto cada TRACKING_INTERVAL. Ajusta dirección
|
||||
// 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) {
|
||||
if (tracking_timer_ >= config_->behavior.tracking_interval && ship_position_ != nullptr) {
|
||||
tracking_timer_ = 0.0F;
|
||||
|
||||
const Vec2 TO_SHIP = *ship_position_ - center_;
|
||||
@@ -335,11 +272,9 @@ void Enemy::behaviorSquare(float delta_time) {
|
||||
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);
|
||||
@@ -349,20 +284,16 @@ void Enemy::behaviorSquare(float delta_time) {
|
||||
}
|
||||
|
||||
// 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;
|
||||
if (DIST < config_->behavior.proximity_distance) {
|
||||
rotation_delta_ = animation_.rotation_delta_base * config_->behavior.rotation_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) {
|
||||
@@ -452,16 +383,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 {
|
||||
@@ -474,12 +396,12 @@ void Enemy::setTrackingStrength(float 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& 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);
|
||||
|
||||
@@ -17,6 +17,9 @@ enum class EnemyType : uint8_t {
|
||||
PINWHEEL = 2 // Molinillo agresivo (rápido, girando)
|
||||
};
|
||||
|
||||
// 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 +51,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,6 +66,9 @@ 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; }
|
||||
@@ -101,29 +105,34 @@ class Enemy : public Entities::Entity {
|
||||
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
|
||||
float tracking_timer_{0.0F};
|
||||
const Vec2* ship_position_{nullptr};
|
||||
float tracking_strength_{0.0F};
|
||||
float direction_change_timer_{0.0F};
|
||||
|
||||
// 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};
|
||||
|
||||
// Métodos privados
|
||||
void updateAnimation(float delta_time);
|
||||
@@ -133,8 +142,8 @@ class Enemy : public Entities::Entity {
|
||||
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;
|
||||
// Static: passa collision_radius com a param per no acoblar a *this.
|
||||
static auto attemptSafeSpawn(const Vec2& ship_pos, float collision_radius, 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).
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
// 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; }
|
||||
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>();
|
||||
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;
|
||||
}
|
||||
|
||||
} // 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 (!parseColors(node, cfg.name, cfg.colors)) { return std::nullopt; }
|
||||
if (!parseScore(node, cfg.name, cfg.score)) { return std::nullopt; }
|
||||
|
||||
return cfg;
|
||||
} catch (const std::exception& e) {
|
||||
std::cerr << "[EnemyConfig] Excepció parsejant: " << e.what() << '\n';
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
// 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
|
||||
|
||||
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;
|
||||
};
|
||||
|
||||
// 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};
|
||||
};
|
||||
|
||||
struct ColorsCfg {
|
||||
SDL_Color normal;
|
||||
SDL_Color wounded;
|
||||
};
|
||||
|
||||
std::string name;
|
||||
EnemyType ai_type;
|
||||
ShapeCfg shape;
|
||||
PhysicsCfg physics;
|
||||
BehaviorCfg behavior;
|
||||
ColorsCfg colors;
|
||||
int score;
|
||||
|
||||
// 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,62 @@
|
||||
// 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;
|
||||
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);
|
||||
loaded = OK;
|
||||
if (OK) {
|
||||
std::cout << "[EnemyRegistry] 3 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;
|
||||
}
|
||||
std::cerr << "[EnemyRegistry] FATAL: tipus desconegut\n";
|
||||
std::exit(EXIT_FAILURE);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
// 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 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 "ship2.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);
|
||||
@@ -89,10 +86,10 @@ void Ship::processInput(float delta_time, uint8_t player_id) {
|
||||
: input->checkActionPlayer2(InputAction::THRUST, Input::ALLOW_REPEAT);
|
||||
|
||||
if (ROTATE_RIGHT) {
|
||||
body_.angle += Defaults::Physics::ROTATION_SPEED * delta_time;
|
||||
body_.angle += config_.physics.rotation_speed * delta_time;
|
||||
}
|
||||
if (ROTATE_LEFT) {
|
||||
body_.angle -= Defaults::Physics::ROTATION_SPEED * delta_time;
|
||||
body_.angle -= config_.physics.rotation_speed * delta_time;
|
||||
}
|
||||
|
||||
// Thrust: fuerza vectorial en la dirección de la nariz.
|
||||
@@ -100,44 +97,36 @@ void Ship::processInput(float delta_time, uint8_t player_id) {
|
||||
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 +136,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 +148,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 daurat 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 +168,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,15 +6,18 @@
|
||||
|
||||
#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);
|
||||
@@ -26,20 +29,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 +66,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.
|
||||
|
||||
@@ -10,10 +10,13 @@
|
||||
#include <iostream>
|
||||
|
||||
#include "core/audio/audio.hpp"
|
||||
#include "core/entities/entity_loader.hpp"
|
||||
#include "core/input/input.hpp"
|
||||
#include "core/locale/locale.hpp"
|
||||
#include "core/system/scene_context.hpp"
|
||||
#include "core/system/service_menu.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"
|
||||
@@ -49,9 +52,29 @@ 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);
|
||||
}
|
||||
|
||||
// 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, "ship2.shp"); // Jugador 2: interceptor amb ales
|
||||
|
||||
// Inicialitzar balas con renderer
|
||||
std::ranges::fill(bullets_, Bullet(sdl.getRenderer()));
|
||||
@@ -758,7 +781,7 @@ void GameScene::tocado(uint8_t player_id) {
|
||||
0.0F, // sense herència angular
|
||||
0.0F, // sin herencia visual
|
||||
Defaults::Sound::EXPLOSION2,
|
||||
Defaults::Palette::SHIP,
|
||||
ships_[player_id].getConfig().colors.normal,
|
||||
Defaults::Physics::Debris::ENEMY_LIFETIME,
|
||||
Defaults::Physics::Debris::ENEMY_FRICTION,
|
||||
Defaults::Physics::Debris::ENEMY_SEGMENT_MULTIPLIER);
|
||||
@@ -944,7 +967,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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,38 +8,13 @@
|
||||
#include "core/physics/collision.hpp"
|
||||
#include "core/types.hpp"
|
||||
#include "game/constants.hpp"
|
||||
#include "game/entities/enemy_config.hpp"
|
||||
|
||||
namespace Systems::Collision {
|
||||
|
||||
namespace {
|
||||
constexpr uint8_t NO_SHOOTER = 0xFF;
|
||||
|
||||
// Lookup tabla puntos / color por tipo de enemy (mantiene la lógica
|
||||
// anterior pero centralizada para reutilizar entre paths).
|
||||
auto scoreForType(EnemyType type) -> int {
|
||||
switch (type) {
|
||||
case EnemyType::PENTAGON:
|
||||
return Defaults::Enemies::Scoring::PENTAGON_SCORE;
|
||||
case EnemyType::SQUARE:
|
||||
return Defaults::Enemies::Scoring::SQUARE_SCORE;
|
||||
case EnemyType::PINWHEEL:
|
||||
return Defaults::Enemies::Scoring::PINWHEEL_SCORE;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
auto colorForType(EnemyType type) -> SDL_Color {
|
||||
switch (type) {
|
||||
case EnemyType::PENTAGON:
|
||||
return Defaults::Palette::PENTAGON;
|
||||
case EnemyType::SQUARE:
|
||||
return Defaults::Palette::SQUARE;
|
||||
case EnemyType::PINWHEEL:
|
||||
return Defaults::Palette::PINWHEEL;
|
||||
}
|
||||
return SDL_Color{};
|
||||
}
|
||||
|
||||
// Mata al enemy con explosión: floating score, debris con velocity heredada,
|
||||
// sonido. Si shooter_id ≠ NO_SHOOTER, suma puntos a ese jugador.
|
||||
// CRUCIAL: leer velocity/datos ANTES de destruir() (que zera la velocity).
|
||||
@@ -48,10 +23,10 @@ namespace Systems::Collision {
|
||||
const Vec2 ENEMY_VEL = enemy.getVelocityVector();
|
||||
const float BRIGHTNESS = enemy.getBrightness();
|
||||
const auto SHAPE = enemy.getShape();
|
||||
const EnemyType TYPE = enemy.getType();
|
||||
|
||||
const int POINTS = scoreForType(TYPE);
|
||||
const SDL_Color COLOR = colorForType(TYPE);
|
||||
const int POINTS = enemy.getConfig().score;
|
||||
const SDL_Color COLOR = enemy.getConfig().colors.normal;
|
||||
const SDL_Color WOUNDED_COLOR = enemy.getConfig().colors.wounded;
|
||||
|
||||
if (shooter_id != NO_SHOOTER) {
|
||||
ctx.score_per_player[shooter_id] += POINTS;
|
||||
@@ -86,7 +61,7 @@ namespace Systems::Collision {
|
||||
Defaults::FX::Firework::N_POINTS,
|
||||
Defaults::FX::Firework::INITIAL_BRIGHTNESS,
|
||||
/*glow=*/true,
|
||||
Defaults::Palette::WOUNDED);
|
||||
WOUNDED_COLOR);
|
||||
}
|
||||
|
||||
// Trenca una bala en debris (8 fragments de l'octàgon) + so HIT + desactiva.
|
||||
@@ -224,7 +199,8 @@ namespace Systems::Collision {
|
||||
// Segon impacte durant HURT → mort. Aplica un impuls afegit
|
||||
// perquè l'enemic surti disparat (feedback visible).
|
||||
const Vec2 SHIP_VEL = ctx.ships[i].getVelocityVector();
|
||||
const Vec2 IMPULSE = SHIP_VEL * (Defaults::Ship::MASS * Defaults::Physics::Ship::DEATH_IMPACT_MOMENTUM_FACTOR);
|
||||
const float DEATH_FACTOR = ctx.ships[i].getConfig().physics.death_impact_factor;
|
||||
const Vec2 IMPULSE = SHIP_VEL * (ctx.ships[i].getBody().mass * DEATH_FACTOR);
|
||||
touched_enemy->applyImpulse(IMPULSE);
|
||||
ctx.on_player_hit(i);
|
||||
} else {
|
||||
|
||||
@@ -1,92 +1,99 @@
|
||||
// pack_resources.cpp - Utilitat per crear paquets de recursos
|
||||
// © 2026 JailDesigner
|
||||
|
||||
#include "../../source/core/resources/resource_pack.hpp"
|
||||
|
||||
#include <filesystem>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
void print_usage(const char* program_name) {
|
||||
std::cout << "Ús: " << program_name << " [opcions] [directori_entrada] [fitxer_sortida]\n";
|
||||
std::cout << "\nOpcions:\n";
|
||||
std::cout << " --list <fitxer> Llistar contingut d'un paquet\n";
|
||||
std::cout << "\nExemples:\n";
|
||||
std::cout << " " << program_name << " data resources.pack\n";
|
||||
std::cout << " " << program_name << " --list resources.pack\n";
|
||||
std::cout << "\nSi no s'especifiquen arguments, empaqueta 'data/' a 'resources.pack'\n";
|
||||
#include "core/resources/resource_pack.hpp"
|
||||
#include "project.h"
|
||||
|
||||
namespace {
|
||||
|
||||
void showHelp() {
|
||||
std::cout << Project::LONG_NAME << " - Resource Packer\n";
|
||||
std::cout << "==============================================\n";
|
||||
std::cout << "Usage: pack_resources [options] [input_dir] [output_file]\n\n";
|
||||
std::cout << "Options:\n";
|
||||
std::cout << " --help Show this help message\n";
|
||||
std::cout << " --list List contents of an existing pack file\n\n";
|
||||
std::cout << "Arguments:\n";
|
||||
std::cout << " input_dir Directory to pack (default: data)\n";
|
||||
std::cout << " output_file Pack file name (default: resources.pack)\n";
|
||||
}
|
||||
|
||||
void listPackContents(const std::string& pack_file) {
|
||||
Resource::Pack pack;
|
||||
if (!pack.loadPack(pack_file)) {
|
||||
std::cerr << "Error: cannot open pack file: " << pack_file << '\n';
|
||||
return;
|
||||
}
|
||||
auto resources = pack.getResourceList();
|
||||
std::cout << "Pack file: " << pack_file << '\n';
|
||||
std::cout << "Resources: " << resources.size() << '\n';
|
||||
for (const auto& r : resources) { std::cout << " " << r << '\n'; }
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char* argv[]) {
|
||||
std::string input_dir = "data";
|
||||
std::string data_dir = "data";
|
||||
std::string output_file = "resources.pack";
|
||||
bool list_mode = false;
|
||||
bool data_dir_set = false;
|
||||
|
||||
// Processar arguments
|
||||
if (argc == 2 && std::string(argv[1]) == "--help") {
|
||||
print_usage(argv[0]);
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
std::string arg = argv[i];
|
||||
if (arg == "--help" || arg == "-h") {
|
||||
showHelp();
|
||||
return 0;
|
||||
}
|
||||
if (arg == "--list") {
|
||||
list_mode = true;
|
||||
if (i + 1 < argc) { output_file = argv[++i]; }
|
||||
continue;
|
||||
}
|
||||
if (!arg.empty() && arg[0] != '-') {
|
||||
if (!data_dir_set) {
|
||||
data_dir = arg;
|
||||
data_dir_set = true;
|
||||
} else {
|
||||
output_file = arg;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (list_mode) {
|
||||
listPackContents(output_file);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Mode --list
|
||||
if (argc == 3 && std::string(argv[1]) == "--list") {
|
||||
Resource::Pack pack;
|
||||
if (!pack.loadPack(argv[2])) {
|
||||
std::cerr << "ERROR: No es pot carregar " << argv[2] << "\n";
|
||||
std::cout << Project::LONG_NAME << " - Resource Packer\n";
|
||||
std::cout << "==============================================\n";
|
||||
std::cout << "Input directory: " << data_dir << '\n';
|
||||
std::cout << "Output file: " << output_file << '\n';
|
||||
|
||||
if (!std::filesystem::exists(data_dir)) {
|
||||
std::cerr << "Error: input directory does not exist: " << data_dir << '\n';
|
||||
return 1;
|
||||
}
|
||||
|
||||
std::cout << "Contingut de " << argv[2] << ":\n";
|
||||
auto resources = pack.getResourceList();
|
||||
std::cout << "Total: " << resources.size() << " recursos\n\n";
|
||||
|
||||
for (const auto& name : resources) {
|
||||
std::cout << " " << name << "\n";
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Mode empaquetar
|
||||
if (argc >= 3) {
|
||||
input_dir = argv[1];
|
||||
output_file = argv[2];
|
||||
}
|
||||
|
||||
// Verificar que existeix el directori
|
||||
if (!std::filesystem::exists(input_dir)) {
|
||||
std::cerr << "ERROR: Directori no trobat: " << input_dir << "\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (!std::filesystem::is_directory(input_dir)) {
|
||||
std::cerr << "ERROR: " << input_dir << " no és un directori\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Crear paquet
|
||||
std::cout << "Creant paquet de recursos...\n";
|
||||
std::cout << " Entrada: " << input_dir << "\n";
|
||||
std::cout << " Sortida: " << output_file << "\n\n";
|
||||
|
||||
Resource::Pack pack;
|
||||
if (!pack.addDirectory(input_dir)) {
|
||||
std::cerr << "ERROR: No s'ha pogut afegir el directori\n";
|
||||
std::cout << "Scanning and packing resources...\n";
|
||||
if (!pack.addDirectory(data_dir)) {
|
||||
std::cerr << "Error: failed to add directory to pack\n";
|
||||
return 1;
|
||||
}
|
||||
std::cout << "Found " << pack.getResourceList().size() << " resources\n";
|
||||
|
||||
std::cout << "Saving pack file...\n";
|
||||
if (!pack.savePack(output_file)) {
|
||||
std::cerr << "ERROR: No s'ha pogut guardar el paquet\n";
|
||||
std::cerr << "Error: failed to save pack file\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Resum
|
||||
auto resources = pack.getResourceList();
|
||||
std::cout << "\n";
|
||||
std::cout << "✓ Paquet creat amb èxit!\n";
|
||||
std::cout << " Recursos: " << resources.size() << "\n";
|
||||
|
||||
// Mostrar mida del fitxer
|
||||
auto file_size = std::filesystem::file_size(output_file);
|
||||
std::cout << " Mida: " << (file_size / 1024) << " KB\n";
|
||||
|
||||
auto file_size = std::filesystem::file_size(std::filesystem::path(output_file));
|
||||
std::cout << "Pack file created: " << output_file << " ("
|
||||
<< (static_cast<double>(file_size) / 1024.0 / 1024.0) << " MB)\n";
|
||||
return 0;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user