Compare commits
13 Commits
b628b426c1
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| e36a555038 | |||
| 9bc129e9b0 | |||
| 29b18e30b5 | |||
| e2e3b7c779 | |||
| 4a2e5c27e2 | |||
| 111cbb2217 | |||
| 578549b122 | |||
| 1883032be5 | |||
| af5bc7dcd6 | |||
| dbcc7faeba | |||
| 066188f6bf | |||
| 5501c00ef4 | |||
| 531a6d1f90 |
107
.gitignore
vendored
107
.gitignore
vendored
@@ -1,2 +1,107 @@
|
|||||||
*.exe
|
demo5_sprites_bouncing
|
||||||
|
build/
|
||||||
|
|
||||||
|
# ---> C++
|
||||||
|
# Prerequisites
|
||||||
|
*.d
|
||||||
|
|
||||||
|
# Compiled Object files
|
||||||
|
*.slo
|
||||||
|
*.lo
|
||||||
|
*.o
|
||||||
|
*.obj
|
||||||
|
|
||||||
|
# Precompiled Headers
|
||||||
|
*.gch
|
||||||
|
*.pch
|
||||||
|
|
||||||
|
# Compiled Dynamic libraries
|
||||||
|
*.so
|
||||||
|
*.dylib
|
||||||
*.dll
|
*.dll
|
||||||
|
|
||||||
|
# Fortran module files
|
||||||
|
*.mod
|
||||||
|
*.smod
|
||||||
|
|
||||||
|
# Compiled Static libraries
|
||||||
|
*.lai
|
||||||
|
*.la
|
||||||
|
*.a
|
||||||
|
*.lib
|
||||||
|
|
||||||
|
# Executables
|
||||||
|
*.exe
|
||||||
|
*.out
|
||||||
|
*.app
|
||||||
|
|
||||||
|
# ---> macOS
|
||||||
|
# General
|
||||||
|
.DS_Store
|
||||||
|
.AppleDouble
|
||||||
|
.LSOverride
|
||||||
|
|
||||||
|
# Icon must end with two \r
|
||||||
|
Icon
|
||||||
|
|
||||||
|
|
||||||
|
# Thumbnails
|
||||||
|
._*
|
||||||
|
|
||||||
|
# Files that might appear in the root of a volume
|
||||||
|
.DocumentRevisions-V100
|
||||||
|
.fseventsd
|
||||||
|
.Spotlight-V100
|
||||||
|
.TemporaryItems
|
||||||
|
.Trashes
|
||||||
|
.VolumeIcon.icns
|
||||||
|
.com.apple.timemachine.donotpresent
|
||||||
|
|
||||||
|
# Directories potentially created on remote AFP share
|
||||||
|
.AppleDB
|
||||||
|
.AppleDesktop
|
||||||
|
Network Trash Folder
|
||||||
|
Temporary Items
|
||||||
|
.apdisk
|
||||||
|
|
||||||
|
# ---> Windows
|
||||||
|
# Windows thumbnail cache files
|
||||||
|
Thumbs.db
|
||||||
|
Thumbs.db:encryptable
|
||||||
|
ehthumbs.db
|
||||||
|
ehthumbs_vista.db
|
||||||
|
|
||||||
|
# Dump file
|
||||||
|
*.stackdump
|
||||||
|
|
||||||
|
# Folder config file
|
||||||
|
[Dd]esktop.ini
|
||||||
|
|
||||||
|
# Recycle Bin used on file shares
|
||||||
|
$RECYCLE.BIN/
|
||||||
|
|
||||||
|
# Windows Installer files
|
||||||
|
*.cab
|
||||||
|
*.msi
|
||||||
|
*.msix
|
||||||
|
*.msm
|
||||||
|
*.msp
|
||||||
|
|
||||||
|
# Windows shortcuts
|
||||||
|
*.lnk
|
||||||
|
|
||||||
|
# ---> Linux
|
||||||
|
*~
|
||||||
|
|
||||||
|
# temporary files which can be created if a process still has a handle open of a deleted file
|
||||||
|
.fuse_hidden*
|
||||||
|
|
||||||
|
# KDE directory preferences
|
||||||
|
.directory
|
||||||
|
|
||||||
|
# Linux trash folder which might appear on any partition or disk
|
||||||
|
.Trash-*
|
||||||
|
|
||||||
|
# .nfs files are created when an open file is removed but is still being accessed
|
||||||
|
.nfs*
|
||||||
|
|
||||||
|
|||||||
5
.vscode/settings.json
vendored
5
.vscode/settings.json
vendored
@@ -1,5 +0,0 @@
|
|||||||
{
|
|
||||||
"files.associations": {
|
|
||||||
"iostream": "cpp"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
49
CMakeLists.txt
Normal file
49
CMakeLists.txt
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
cmake_minimum_required(VERSION 3.20)
|
||||||
|
project(demo5_sprites_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 -ffunction-sections -fdata-sections")
|
||||||
|
|
||||||
|
# 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()
|
||||||
|
|
||||||
|
# Detectar la plataforma y configuraciones específicas
|
||||||
|
if(WIN32)
|
||||||
|
set(PLATFORM windows)
|
||||||
|
set(LINK_LIBS ${SDL3_LIBRARIES} mingw32 ws2_32)
|
||||||
|
elseif(UNIX AND NOT APPLE)
|
||||||
|
set(PLATFORM linux)
|
||||||
|
set(LINK_LIBS ${SDL3_LIBRARIES})
|
||||||
|
elseif(APPLE)
|
||||||
|
set(PLATFORM macos)
|
||||||
|
set(LINK_LIBS ${SDL3_LIBRARIES})
|
||||||
|
endif()
|
||||||
|
|
||||||
|
# Incluir directorios de SDL3
|
||||||
|
include_directories(${SDL3_INCLUDE_DIRS})
|
||||||
|
|
||||||
|
# Añadir el ejecutable reutilizando el nombre del proyecto
|
||||||
|
add_executable(${PROJECT_NAME} ${SOURCE_FILES})
|
||||||
|
|
||||||
|
# Especificar la ubicación del ejecutable (en la raíz del proyecto)
|
||||||
|
set_target_properties(${PROJECT_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR})
|
||||||
|
|
||||||
|
# Enlazar las bibliotecas necesarias
|
||||||
|
target_link_libraries(${PROJECT_NAME} ${LINK_LIBS})
|
||||||
25
Makefile
25
Makefile
@@ -1,11 +1,20 @@
|
|||||||
source := source/*.cpp
|
# Variables comunes
|
||||||
executable_name := demo_pelotas2
|
SOURCE := source/*.cpp
|
||||||
|
EXECUTABLE_NAME := demo5_sprites_bouncing
|
||||||
|
CXXFLAGS := -std=c++20 -Wall -Os -ffunction-sections -fdata-sections # Opciones comunes de compilación
|
||||||
|
LDFLAGS := -lSDL3 # Flags de enlace comunes
|
||||||
|
OUTPUT_EXT :=
|
||||||
|
|
||||||
windows:
|
# Detectar plataforma y configurar
|
||||||
g++ $(source) -Wall -lmingw32 -lws2_32 -lSDL2main -lSDL2 -o $(executable_name).exe
|
ifeq ($(OS),Windows_NT)
|
||||||
|
LDFLAGS += -lmingw32 -lws2_32
|
||||||
|
OUTPUT_EXT := .exe
|
||||||
|
endif
|
||||||
|
|
||||||
linux:
|
# Regla principal: compilar el ejecutable
|
||||||
g++ $(source) -Wall -lSDL2 -o $(executable_name)
|
all:
|
||||||
|
$(CXX) $(SOURCE) $(CXXFLAGS) $(LDFLAGS) -o $(EXECUTABLE_NAME)$(OUTPUT_EXT)
|
||||||
|
|
||||||
macos:
|
# Regla para limpiar archivos generados
|
||||||
g++ $(source) -Wall -lSDL2 -o $(executable_name)
|
clean:
|
||||||
|
rm -f $(EXECUTABLE_NAME)$(OUTPUT_EXT)
|
||||||
|
Before Width: | Height: | Size: 128 B After Width: | Height: | Size: 128 B |
117
source/ball.cpp
117
source/ball.cpp
@@ -1,118 +1,113 @@
|
|||||||
#include "ball.h"
|
#include "ball.h"
|
||||||
#include "defines.h"
|
#include <stdlib.h> // for rand
|
||||||
|
#include <cmath> // for fabs
|
||||||
|
#include "defines.h" // for BALL_SIZE, Color, SCREEN_HEIGHT, GRAVITY_FORCE
|
||||||
|
class Texture;
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Ball::Ball(float x, float vx, float vy, color_t color, Texture *texture)
|
Ball::Ball(float x, float vx, float vy, Color color, std::shared_ptr<Texture> texture)
|
||||||
|
: sprite_(std::make_unique<Sprite>(texture)),
|
||||||
|
pos_({x, 0.0f, BALL_SIZE, BALL_SIZE})
|
||||||
{
|
{
|
||||||
this->x = x;
|
vx_ = vx;
|
||||||
this->y = 0.0f;
|
vy_ = vy;
|
||||||
this->w = BALL_SIZE;
|
sprite_->setPos({pos_.x, pos_.y});
|
||||||
this->h = BALL_SIZE;
|
sprite_->setSize(BALL_SIZE, BALL_SIZE);
|
||||||
this->vx = vx;
|
sprite_->setClip({0, 0, BALL_SIZE, BALL_SIZE});
|
||||||
this->vy = vy;
|
color_ = color;
|
||||||
sprite = new Sprite(texture);
|
gravity_force_ = GRAVITY_FORCE;
|
||||||
sprite->setPos({(int)x, (int)y});
|
on_floor_ = false;
|
||||||
sprite->setSize(BALL_SIZE, BALL_SIZE);
|
stopped_ = false;
|
||||||
sprite->setClip({0, 0, BALL_SIZE, BALL_SIZE});
|
loss_ = ((rand() % 30) * 0.01f) + 0.6f;
|
||||||
this->color = color;
|
|
||||||
g = GRAVITY;
|
|
||||||
onFloor = false;
|
|
||||||
stopped = false;
|
|
||||||
loss = ((rand() % 30) * 0.01f) + 0.6f;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Destructor
|
|
||||||
Ball::~Ball()
|
|
||||||
{
|
|
||||||
if (sprite)
|
|
||||||
{
|
|
||||||
delete sprite;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza la lógica de la clase
|
// Actualiza la lógica de la clase
|
||||||
void Ball::update()
|
void Ball::update()
|
||||||
{
|
{
|
||||||
if (stopped)
|
if (stopped_)
|
||||||
{
|
{
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Aplica la gravedad a la velocidad
|
// Aplica la gravedad a la velocidad
|
||||||
if (!onFloor && (y - SCREEN_HEIGHT) < BALL_SIZE * 2)
|
if (!on_floor_ && (pos_.y - SCREEN_HEIGHT) < BALL_SIZE * 2)
|
||||||
{
|
{
|
||||||
vy += g;
|
vy_ += gravity_force_;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza la posición en función de la velocidad
|
// Actualiza la posición en función de la velocidad
|
||||||
x += vx;
|
pos_.x += vx_;
|
||||||
y += vy;
|
pos_.y += vy_;
|
||||||
|
|
||||||
// Comprueba las colisiones con el lateral izquierdo
|
// Comprueba las colisiones con el lateral izquierdo
|
||||||
if (x < 0)
|
if (pos_.x < 0)
|
||||||
{
|
{
|
||||||
x = 0;
|
pos_.x = 0;
|
||||||
vx = -vx;
|
vx_ = -vx_;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba las colisiones con el lateral derecho
|
// Comprueba las colisiones con el lateral derecho
|
||||||
if (x + w > SCREEN_WIDTH)
|
if (pos_.x + pos_.w > SCREEN_WIDTH)
|
||||||
{
|
{
|
||||||
x = SCREEN_WIDTH - w;
|
pos_.x = SCREEN_WIDTH - pos_.w;
|
||||||
vx = -vx;
|
vx_ = -vx_;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba las colisiones con la parte superior
|
// Comprueba las colisiones con la parte superior
|
||||||
if (y < 0)
|
if (pos_.y < 0)
|
||||||
{
|
{
|
||||||
y = 0;
|
pos_.y = 0;
|
||||||
vy = -vy;
|
vy_ = -vy_;
|
||||||
//vy = -vy * loss;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba las colisiones con la parte inferior
|
// Comprueba las colisiones con la parte inferior
|
||||||
if (y + h > SCREEN_HEIGHT)
|
if (pos_.y + pos_.h > SCREEN_HEIGHT)
|
||||||
{
|
{
|
||||||
y = SCREEN_HEIGHT - h;
|
pos_.y = SCREEN_HEIGHT - pos_.h;
|
||||||
vy = -vy * loss;
|
vy_ = -vy_ * loss_;
|
||||||
if (abs(vy) < 0.1f)
|
if (std::fabs(vy_) < 0.1f)
|
||||||
{
|
{
|
||||||
vy = 0.0f;
|
vy_ = 0.0f;
|
||||||
onFloor = true;
|
on_floor_ = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Aplica rozamiento al rodar por el suelo
|
// Aplica rozamiento al rodar por el suelo
|
||||||
if (onFloor)
|
if (on_floor_)
|
||||||
{
|
{
|
||||||
vx = vx * 0.97f;
|
vx_ = vx_ * 0.97f;
|
||||||
if (abs(vx) < 0.1f)
|
if (std::fabs(vx_) < 0.1f)
|
||||||
{
|
{
|
||||||
vx = 0.0f;
|
vx_ = 0.0f;
|
||||||
stopped = true;
|
stopped_ = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza la posición del sprite
|
// Actualiza la posición del sprite
|
||||||
sprite->setPos({(int)x, (int)y});
|
sprite_->setPos({pos_.x, pos_.y});
|
||||||
sprite->update();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pinta la clase
|
// Pinta la clase
|
||||||
void Ball::render()
|
void Ball::render()
|
||||||
{
|
{
|
||||||
sprite->setColor(color.r, color.g, color.b);
|
sprite_->setColor(color_.r, color_.g, color_.b);
|
||||||
sprite->render();
|
sprite_->render();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Modifica la velocidad
|
// Modifica la velocidad
|
||||||
void Ball::modVel(float vx, float vy)
|
void Ball::modVel(float vx, float vy)
|
||||||
{
|
{
|
||||||
if (stopped)
|
if (stopped_)
|
||||||
{
|
{
|
||||||
this->vx = this->vx + vx;
|
vx_ = vx_ + vx;
|
||||||
}
|
}
|
||||||
this->vy = this->vy + vy;
|
vy_ = vy_ + vy;
|
||||||
onFloor = false;
|
on_floor_ = false;
|
||||||
stopped = false;
|
stopped_ = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cambia la gravedad
|
||||||
|
void Ball::switchGravity()
|
||||||
|
{
|
||||||
|
gravity_force_ = gravity_force_ == 0.0f ? GRAVITY_FORCE : 0.0f;
|
||||||
}
|
}
|
||||||
@@ -1,30 +1,29 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include "sprite.h"
|
#include <SDL3/SDL_rect.h> // for SDL_FRect
|
||||||
#include "texture.h"
|
#include <memory> // for shared_ptr, unique_ptr
|
||||||
#include "defines.h"
|
#include "defines.h" // for Color
|
||||||
|
#include "sprite.h" // for Sprite
|
||||||
|
class Texture;
|
||||||
|
|
||||||
class Ball
|
class Ball
|
||||||
{
|
{
|
||||||
private:
|
private:
|
||||||
Sprite *sprite; // Sprite para pintar la clase
|
std::unique_ptr<Sprite> sprite_; // Sprite para pintar la clase
|
||||||
float x; // Posición x
|
SDL_FRect pos_; // Posición y tamaño de la pelota
|
||||||
float y; // Posición y
|
float vx_, vy_; // Velocidad
|
||||||
int w; // Ancho
|
float gravity_force_; // Gravedad
|
||||||
int h; // Alto
|
Color color_; // Color de la pelota
|
||||||
float vx, vy; // Velocidad
|
bool on_floor_; // Indica si la pelota está ya en el suelo
|
||||||
float g; // Gravedad
|
bool stopped_; // Indica si la pelota ha terminado de moverse;
|
||||||
color_t color; // Color de la pelota
|
float loss_; // Coeficiente de rebote. Pérdida de energía en cada rebote
|
||||||
bool onFloor; // Indica si la pelota está ya en el suelo
|
|
||||||
bool stopped; // Indica si la pelota ha terminado de moverse;
|
|
||||||
float loss; // Coeficiente de rebote. Pérdida de energía en cada rebote
|
|
||||||
|
|
||||||
public:
|
public:
|
||||||
// Constructor
|
// Constructor
|
||||||
Ball(float x, float vx, float vy, color_t color, Texture *texture);
|
Ball(float x, float vx, float vy, Color color, std::shared_ptr<Texture> texture);
|
||||||
|
|
||||||
// Destructor
|
// Destructor
|
||||||
~Ball();
|
~Ball() = default;
|
||||||
|
|
||||||
// Actualiza la lógica de la clase
|
// Actualiza la lógica de la clase
|
||||||
void update();
|
void update();
|
||||||
@@ -34,4 +33,7 @@ public:
|
|||||||
|
|
||||||
// Modifica la velocidad
|
// Modifica la velocidad
|
||||||
void modVel(float vx, float vy);
|
void modVel(float vx, float vy);
|
||||||
|
|
||||||
|
// Cambia la gravedad
|
||||||
|
void switchGravity();
|
||||||
};
|
};
|
||||||
42
source/dbgtxt.h
Normal file
42
source/dbgtxt.h
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
SDL_Texture *dbg_tex = nullptr;
|
||||||
|
SDL_Renderer *dbg_ren = nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
void dbg_init(SDL_Renderer *renderer)
|
||||||
|
{
|
||||||
|
dbg_ren = renderer;
|
||||||
|
Uint8 font[448] = {0x42, 0x4D, 0xC0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x82, 0x01, 0x00, 0x00, 0x12, 0x0B, 0x00, 0x00, 0x12, 0x0B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x18, 0xF3, 0x83, 0x83, 0xCF, 0x83, 0x87, 0x00, 0x00, 0xF3, 0x39, 0x39, 0xCF, 0x79, 0xF3, 0x00, 0x00, 0x01, 0xF9, 0x39, 0xCF, 0x61, 0xF9, 0x00, 0x00, 0x33, 0xF9, 0x03, 0xE7, 0x87, 0x81, 0x00, 0x00, 0x93, 0x03, 0x3F, 0xF3, 0x1B, 0x39, 0x00, 0x00, 0xC3, 0x3F, 0x9F, 0x39, 0x3B, 0x39, 0x00, 0x41, 0xE3, 0x03, 0xC3, 0x01, 0x87, 0x83, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xE7, 0x01, 0xC7, 0x81, 0x01, 0x83, 0x00, 0x00, 0xE7, 0x1F, 0x9B, 0xE7, 0x1F, 0x39, 0x00, 0x00, 0xE7, 0x8F, 0x39, 0xE7, 0x87, 0xF9, 0x00, 0x00, 0xC3, 0xC7, 0x39, 0xE7, 0xC3, 0xC3, 0x00, 0x00, 0x99, 0xE3, 0x39, 0xE7, 0xF1, 0xE7, 0x00, 0x00, 0x99, 0xF1, 0xB3, 0xC7, 0x39, 0xF3, 0x00, 0x00, 0x99, 0x01, 0xC7, 0xE7, 0x83, 0x81, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x83, 0xE7, 0x83, 0xEF, 0x39, 0x39, 0x00, 0x00, 0x39, 0xE7, 0x39, 0xC7, 0x11, 0x11, 0x00, 0x00, 0xF9, 0xE7, 0x39, 0x83, 0x01, 0x83, 0x00, 0x00, 0x83, 0xE7, 0x39, 0x11, 0x01, 0xC7, 0x00, 0x00, 0x3F, 0xE7, 0x39, 0x39, 0x29, 0x83, 0x00, 0x00, 0x33, 0xE7, 0x39, 0x39, 0x39, 0x11, 0x00, 0x00, 0x87, 0x81, 0x39, 0x39, 0x39, 0x39, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x39, 0x39, 0x83, 0x3F, 0x85, 0x31, 0x00, 0x00, 0x39, 0x31, 0x39, 0x3F, 0x33, 0x23, 0x00, 0x00, 0x29, 0x21, 0x39, 0x03, 0x21, 0x07, 0x00, 0x00, 0x01, 0x01, 0x39, 0x39, 0x39, 0x31, 0x00, 0x00, 0x01, 0x09, 0x39, 0x39, 0x39, 0x39, 0x00, 0x00, 0x11, 0x19, 0x39, 0x39, 0x39, 0x39, 0x00, 0x00, 0x39, 0x39, 0x83, 0x03, 0x83, 0x03, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xC1, 0x39, 0x81, 0x83, 0x31, 0x01, 0x00, 0x00, 0x99, 0x39, 0xE7, 0x39, 0x23, 0x3F, 0x00, 0x00, 0x39, 0x39, 0xE7, 0xF9, 0x07, 0x3F, 0x00, 0x00, 0x31, 0x01, 0xE7, 0xF9, 0x0F, 0x3F, 0x00, 0x00, 0x3F, 0x39, 0xE7, 0xF9, 0x27, 0x3F, 0x00, 0x00, 0x9F, 0x39, 0xE7, 0xF9, 0x33, 0x3F, 0x00, 0x00, 0xC1, 0x39, 0x81, 0xF9, 0x39, 0x3F, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x39, 0x03, 0xC3, 0x07, 0x01, 0x3F, 0x00, 0x00, 0x39, 0x39, 0x99, 0x33, 0x3F, 0x3F, 0x00, 0x00, 0x01, 0x39, 0x3F, 0x39, 0x3F, 0x3F, 0x00, 0x00, 0x39, 0x03, 0x3F, 0x39, 0x03, 0x03, 0x00, 0x00, 0x39, 0x39, 0x3F, 0x39, 0x3F, 0x3F, 0x00, 0x00, 0x93, 0x39, 0x99, 0x33, 0x3F, 0x3F, 0x00, 0x00, 0xC7, 0x03, 0xC3, 0x07, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00};
|
||||||
|
dbg_tex = SDL_CreateTextureFromSurface(dbg_ren, SDL_LoadBMP_IO(SDL_IOFromMem(font, 448), 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
void dbg_print(int x, int y, const char *text, Uint8 r, Uint8 g, Uint8 b)
|
||||||
|
{
|
||||||
|
int cc = 0;
|
||||||
|
SDL_SetTextureColorMod(dbg_tex, r, g, b);
|
||||||
|
SDL_FRect src = {0, 0, 8, 8};
|
||||||
|
SDL_FRect dst = {static_cast<float>(x), static_cast<float>(y), 8, 8};
|
||||||
|
while (text[cc] != 0)
|
||||||
|
{
|
||||||
|
if (text[cc] != 32)
|
||||||
|
{
|
||||||
|
if (text[cc] >= 65)
|
||||||
|
{
|
||||||
|
src.x = ((text[cc] - 65) % 6) * 8;
|
||||||
|
src.y = ((text[cc] - 65) / 6) * 8;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
src.x = ((text[cc] - 22) % 6) * 8;
|
||||||
|
src.y = ((text[cc] - 22) / 6) * 8;
|
||||||
|
}
|
||||||
|
|
||||||
|
SDL_RenderTexture(dbg_ren, dbg_tex, &src, &dst);
|
||||||
|
}
|
||||||
|
cc++;
|
||||||
|
dst.x += 8;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,12 +1,17 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#define WINDOW_CAPTION "demo_pelotas2"
|
constexpr char WINDOW_CAPTION[] = "demo5_sprites_bouncing";
|
||||||
#define SCREEN_WIDTH 320
|
|
||||||
#define SCREEN_HEIGHT 240
|
|
||||||
#define BALL_SIZE 8
|
|
||||||
#define GRAVITY 0.2f
|
|
||||||
|
|
||||||
struct color_t
|
constexpr int SCREEN_WIDTH = 320;
|
||||||
|
constexpr int SCREEN_HEIGHT = 240;
|
||||||
|
constexpr int WINDOW_SIZE = 3;
|
||||||
|
constexpr int BALL_SIZE = 8;
|
||||||
|
constexpr float GRAVITY_FORCE = 0.2f;
|
||||||
|
|
||||||
|
constexpr Uint64 DEMO_SPEED = 1000 / 60;
|
||||||
|
constexpr Uint64 TEXT_DURATION = 2000;
|
||||||
|
|
||||||
|
struct Color
|
||||||
{
|
{
|
||||||
int r, g, b;
|
int r, g, b;
|
||||||
};
|
};
|
||||||
283
source/main.cpp
283
source/main.cpp
@@ -1,237 +1,266 @@
|
|||||||
#include <SDL2/SDL.h>
|
#include <SDL3/SDL_error.h> // for SDL_GetError
|
||||||
#include "texture.h"
|
#include <SDL3/SDL_events.h> // for SDL_EventType, SDL_PollEvent, SDL_Event
|
||||||
#include "ball.h"
|
#include <SDL3/SDL_init.h> // for SDL_Init, SDL_Quit, SDL_INIT_VIDEO
|
||||||
#include "defines.h"
|
#include <SDL3/SDL_keycode.h> // for SDLK_1, SDLK_2, SDLK_3, SDLK_4, SDLK_5
|
||||||
#include <iostream>
|
#include <SDL3/SDL_render.h> // for SDL_SetRenderDrawColor, SDL_CreateRend...
|
||||||
#include <vector>
|
#include <SDL3/SDL_stdinc.h> // for Uint64
|
||||||
|
#include <SDL3/SDL_timer.h> // for SDL_GetTicks
|
||||||
|
#include <SDL3/SDL_video.h> // for SDL_CreateWindow, SDL_DestroyWindow
|
||||||
|
#include <array> // for array
|
||||||
|
#include <cstdlib> // for rand, srand
|
||||||
|
#include <ctime> // for time
|
||||||
|
#include <iostream> // for basic_ostream, char_traits, operator<<
|
||||||
|
#include <memory> // for unique_ptr, shared_ptr, make_shared
|
||||||
|
#include <string> // for operator+, string, to_string
|
||||||
|
#include <vector> // for vector
|
||||||
|
#include "ball.h" // for Ball
|
||||||
|
#include "dbgtxt.h" // for dbg_init, dbg_print
|
||||||
|
#include "defines.h" // for SCREEN_WIDTH, SCREEN_HEIGHT, WINDOW_SIZE
|
||||||
|
#include "texture.h" // for Texture
|
||||||
|
|
||||||
SDL_Window *window = NULL;
|
// Variables globales
|
||||||
SDL_Renderer *renderer = NULL;
|
SDL_Window *window = nullptr;
|
||||||
SDL_Event *event;
|
SDL_Renderer *renderer = nullptr;
|
||||||
Texture *texture = nullptr;
|
std::shared_ptr<Texture> texture = nullptr;
|
||||||
std::vector<Ball *> balls;
|
std::vector<std::unique_ptr<Ball>> balls;
|
||||||
int test[8] = {1, 10, 100, 500, 1000, 10000, 50000, 100000};
|
std::array<int, 8> test = {1, 10, 100, 500, 1000, 10000, 50000, 100000};
|
||||||
|
|
||||||
bool shouldExit = false;
|
bool should_exit = false; // Controla si la aplicación debe cerrarse
|
||||||
Uint32 ticks = 0;
|
Uint64 ticks = 0; // Tiempo en milisegundos para controlar la actualización
|
||||||
|
int scenario = 0; // Escenario actual basado en el número de bolas
|
||||||
|
std::string text; // Texto a mostrar en pantalla
|
||||||
|
int text_pos = 0; // Posición del texto en la pantalla
|
||||||
|
bool show_text = true; // Determina si el texto se debe mostrar
|
||||||
|
Uint64 text_init_time = 0; // Temporizador para mostrar el texto
|
||||||
|
|
||||||
void deleteBalls();
|
// Establece el texto en pantalla mostrando el número de bolas actuales
|
||||||
|
void setText()
|
||||||
|
{
|
||||||
|
const std::string TEXT_NUMBER = test[scenario] == 1 ? " PELOTA" : " PELOTAS";
|
||||||
|
text = std::to_string(test[scenario]) + TEXT_NUMBER;
|
||||||
|
const int TEXT_SIZE = static_cast<int>(text.size() * 8);
|
||||||
|
text_pos = SCREEN_WIDTH / 2 - TEXT_SIZE / 2;
|
||||||
|
text_init_time = SDL_GetTicks();
|
||||||
|
show_text = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Inicializa las bolas según el escenario seleccionado
|
||||||
void initBalls(int value)
|
void initBalls(int value)
|
||||||
{
|
{
|
||||||
deleteBalls();
|
balls.clear();
|
||||||
for (int i = 0; i < test[value]; ++i)
|
for (int i = 0; i < test.at(value); ++i)
|
||||||
{
|
{
|
||||||
const int sign = ((rand() % 2) * 2) - 1;
|
const int SIGN = ((rand() % 2) * 2) - 1; // Genera un signo aleatorio (+ o -)
|
||||||
;
|
const float X = (rand() % (SCREEN_WIDTH / 2)) + (SCREEN_WIDTH / 4); // Posición inicial en X
|
||||||
const float x = (rand() % (SCREEN_WIDTH / 2)) + (SCREEN_WIDTH / 4);
|
const float VX = (((rand() % 20) + 10) * 0.1f) * SIGN; // Velocidad en X
|
||||||
const float vx = (((rand() % 20) + 10) * 0.1f) * sign;
|
const float VY = ((rand() % 60) - 30) * 0.1f; // Velocidad en Y
|
||||||
const float vy = ((rand() % 60) - 30) * 0.1f;
|
const Color COLOR = {(rand() % 192) + 32, (rand() % 192) + 32, (rand() % 192) + 32}; // Color aleatorio
|
||||||
const color_t color = {(rand() % 192) + 32, (rand() % 192) + 32, (rand() % 192) + 32};
|
balls.emplace_back(std::make_unique<Ball>(X, VX, VY, COLOR, texture));
|
||||||
Ball *b = new Ball(x, vx, vy, color, texture);
|
|
||||||
balls.push_back(b);
|
|
||||||
}
|
}
|
||||||
|
setText(); // Actualiza el texto
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Aumenta la velocidad vertical de las bolas "hacia arriba"
|
||||||
void pushUpBalls()
|
void pushUpBalls()
|
||||||
{
|
{
|
||||||
for (auto ball : balls)
|
for (auto &ball : balls)
|
||||||
{
|
{
|
||||||
const int sign = ((rand() % 2) * 2) - 1;
|
const int SIGNO = ((rand() % 2) * 2) - 1;
|
||||||
const float vx = (((rand() % 20) + 10) * 0.1f) * sign;
|
const float VX = (((rand() % 20) + 10) * 0.1f) * SIGNO;
|
||||||
const float vy = ((rand() % 40) * 0.1f) + 5;
|
const float VY = ((rand() % 40) * 0.1f) + 5;
|
||||||
ball->modVel(vx, -vy);
|
ball->modVel(VX, -VY); // Modifica la velocidad de la bola
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void deleteBalls()
|
// Cambia la gravedad de todas las bolas
|
||||||
|
void switchBallsGravity()
|
||||||
{
|
{
|
||||||
for (auto ball : balls)
|
for (auto &ball : balls)
|
||||||
{
|
{
|
||||||
if (ball)
|
ball->switchGravity();
|
||||||
{
|
|
||||||
delete ball;
|
|
||||||
ball = nullptr;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
balls.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
|
// Inicializa SDL y configura los componentes principales
|
||||||
bool init()
|
bool init()
|
||||||
{
|
{
|
||||||
// Initialization flag
|
|
||||||
bool success = true;
|
bool success = true;
|
||||||
|
|
||||||
// Initialize SDL
|
// Inicializa SDL
|
||||||
if (SDL_Init(SDL_INIT_VIDEO) < 0)
|
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
|
||||||
{
|
{
|
||||||
// Set texture filtering to linear
|
// Crear ventana principal
|
||||||
if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1"))
|
window = SDL_CreateWindow(WINDOW_CAPTION, SCREEN_WIDTH * WINDOW_SIZE, SCREEN_HEIGHT * WINDOW_SIZE, SDL_WINDOW_OPENGL);
|
||||||
|
if (window == nullptr)
|
||||||
{
|
{
|
||||||
printf("Warning: Linear texture filtering not enabled!");
|
std::cout << "¡No se pudo crear la ventana! Error de SDL: " << SDL_GetError() << std::endl;
|
||||||
}
|
|
||||||
|
|
||||||
// Create window
|
|
||||||
window = SDL_CreateWindow(WINDOW_CAPTION, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH * 2, SCREEN_HEIGHT * 2, SDL_WINDOW_SHOWN);
|
|
||||||
if (window == NULL)
|
|
||||||
{
|
|
||||||
printf("Window could not be created! SDL Error: %s\n", SDL_GetError());
|
|
||||||
success = false;
|
success = false;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
// Create renderer for window
|
// Crear renderizador
|
||||||
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
|
renderer = SDL_CreateRenderer(window, nullptr);
|
||||||
if (renderer == NULL)
|
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
|
// Establecer color inicial del renderizador
|
||||||
SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
|
SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
|
||||||
|
|
||||||
// Establece el tamaño del renderizador
|
// Establecer tamaño lógico para el renderizado
|
||||||
SDL_RenderSetLogicalSize(renderer, SCREEN_WIDTH, SCREEN_HEIGHT);
|
SDL_SetRenderLogicalPresentation(renderer, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_LOGICAL_PRESENTATION_INTEGER_SCALE);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
event = new SDL_Event();
|
// Inicializar otros componentes
|
||||||
|
texture = std::make_shared<Texture>(renderer, "resources/ball.png");
|
||||||
texture = new Texture(renderer, "resources/pelota.png");
|
|
||||||
ticks = SDL_GetTicks();
|
ticks = SDL_GetTicks();
|
||||||
srand(time(NULL));
|
srand(static_cast<unsigned>(time(nullptr)));
|
||||||
initBalls(2);
|
dbg_init(renderer);
|
||||||
|
initBalls(scenario);
|
||||||
|
|
||||||
return success;
|
return success;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Limpia todos los recursos y cierra SDL
|
||||||
void close()
|
void close()
|
||||||
{
|
{
|
||||||
// Destroy window
|
|
||||||
SDL_DestroyRenderer(renderer);
|
SDL_DestroyRenderer(renderer);
|
||||||
SDL_DestroyWindow(window);
|
SDL_DestroyWindow(window);
|
||||||
window = nullptr;
|
|
||||||
renderer = nullptr;
|
|
||||||
|
|
||||||
if (event)
|
|
||||||
{
|
|
||||||
delete event;
|
|
||||||
event = nullptr;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (texture)
|
|
||||||
{
|
|
||||||
delete texture;
|
|
||||||
texture = nullptr;
|
|
||||||
}
|
|
||||||
|
|
||||||
deleteBalls();
|
|
||||||
|
|
||||||
// Quit SDL subsystems
|
|
||||||
SDL_Quit();
|
SDL_Quit();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Verifica los eventos en la cola
|
||||||
void checkEvents()
|
void checkEvents()
|
||||||
{
|
{
|
||||||
// Comprueba los eventos que hay en la cola
|
SDL_Event event;
|
||||||
while (SDL_PollEvent(event) != 0)
|
while (SDL_PollEvent(&event) != 0)
|
||||||
{
|
{
|
||||||
// Evento de salida de la aplicación
|
// Evento de salida
|
||||||
if (event->type == SDL_QUIT)
|
if (event.type == SDL_EVENT_QUIT)
|
||||||
{
|
{
|
||||||
shouldExit = true;
|
should_exit = true;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (event->type == SDL_KEYDOWN && event->key.repeat == 0)
|
// Procesar eventos de teclado
|
||||||
|
if (event.type == SDL_EVENT_KEY_DOWN && event.key.repeat == 0)
|
||||||
{
|
{
|
||||||
if (event->key.keysym.sym == SDLK_SPACE)
|
switch (event.key.key)
|
||||||
{
|
{
|
||||||
|
case SDLK_ESCAPE:
|
||||||
|
should_exit = true;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case SDLK_SPACE:
|
||||||
pushUpBalls();
|
pushUpBalls();
|
||||||
}
|
break;
|
||||||
|
|
||||||
if (event->key.keysym.sym == SDLK_1)
|
case SDLK_G:
|
||||||
{
|
switchBallsGravity();
|
||||||
initBalls(0);
|
break;
|
||||||
}
|
|
||||||
|
|
||||||
if (event->key.keysym.sym == SDLK_2)
|
case SDLK_1:
|
||||||
{
|
scenario = 0;
|
||||||
initBalls(1);
|
initBalls(scenario);
|
||||||
}
|
break;
|
||||||
|
|
||||||
if (event->key.keysym.sym == SDLK_3)
|
case SDLK_2:
|
||||||
{
|
scenario = 1;
|
||||||
initBalls(2);
|
initBalls(scenario);
|
||||||
}
|
break;
|
||||||
|
|
||||||
if (event->key.keysym.sym == SDLK_4)
|
case SDLK_3:
|
||||||
{
|
scenario = 2;
|
||||||
initBalls(3);
|
initBalls(scenario);
|
||||||
}
|
break;
|
||||||
|
|
||||||
if (event->key.keysym.sym == SDLK_5)
|
case SDLK_4:
|
||||||
{
|
scenario = 3;
|
||||||
initBalls(4);
|
initBalls(scenario);
|
||||||
}
|
break;
|
||||||
|
|
||||||
if (event->key.keysym.sym == SDLK_6)
|
case SDLK_5:
|
||||||
{
|
scenario = 4;
|
||||||
initBalls(5);
|
initBalls(scenario);
|
||||||
}
|
break;
|
||||||
|
|
||||||
if (event->key.keysym.sym == SDLK_7)
|
case SDLK_6:
|
||||||
{
|
scenario = 5;
|
||||||
initBalls(6);
|
initBalls(scenario);
|
||||||
}
|
break;
|
||||||
|
|
||||||
if (event->key.keysym.sym == SDLK_8)
|
case SDLK_7:
|
||||||
{
|
scenario = 6;
|
||||||
initBalls(7);
|
initBalls(scenario);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case SDLK_8:
|
||||||
|
scenario = 7;
|
||||||
|
initBalls(scenario);
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Actualiza la lógica del juego
|
||||||
void update()
|
void update()
|
||||||
{
|
{
|
||||||
if (SDL_GetTicks() - ticks > 15)
|
if (SDL_GetTicks() - ticks > DEMO_SPEED)
|
||||||
{
|
{
|
||||||
ticks = SDL_GetTicks();
|
ticks = SDL_GetTicks();
|
||||||
|
|
||||||
for (auto ball : balls)
|
for (auto &ball : balls)
|
||||||
{
|
{
|
||||||
ball->update();
|
ball->update();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (show_text)
|
||||||
|
{
|
||||||
|
show_text = !(SDL_GetTicks() - text_init_time > TEXT_DURATION);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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);
|
||||||
|
|
||||||
for (auto ball : balls)
|
for (auto &ball : balls)
|
||||||
{
|
{
|
||||||
ball->render();
|
ball->render();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (show_text)
|
||||||
|
{
|
||||||
|
dbg_print(text_pos, 8, text.c_str(), 255, 255, 255);
|
||||||
|
}
|
||||||
|
|
||||||
SDL_RenderPresent(renderer);
|
SDL_RenderPresent(renderer);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Función principal
|
||||||
int main(int argc, char *args[])
|
int main(int argc, char *args[])
|
||||||
{
|
{
|
||||||
init();
|
if (!init())
|
||||||
|
{
|
||||||
|
std::cout << "Ocurrió un error durante la inicialización." << std::endl;
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
while (!shouldExit)
|
while (!should_exit)
|
||||||
{
|
{
|
||||||
update();
|
update();
|
||||||
checkEvents();
|
checkEvents();
|
||||||
|
|||||||
@@ -1,52 +1,40 @@
|
|||||||
#include "sprite.h"
|
#include "sprite.h"
|
||||||
|
#include "texture.h" // for Texture
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Sprite::Sprite(Texture *texture)
|
Sprite::Sprite(std::shared_ptr<Texture> texture)
|
||||||
{
|
: texture_(texture),
|
||||||
this->texture = texture;
|
pos_{0.0f, 0.0f, 0.0f, 0.0f},
|
||||||
pos = {0, 0, 0, 0};
|
clip_{0.0f, 0.0f, 0.0f, 0.0f} {}
|
||||||
clip = {0, 0, 0, 0};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Destructor
|
|
||||||
Sprite::~Sprite()
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
// Establece la posición del sprite
|
// Establece la posición del sprite
|
||||||
void Sprite::setPos(SDL_Point pos)
|
void Sprite::setPos(SDL_FPoint pos)
|
||||||
{
|
{
|
||||||
this->pos.x = pos.x;
|
pos_.x = pos.x;
|
||||||
this->pos.y = pos.y;
|
pos_.y = pos.y;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pinta el sprite
|
// Pinta el sprite
|
||||||
void Sprite::render()
|
void Sprite::render()
|
||||||
{
|
{
|
||||||
texture->render(&clip, &pos);
|
texture_->render(&clip_, &pos_);
|
||||||
}
|
|
||||||
|
|
||||||
// Actualiza la lógica de la clase
|
|
||||||
void Sprite::update()
|
|
||||||
{
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Establece el rectangulo de la textura que se va a pintar
|
// Establece el rectangulo de la textura que se va a pintar
|
||||||
void Sprite::setClip(SDL_Rect clip)
|
void Sprite::setClip(SDL_FRect clip)
|
||||||
{
|
{
|
||||||
this->clip = clip;
|
clip_ = clip;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Establece el tamaño del sprite
|
// Establece el tamaño del sprite
|
||||||
void Sprite::setSize(int w, int h)
|
void Sprite::setSize(float w, float h)
|
||||||
{
|
{
|
||||||
this->pos.w = w;
|
pos_.w = w;
|
||||||
this->pos.h = h;
|
pos_.h = h;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Modulación de color
|
// Modulación de color
|
||||||
void Sprite::setColor(int r, int g, int b)
|
void Sprite::setColor(int r, int g, int b)
|
||||||
{
|
{
|
||||||
texture->setColor(r, g, b);
|
texture_->setColor(r, g, b);
|
||||||
}
|
}
|
||||||
@@ -1,36 +1,34 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <SDL2/SDL.h>
|
#include <SDL3/SDL_rect.h> // for SDL_FRect, SDL_FPoint
|
||||||
#include "texture.h"
|
#include <memory> // for shared_ptr
|
||||||
|
class Texture;
|
||||||
|
|
||||||
class Sprite
|
class Sprite
|
||||||
{
|
{
|
||||||
private:
|
private:
|
||||||
Texture *texture; // Textura con los gráficos del sprite
|
std::shared_ptr<Texture> texture_; // Textura con los gráficos del sprite
|
||||||
SDL_Rect pos; // Posición y tamaño del sprite
|
SDL_FRect pos_; // Posición y tamaño del sprite
|
||||||
SDL_Rect clip; // Parte de la textura que se va a dibujar
|
SDL_FRect clip_; // Parte de la textura que se va a dibujar
|
||||||
|
|
||||||
public:
|
public:
|
||||||
// Constructor
|
// Constructor
|
||||||
Sprite(Texture *texture);
|
explicit Sprite(std::shared_ptr<Texture> texture);
|
||||||
|
|
||||||
// Destructor
|
// Destructor
|
||||||
~Sprite();
|
~Sprite() = default;
|
||||||
|
|
||||||
// Establece la posición del sprite
|
// Establece la posición del sprite
|
||||||
void setPos(SDL_Point pos);
|
void setPos(SDL_FPoint pos);
|
||||||
|
|
||||||
// Pinta el sprite
|
// Pinta el sprite
|
||||||
void render();
|
void render();
|
||||||
|
|
||||||
// Actualiza la lógica de la clase
|
|
||||||
void update();
|
|
||||||
|
|
||||||
// Establece el rectangulo de la textura que se va a pintar
|
// Establece el rectangulo de la textura que se va a pintar
|
||||||
void setClip(SDL_Rect clip);
|
void setClip(SDL_FRect clip);
|
||||||
|
|
||||||
// Establece el tamaño del sprite
|
// Establece el tamaño del sprite
|
||||||
void setSize(int w, int h);
|
void setSize(float w, float h);
|
||||||
|
|
||||||
// Modulación de color
|
// Modulación de color
|
||||||
void setColor(int r, int g, int b);
|
void setColor(int r, int g, int b);
|
||||||
|
|||||||
@@ -1,24 +1,22 @@
|
|||||||
#include <stdio.h>
|
|
||||||
#include <string>
|
|
||||||
#define STB_IMAGE_IMPLEMENTATION
|
#define STB_IMAGE_IMPLEMENTATION
|
||||||
#include "stb_image.h"
|
|
||||||
#include "texture.h"
|
#include "texture.h"
|
||||||
|
#include <SDL3/SDL_error.h> // Para SDL_GetError
|
||||||
|
#include <SDL3/SDL_log.h> // Para SDL_Log
|
||||||
|
#include <SDL3/SDL_pixels.h> // Para SDL_PixelFormat
|
||||||
|
#include <SDL3/SDL_surface.h> // Para SDL_CreateSurfaceFrom, SDL_DestroySurface
|
||||||
|
#include <stdio.h> // Para NULL
|
||||||
|
#include <stdlib.h> // Para exit
|
||||||
|
#include <iostream> // Para basic_ostream, char_traits, operator<<
|
||||||
|
#include <string> // Para operator<<, string
|
||||||
|
#include "stb_image.h" // Para stbi_failure_reason, stbi_image_free
|
||||||
|
|
||||||
Texture::Texture(SDL_Renderer *renderer)
|
Texture::Texture(SDL_Renderer *renderer)
|
||||||
{
|
: renderer_(renderer), texture_(nullptr), width_(0), height_(0) {}
|
||||||
this->renderer = renderer;
|
|
||||||
texture = nullptr;
|
|
||||||
width = 0;
|
|
||||||
height = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
Texture::Texture(SDL_Renderer *renderer, std::string filepath)
|
Texture::Texture(SDL_Renderer *renderer, const std::string &file_path)
|
||||||
|
: renderer_(renderer), texture_(nullptr), width_(0), height_(0)
|
||||||
{
|
{
|
||||||
this->renderer = renderer;
|
loadFromFile(file_path);
|
||||||
texture = nullptr;
|
|
||||||
width = 0;
|
|
||||||
height = 0;
|
|
||||||
loadFromFile(filepath);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Texture::~Texture()
|
Texture::~Texture()
|
||||||
@@ -26,104 +24,105 @@ Texture::~Texture()
|
|||||||
free();
|
free();
|
||||||
}
|
}
|
||||||
|
|
||||||
bool Texture::loadFromFile(std::string path)
|
// Carga la imagen desde una ruta especificada
|
||||||
|
bool Texture::loadFromFile(const std::string &file_path)
|
||||||
{
|
{
|
||||||
const std::string filename = path.substr(path.find_last_of("\\/") + 1);
|
const std::string filename = file_path.substr(file_path.find_last_of("\\/") + 1);
|
||||||
int req_format = STBI_rgb_alpha;
|
int req_format = STBI_rgb_alpha;
|
||||||
int width, height, orig_format;
|
int width, height, orig_format;
|
||||||
unsigned char *data = stbi_load(path.c_str(), &width, &height, &orig_format, req_format);
|
unsigned char *data = stbi_load(file_path.c_str(), &width, &height, &orig_format, req_format);
|
||||||
if (data == nullptr)
|
if (data == nullptr)
|
||||||
{
|
{
|
||||||
SDL_Log("Loading image failed: %s", stbi_failure_reason());
|
SDL_Log("Error al cargar la imagen: %s", stbi_failure_reason());
|
||||||
exit(1);
|
exit(1);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
std::cout << "Image loaded: " << filename.c_str() << std::endl;
|
std::cout << "Imagen cargada: " << filename.c_str() << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
int depth, pitch;
|
int pitch;
|
||||||
Uint32 pixel_format;
|
SDL_PixelFormat pixel_format;
|
||||||
if (req_format == STBI_rgb)
|
if (req_format == STBI_rgb)
|
||||||
{
|
{
|
||||||
depth = 24;
|
pitch = 3 * width; // 3 bytes por pixel * pixels por línea
|
||||||
pitch = 3 * width; // 3 bytes por pixel * pixels por linea
|
|
||||||
pixel_format = SDL_PIXELFORMAT_RGB24;
|
pixel_format = SDL_PIXELFORMAT_RGB24;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{ // STBI_rgb_alpha (RGBA)
|
{ // STBI_rgb_alpha (RGBA)
|
||||||
depth = 32;
|
|
||||||
pitch = 4 * width;
|
pitch = 4 * width;
|
||||||
pixel_format = SDL_PIXELFORMAT_RGBA32;
|
pixel_format = SDL_PIXELFORMAT_RGBA32;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Limpia
|
// Libera la memoria previa
|
||||||
free();
|
free();
|
||||||
|
|
||||||
// La textura final
|
// La textura final
|
||||||
SDL_Texture *newTexture = nullptr;
|
SDL_Texture *new_texture = nullptr;
|
||||||
|
|
||||||
// Carga la imagen desde una ruta específica
|
// Crea la superficie de la imagen desde los datos cargados
|
||||||
SDL_Surface *loadedSurface = SDL_CreateRGBSurfaceWithFormatFrom((void *)data, width, height, depth, pitch, pixel_format);
|
SDL_Surface *loaded_surface = SDL_CreateSurfaceFrom(width, height, pixel_format, (void *)data, pitch);
|
||||||
if (loadedSurface == nullptr)
|
if (loaded_surface == nullptr)
|
||||||
{
|
{
|
||||||
std::cout << "Unable to load image " << path.c_str() << std::endl;
|
std::cout << "No se pudo cargar la imagen " << file_path << std::endl;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
// Crea la textura desde los pixels de la surface
|
// Crea la textura desde los píxeles de la superficie
|
||||||
newTexture = SDL_CreateTextureFromSurface(renderer, loadedSurface);
|
new_texture = SDL_CreateTextureFromSurface(renderer_, loaded_surface);
|
||||||
if (newTexture == nullptr)
|
if (new_texture == nullptr)
|
||||||
{
|
{
|
||||||
std::cout << "Unable to create texture from " << path.c_str() << "! SDL Error: " << SDL_GetError() << std::endl;
|
std::cout << "No se pudo crear la textura desde " << file_path << "! Error de SDL: " << SDL_GetError() << std::endl;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
// Obtiene las dimensiones de la imagen
|
// Obtiene las dimensiones de la imagen
|
||||||
this->width = loadedSurface->w;
|
width_ = loaded_surface->w;
|
||||||
this->height = loadedSurface->h;
|
height_ = loaded_surface->h;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Elimina la textura cargada
|
// Destruye la superficie cargada
|
||||||
SDL_FreeSurface(loadedSurface);
|
SDL_DestroySurface(loaded_surface);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Return success
|
// Devuelve el resultado del proceso
|
||||||
stbi_image_free(data);
|
stbi_image_free(data);
|
||||||
texture = newTexture;
|
texture_ = new_texture;
|
||||||
return texture != nullptr;
|
return texture_ != nullptr;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Libera la textura si existe
|
||||||
void Texture::free()
|
void Texture::free()
|
||||||
{
|
{
|
||||||
// Free texture if it exists
|
if (texture_ != nullptr)
|
||||||
if (texture != nullptr)
|
|
||||||
{
|
{
|
||||||
SDL_DestroyTexture(texture);
|
SDL_DestroyTexture(texture_);
|
||||||
texture = nullptr;
|
texture_ = nullptr;
|
||||||
width = 0;
|
width_ = 0;
|
||||||
height = 0;
|
height_ = 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void Texture::render(SDL_Rect *src, SDL_Rect *dst)
|
// Renderiza la textura en pantalla
|
||||||
|
void Texture::render(SDL_FRect *src, SDL_FRect *dst)
|
||||||
{
|
{
|
||||||
// Render to screen
|
SDL_RenderTexture(renderer_, texture_, src, dst);
|
||||||
SDL_RenderCopy(renderer, texture, src, dst);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Obtiene el ancho de la imagen
|
||||||
int Texture::getWidth()
|
int Texture::getWidth()
|
||||||
{
|
{
|
||||||
return width;
|
return width_;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Obtiene la altura de la imagen
|
||||||
int Texture::getHeight()
|
int Texture::getHeight()
|
||||||
{
|
{
|
||||||
return height;
|
return height_;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Modulación de color
|
// Modula el color de la textura
|
||||||
void Texture::setColor(int r, int g, int b)
|
void Texture::setColor(int r, int g, int b)
|
||||||
{
|
{
|
||||||
SDL_SetTextureColorMod(texture, r, g, b);
|
SDL_SetTextureColorMod(texture_, r, g, b);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,40 +1,40 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <SDL2/SDL.h>
|
#include <SDL3/SDL_rect.h> // Para SDL_FRect
|
||||||
#include <iostream>
|
#include <SDL3/SDL_render.h> // Para SDL_Renderer, SDL_Texture
|
||||||
|
#include <string> // Para std::string
|
||||||
|
|
||||||
// Texture wrapper class
|
|
||||||
class Texture
|
class Texture
|
||||||
{
|
{
|
||||||
private:
|
private:
|
||||||
SDL_Renderer *renderer;
|
SDL_Renderer *renderer_;
|
||||||
SDL_Texture *texture;
|
SDL_Texture *texture_;
|
||||||
|
|
||||||
// Image dimensions
|
// Dimensiones de la imagen
|
||||||
int width;
|
int width_;
|
||||||
int height;
|
int height_;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
// Initializes variables
|
// Inicializa las variables
|
||||||
Texture(SDL_Renderer *renderer);
|
explicit Texture(SDL_Renderer *renderer);
|
||||||
Texture(SDL_Renderer *renderer, std::string filepath);
|
Texture(SDL_Renderer *renderer, const std::string &file_path);
|
||||||
|
|
||||||
// Deallocates memory
|
// Libera la memoria
|
||||||
~Texture();
|
~Texture();
|
||||||
|
|
||||||
// Loads image at specified path
|
// Carga una imagen desde la ruta especificada
|
||||||
bool loadFromFile(std::string path);
|
bool loadFromFile(const std::string &path);
|
||||||
|
|
||||||
// Deallocates texture
|
// Libera la textura
|
||||||
void free();
|
void free();
|
||||||
|
|
||||||
// Renders texture at given point
|
// Renderiza la textura en el punto especificado
|
||||||
void render(SDL_Rect *src = nullptr, SDL_Rect *dst = nullptr);
|
void render(SDL_FRect *src = nullptr, SDL_FRect *dst = nullptr);
|
||||||
|
|
||||||
// Gets image dimensions
|
// Obtiene las dimensiones de la imagen
|
||||||
int getWidth();
|
int getWidth();
|
||||||
int getHeight();
|
int getHeight();
|
||||||
|
|
||||||
// Modulación de color
|
// Modula el color de la textura
|
||||||
void setColor(int r, int g, int b);
|
void setColor(int r, int g, int b);
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user