afegit CMakeLists.txt

arreglos d'estil
This commit is contained in:
2025-03-23 20:27:03 +01:00
parent 4c9b8adfa6
commit 9cddd6e03b
4 changed files with 237 additions and 167 deletions

5
.gitignore vendored
View File

@@ -1,3 +1,5 @@
build/
# ---> C++ # ---> C++
# Prerequisites # Prerequisites
*.d *.d
@@ -39,7 +41,8 @@
.LSOverride .LSOverride
# Icon must end with two \r # Icon must end with two \r
Icon Icon
# Thumbnails # Thumbnails
._* ._*

55
CMakeLists.txt Normal file
View File

@@ -0,0 +1,55 @@
cmake_minimum_required(VERSION 3.20)
project(demo3_pixels_bouncing)
# Establecer el estándar de C++
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# Opciones comunes de compilación
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Os")
# Buscar SDL3 automáticamente
find_package(SDL3 REQUIRED)
# Si no se encuentra SDL3, generar un error
if (NOT SDL3_FOUND)
message(FATAL_ERROR "SDL3 no encontrado. Por favor, verifica su instalación.")
endif()
# Archivos fuente
file(GLOB SOURCE_FILES source/*.cpp)
# Comprobar si se encontraron archivos fuente
if(NOT SOURCE_FILES)
message(FATAL_ERROR "No se encontraron archivos fuente en el directorio 'source/'. Verifica la ruta.")
endif()
# Nombre del ejecutable
set(EXECUTABLE_NAME demo3_pixels_bouncing)
# Detectar la plataforma y configuraciones específicas
if(WIN32)
set(PLATFORM windows)
set(LINK_LIBS ${SDL3_LIBRARIES} mingw32 ws2_32)
set(EXECUTABLE_EXTENSION ".exe")
elseif(UNIX AND NOT APPLE)
set(PLATFORM linux)
set(LINK_LIBS ${SDL3_LIBRARIES})
set(EXECUTABLE_EXTENSION ".out")
elseif(APPLE)
set(PLATFORM macos)
set(LINK_LIBS ${SDL3_LIBRARIES})
set(EXECUTABLE_EXTENSION ".out")
endif()
# Incluir directorios de SDL3
include_directories(${SDL3_INCLUDE_DIRS})
# Añadir el ejecutable
add_executable(${EXECUTABLE_NAME}${EXECUTABLE_EXTENSION} ${SOURCE_FILES})
# Especificar la ubicación del ejecutable (en la raíz del proyecto)
set_target_properties(${EXECUTABLE_NAME}${EXECUTABLE_EXTENSION} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR})
# Enlazar las bibliotecas necesarias
target_link_libraries(${EXECUTABLE_NAME}${EXECUTABLE_EXTENSION} ${LINK_LIBS})

View File

@@ -10,7 +10,8 @@ constexpr int ZOOM = 3;
constexpr float GRAVITY = 0.2f; constexpr float GRAVITY = 0.2f;
constexpr int DOT_SIZE = 1; constexpr int DOT_SIZE = 1;
constexpr int MAX_DOTS = 200000; constexpr int MAX_DOTS = 200000;
constexpr int TEXT_TIME = 100; constexpr Uint64 TEXT_DURATION = 2000;
constexpr Uint64 DEMO_SPEED = 1000/60;
struct Color struct Color
{ {

View File

@@ -5,236 +5,247 @@
#include <iostream> #include <iostream>
#include <vector> #include <vector>
SDL_Window *window = NULL; // Ventana y renderizador
SDL_Renderer *renderer = NULL; SDL_Window *window = nullptr;
SDL_Renderer *renderer = nullptr;
// Datos de los puntos y su representación gráfica
Dot::DotData dots[MAX_DOTS]; Dot::DotData dots[MAX_DOTS];
SDL_FPoint dot_points[MAX_DOTS]; SDL_FPoint dot_points[MAX_DOTS];
// Escenarios y configuración
int test[8] = {1, 10, 100, 500, 1000, 10000, 50000, MAX_DOTS}; int test[8] = {1, 10, 100, 500, 1000, 10000, 50000, MAX_DOTS};
int scenario = 0; int scenario = 0;
std::string text = ""; std::string text = "";
int text_pos = 0; int text_pos = 0;
bool show_text = true; bool show_text = true;
int counter = 0; Uint64 text_init_time;
bool should_exit = false; bool should_exit = false;
Uint32 ticks = 0; Uint64 ticks = 0;
// Actualiza el texto a mostrar en pantalla
void setText() void setText()
{ {
const std::string text2 = test[scenario] == 1 ? " PIXEL" : " PIXELS"; const std::string text2 = test[scenario] == 1 ? " PIXEL" : " PIXELES";
text = std::to_string(test[scenario]) + text2; text = std::to_string(test[scenario]) + text2;
const int size = text.size() * 8; const int size = text.size() * 8;
text_pos = WIDTH / 2 - size / 2; text_pos = WIDTH / 2 - size / 2;
counter = TEXT_TIME; text_init_time = SDL_GetTicks();
show_text = true; show_text = true;
} }
// Inicializa los puntos para el escenario actual
void initDots() void initDots()
{ {
for (int i = 0; i < test[scenario]; ++i) for (int i = 0; i < test[scenario]; ++i)
{ {
const int sign = ((rand() % 2) * 2) - 1; const int sign = ((rand() % 2) * 2) - 1;
const float x = (rand() % (WIDTH / 2)) + (WIDTH / 4); const float x = (rand() % (WIDTH / 2)) + (WIDTH / 4);
const float vx = (((rand() % 20) + 10) * 0.1f) * sign; const float vx = (((rand() % 20) + 10) * 0.1f) * sign;
const float vy = ((rand() % 60) - 30) * 0.1f; const float vy = ((rand() % 60) - 30) * 0.1f;
const Color color = {(rand() % 192) + 32, (rand() % 192) + 32, (rand() % 192) + 32}; const Color color = {(rand() % 192) + 32, (rand() % 192) + 32, (rand() % 192) + 32};
dots[i] = Dot::ini(x, vx, vy, color); dots[i] = Dot::ini(x, vx, vy, color);
} }
setText(); setText();
} }
// Empuja los puntos hacia arriba con una fuerza aleatoria
void pushUpDots() void pushUpDots()
{ {
for (int i = 0; i < test[scenario]; ++i) for (int i = 0; i < test[scenario]; ++i)
{ {
const int sign = ((rand() % 2) * 2) - 1; const int sign = ((rand() % 2) * 2) - 1;
const float vx = (((rand() % 20) + 10) * 0.1f) * sign; const float vx = (((rand() % 20) + 10) * 0.1f) * sign;
const float vy = ((rand() % 40) * 0.1f) + 5; const float vy = ((rand() % 40) * 0.1f) + 5;
Dot::modVel(dots[i], vx, -vy); Dot::modVel(dots[i], vx, -vy);
} }
} }
// Inicializa SDL y configura la ventana y el renderizador
bool init() bool init()
{ {
// Initialization flag bool success = true;
bool success = true;
// Initialize SDL // Inicializar SDL
if (!SDL_Init(SDL_INIT_VIDEO)) if (!SDL_Init(SDL_INIT_VIDEO))
{ {
printf("SDL could not initialize! SDL Error: %s\n", SDL_GetError()); std::cout << "¡SDL no se pudo inicializar! Error de SDL: " << SDL_GetError() << std::endl;
success = false; success = false;
} }
else else
{ {
// Create window // Crear ventana
window = SDL_CreateWindow(WINDOW_CAPTION, WIDTH * ZOOM, HEIGHT * ZOOM, SDL_WINDOW_OPENGL); window = SDL_CreateWindow(WINDOW_CAPTION, WIDTH * ZOOM, HEIGHT * ZOOM, SDL_WINDOW_OPENGL);
if (window == nullptr) if (window == nullptr)
{ {
printf("Window could not be created! SDL Error: %s\n", SDL_GetError()); std::cout << "¡No se pudo crear la ventana! Error de SDL: " << SDL_GetError() << std::endl;
success = false; success = false;
} }
else else
{ {
// Create renderer for window // Crear renderizador
renderer = SDL_CreateRenderer(window, nullptr); renderer = SDL_CreateRenderer(window, nullptr);
if (renderer == nullptr) if (renderer == nullptr)
{ {
printf("Renderer could not be created! SDL Error: %s\n", SDL_GetError()); std::cout << "¡No se pudo crear el renderizador! Error de SDL: " << SDL_GetError() << std::endl;
success = false; success = false;
} }
else else
{ {
// Initialize renderer color // Inicializar el color del renderizador
SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF); SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
// Establece el tamaño del renderizador // Establecer el tamaño lógico del renderizador
SDL_SetRenderLogicalPresentation(renderer, WIDTH, HEIGHT, SDL_LOGICAL_PRESENTATION_INTEGER_SCALE); SDL_SetRenderLogicalPresentation(renderer, WIDTH, HEIGHT, SDL_LOGICAL_PRESENTATION_INTEGER_SCALE);
} }
} }
} }
ticks = SDL_GetTicks(); ticks = SDL_GetTicks();
srand(time(nullptr)); srand(time(nullptr));
dbg_init(renderer); dbg_init(renderer);
initDots(); initDots();
setText(); setText();
return success; return success;
} }
// Libera los recursos y cierra SDL
void close() void close()
{ {
// Destroy window SDL_DestroyRenderer(renderer);
SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window);
SDL_DestroyWindow(window);
// Quit SDL subsystems // Finalizar SDL
SDL_Quit(); SDL_Quit();
} }
// Maneja los eventos del teclado y del sistema
void checkEvents() void checkEvents()
{ {
SDL_Event event; SDL_Event event;
// Comprueba los eventos que hay en la cola while (SDL_PollEvent(&event) != 0)
while (SDL_PollEvent(&event) != 0) {
{ // Evento de salida
// Evento de salida de la aplicación if (event.type == SDL_EVENT_QUIT)
if (event.type == SDL_EVENT_QUIT) {
{ should_exit = true;
should_exit = true; break;
break; }
}
if (event.type == SDL_EVENT_KEY_DOWN && event.key.repeat == 0) // Eventos de teclado
{ if (event.type == SDL_EVENT_KEY_DOWN && event.key.repeat == 0)
switch (event.key.key) {
{ switch (event.key.key)
case SDLK_ESCAPE: {
should_exit = true; case SDLK_ESCAPE:
break; should_exit = true;
break;
case SDLK_SPACE: case SDLK_SPACE:
pushUpDots(); pushUpDots();
break; break;
case SDLK_1: case SDLK_1:
scenario = 0; scenario = 0;
initDots(); initDots();
break; break;
case SDLK_2: case SDLK_2:
scenario = 1; scenario = 1;
initDots(); initDots();
break; break;
case SDLK_3: case SDLK_3:
scenario = 2; scenario = 2;
initDots(); initDots();
break; break;
case SDLK_4: case SDLK_4:
scenario = 3; scenario = 3;
initDots(); initDots();
break; break;
case SDLK_5: case SDLK_5:
scenario = 4; scenario = 4;
initDots(); initDots();
break; break;
case SDLK_6: case SDLK_6:
scenario = 5; scenario = 5;
initDots(); initDots();
break; break;
case SDLK_7: case SDLK_7:
scenario = 6; scenario = 6;
initDots(); initDots();
break; break;
case SDLK_8: case SDLK_8:
scenario = 7; scenario = 7;
initDots(); initDots();
break; break;
default: default:
break; break;
} }
} }
} }
} }
// Actualiza la posición de los puntos y gestiona el temporizador del texto
void update() void update()
{ {
if (SDL_GetTicks() - ticks > 15) if (SDL_GetTicks() - ticks > DEMO_SPEED)
{ {
ticks = SDL_GetTicks(); ticks = SDL_GetTicks();
for (int i = 0; i < test[scenario]; ++i) for (int i = 0; i < test[scenario]; ++i)
{ {
dot_points[i] = Dot::update(dots[i]); dot_points[i] = Dot::update(dots[i]);
} }
if (counter > 0) if (show_text)
{ {
counter--; show_text = !(SDL_GetTicks() - text_init_time > TEXT_DURATION);
} }
else }
{
show_text = false;
}
}
} }
// Renderiza el contenido en la pantalla
void render() void render()
{ {
SDL_SetRenderDrawColor(renderer, 32, 32, 32, 255); SDL_SetRenderDrawColor(renderer, 32, 32, 32, 255);
SDL_RenderClear(renderer); SDL_RenderClear(renderer);
SDL_SetRenderDrawColor(renderer, 224, 224, 224, 255); SDL_SetRenderDrawColor(renderer, 224, 224, 224, 255);
SDL_RenderPoints(renderer, dot_points, test[scenario]); SDL_RenderPoints(renderer, dot_points, test[scenario]);
if (show_text) if (show_text)
{ {
dbg_print(text_pos, 8, text.c_str(), 255, 32, 32); dbg_print(text_pos, 8, text.c_str(), 255, 32, 32);
} }
SDL_RenderPresent(renderer); SDL_RenderPresent(renderer);
} }
// Función principal
int main(int argc, char *args[]) int main(int argc, char *args[])
{ {
init(); if (!init())
{
return -1;
}
while (!should_exit) while (!should_exit)
{ {
update(); update();
checkEvents(); checkEvents();
render(); render();
} }
close(); close();
return 0; return 0;
} }