Files
projecte_2026/source/utils/utils.cpp

260 lines
7.6 KiB
C++

#include "utils/utils.hpp"
#include <algorithm> // Para find, transform, ranges::all_of
#include <array> // Para array
#include <cctype> // Para tolower, isdigit
#include <cmath> // Para round, abs
#include <cstdlib> // Para abs
#include <exception> // Para exception
#include <filesystem> // Para path
#include <iostream> // Para basic_ostream, cout, basic_ios, ios, endl
#include <string> // Para basic_string, string, char_traits, allocator
#include <unordered_map> // Para unordered_map, operator==, _Node_const_iter...
#include <utility> // Para pair
#include "core/resources/resource_cache.hpp" // Para Resource
// Calcula el cuadrado de la distancia entre dos puntos
auto distanceSquared(int x1, int y1, int x2, int y2) -> double {
const int DELTA_X = x2 - x1;
const int DELTA_Y = y2 - y1;
return (DELTA_X * DELTA_X) + (DELTA_Y * DELTA_Y);
}
// Detector de colisiones entre dos circulos
auto checkCollision(const Circle& a, const Circle& b) -> bool {
// Calcula el radio total al cuadrado
int total_radius_squared = a.r + b.r;
total_radius_squared = total_radius_squared * total_radius_squared;
// Si la distancia entre el centro de los circulos es inferior a la suma de sus radios
return distanceSquared(a.x, a.y, b.x, b.y) < total_radius_squared;
}
// Detector de colisiones entre un circulo y un rectangulo
auto checkCollision(const Circle& a, const SDL_FRect& rect) -> bool {
SDL_Rect b = toSDLRect(rect);
// Closest point on collision box
int c_x;
int c_y;
// Find closest x offset
if (a.x < b.x) {
c_x = b.x;
} else if (a.x > b.x + b.w) {
c_x = b.x + b.w;
} else {
c_x = a.x;
}
// Find closest y offset
if (a.y < b.y) {
c_y = b.y;
} else if (a.y > b.y + b.h) {
c_y = b.y + b.h;
} else {
c_y = a.y;
}
// If the closest point is inside the circle_t
if (distanceSquared(a.x, a.y, c_x, c_y) < a.r * a.r) {
// This box and the circle_t have collided
return true;
}
// If the shapes have not collided
return false;
}
// Detector de colisiones entre dos rectangulos
auto checkCollision(const SDL_FRect& rect_a, const SDL_FRect& rect_b) -> bool {
SDL_Rect a = toSDLRect(rect_a);
SDL_Rect b = toSDLRect(rect_b);
// Calcula las caras del rectangulo a
const int LEFT_A = a.x;
const int RIGHT_A = a.x + a.w;
const int TOP_A = a.y;
const int BOTTOM_A = a.y + a.h;
// Calcula las caras del rectangulo b
const int LEFT_B = b.x;
const int RIGHT_B = b.x + b.w;
const int TOP_B = b.y;
const int BOTTOM_B = b.y + b.h;
// Si cualquiera de las caras de a está fuera de b
if (BOTTOM_A <= TOP_B) {
return false;
}
if (TOP_A >= BOTTOM_B) {
return false;
}
if (RIGHT_A <= LEFT_B) {
return false;
}
if (LEFT_A >= RIGHT_B) {
return false;
}
// Si ninguna de las caras está fuera de b
return true;
}
// Detector de colisiones entre un punto y un rectangulo
auto checkCollision(const SDL_FPoint& point, const SDL_FRect& rect) -> bool {
SDL_Rect r = toSDLRect(rect);
SDL_Point p = toSDLPoint(point);
// Comprueba si el punto está a la izquierda del rectangulo
if (p.x < r.x) {
return false;
}
// Comprueba si el punto está a la derecha del rectangulo
if (p.x > r.x + r.w) {
return false;
}
// Comprueba si el punto está por encima del rectangulo
if (p.y < r.y) {
return false;
}
// Comprueba si el punto está por debajo del rectangulo
if (p.y > r.y + r.h) {
return false;
}
// Si no está fuera, es que está dentro
return true;
}
// Convierte SDL_FRect a SDL_Rect
auto toSDLRect(const SDL_FRect& frect) -> SDL_Rect {
SDL_Rect rect = {
.x = static_cast<int>(frect.x),
.y = static_cast<int>(frect.y),
.w = static_cast<int>(frect.w),
.h = static_cast<int>(frect.h)};
return rect;
}
// Convierte SDL_FPoint a SDL_Point
auto toSDLPoint(const SDL_FPoint& fpoint) -> SDL_Point {
SDL_Point point = {
.x = static_cast<int>(fpoint.x),
.y = static_cast<int>(fpoint.y)};
return point;
}
// Convierte una cadena a un entero de forma segura
auto safeStoi(const std::string& value, int default_value) -> int {
try {
return std::stoi(value);
} catch (const std::exception&) {
return default_value;
}
}
// Convierte una cadena a un booleano
auto stringToBool(const std::string& str) -> bool {
std::string lower_str = str;
std::ranges::transform(lower_str, lower_str.begin(), ::tolower);
return (lower_str == "true" || lower_str == "1" || lower_str == "yes" || lower_str == "on");
}
// Convierte un booleano a una cadena
auto boolToString(bool value) -> std::string {
return value ? "1" : "0";
}
// Compara dos colores
auto colorAreEqual(Rgb color1, Rgb color2) -> bool {
const bool R = color1.r == color2.r;
const bool G = color1.g == color2.g;
const bool B = color1.b == color2.b;
return (R && G && B);
}
// Función para convertir un string a minúsculas
auto toLower(const std::string& str) -> std::string {
std::string lower_str = str;
std::ranges::transform(lower_str, lower_str.begin(), ::tolower);
return lower_str;
}
// Función para convertir un string a mayúsculas
auto toUpper(const std::string& str) -> std::string {
std::string upper_str = str;
std::ranges::transform(upper_str, upper_str.begin(), ::toupper);
return upper_str;
}
// Convierte guiones a espacios ("crt-live" → "crt live")
auto prettyName(const std::string& str) -> std::string {
std::string result = str;
std::ranges::replace(result, '-', ' ');
return result;
}
// Obtiene el nombre de un fichero a partir de una ruta completa
auto getFileName(const std::string& path) -> std::string {
return std::filesystem::path(path).filename().string();
}
// Obtiene la ruta eliminando el nombre del fichero
auto getPath(const std::string& full_path) -> std::string {
std::filesystem::path path(full_path);
return path.parent_path().string();
}
// Imprime por pantalla una linea de texto de tamaño fijo rellena con puntos
void printWithDots(const std::string& text1, const std::string& text2, const std::string& text3) {
std::cout.setf(std::ios::left, std::ios::adjustfield);
std::cout << text1;
std::cout.width(50 - text1.length() - text3.length());
std::cout.fill('.');
std::cout << text2;
std::cout << text3 << '\n';
}
// Comprueba si una vector contiene una cadena
auto stringInVector(const std::vector<std::string>& vec, const std::string& str) -> bool {
return std::ranges::find(vec, str) != vec.end();
}
// Rellena una textura de un color
void fillTextureWithColor(SDL_Renderer* renderer, SDL_Texture* texture, Uint8 r, Uint8 g, Uint8 b, Uint8 a) {
// Guardar el render target actual
SDL_Texture* previous_target = SDL_GetRenderTarget(renderer);
// Establecer la textura como el render target
SDL_SetRenderTarget(renderer, texture);
// Establecer el color deseado
SDL_SetRenderDrawColor(renderer, r, g, b, a);
// Pintar toda el área
SDL_RenderClear(renderer);
// Restaurar el render target previo
SDL_SetRenderTarget(renderer, previous_target);
}
// Añade espacios entre las letras de un string
auto spaceBetweenLetters(const std::string& input) -> std::string {
std::string result;
for (size_t i = 0; i < input.size(); ++i) {
result += input[i];
if (i != input.size() - 1) {
result += ' ';
}
}
return result;
}