Implementar sistema de gravedad direccional con controles de cursor
- Añadir enum GravityDirection (UP/DOWN/LEFT/RIGHT) en defines.h - Modificar Ball class para soportar gravedad multi-direccional - Reescribir Ball::update() con lógica direccional completa - Cambiar on_floor_ por on_surface_ (más genérico) - Implementar detección de superficie según dirección de gravedad - Añadir controles de teclado con teclas de cursor - Actualizar debug display para mostrar dirección actual - Aplicar fricción correctamente según superficie activa Controles nuevos: - ↑/↓/←/→: Cambiar dirección de gravedad - H: Toggle debug display (incluye nueva info de gravedad) 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
21
.clang-format
Normal file
21
.clang-format
Normal file
@@ -0,0 +1,21 @@
|
||||
BasedOnStyle: Google
|
||||
IndentWidth: 4
|
||||
IndentAccessModifiers: true
|
||||
ColumnLimit: 0 # Sin límite de longitud de línea
|
||||
BreakBeforeBraces: Attach # Llaves en la misma línea
|
||||
AllowShortIfStatementsOnASingleLine: true
|
||||
AllowShortBlocksOnASingleLine: true
|
||||
AllowShortFunctionsOnASingleLine: All
|
||||
AlignOperands: DontAlign
|
||||
AlignAfterOpenBracket: DontAlign
|
||||
BinPackArguments: false
|
||||
BinPackParameters: false
|
||||
ContinuationIndentWidth: 4
|
||||
ConstructorInitializerIndentWidth: 4
|
||||
IndentWrappedFunctionNames: false
|
||||
Cpp11BracedListStyle: true
|
||||
BreakConstructorInitializers: BeforeColon
|
||||
AllowAllConstructorInitializersOnNextLine: false
|
||||
PackConstructorInitializers: Never
|
||||
AllowAllArgumentsOnNextLine: false
|
||||
AllowAllParametersOfDeclarationOnNextLine: false
|
||||
83
.clang-tidy
Normal file
83
.clang-tidy
Normal file
@@ -0,0 +1,83 @@
|
||||
Checks: >
|
||||
readability-*,
|
||||
modernize-*,
|
||||
performance-*,
|
||||
bugprone-unchecked-optional-access,
|
||||
bugprone-sizeof-expression,
|
||||
bugprone-suspicious-missing-comma,
|
||||
bugprone-suspicious-index,
|
||||
bugprone-undefined-memory-manipulation,
|
||||
bugprone-use-after-move,
|
||||
bugprone-out-of-bound-access,
|
||||
-readability-identifier-length,
|
||||
-readability-magic-numbers,
|
||||
-bugprone-narrowing-conversions,
|
||||
-performance-enum-size,
|
||||
-performance-inefficient-string-concatenation,
|
||||
-bugprone-integer-division,
|
||||
-bugprone-easily-swappable-parameters,
|
||||
|
||||
WarningsAsErrors: '*'
|
||||
# Solo incluir archivos de tu código fuente
|
||||
HeaderFilterRegex: '^source/(sections|ui)/.*'
|
||||
FormatStyle: file
|
||||
|
||||
CheckOptions:
|
||||
# Variables locales en snake_case
|
||||
- { key: readability-identifier-naming.VariableCase, value: lower_case }
|
||||
|
||||
# Miembros privados en snake_case con sufijo _
|
||||
- { key: readability-identifier-naming.PrivateMemberCase, value: lower_case }
|
||||
- { key: readability-identifier-naming.PrivateMemberSuffix, value: _ }
|
||||
|
||||
# Miembros protegidos en snake_case con sufijo _
|
||||
- { key: readability-identifier-naming.ProtectedMemberCase, value: lower_case }
|
||||
- { key: readability-identifier-naming.ProtectedMemberSuffix, value: _ }
|
||||
|
||||
# Miembros públicos en snake_case (sin sufijo)
|
||||
- { key: readability-identifier-naming.PublicMemberCase, value: lower_case }
|
||||
|
||||
# Namespaces en CamelCase
|
||||
- { key: readability-identifier-naming.NamespaceCase, value: CamelCase }
|
||||
|
||||
# Variables estáticas privadas como miembros privados
|
||||
- { key: readability-identifier-naming.StaticVariableCase, value: lower_case }
|
||||
- { key: readability-identifier-naming.StaticVariableSuffix, value: _ }
|
||||
|
||||
# Constantes estáticas sin sufijo
|
||||
- { key: readability-identifier-naming.StaticConstantCase, value: UPPER_CASE }
|
||||
|
||||
# Constantes globales en UPPER_CASE
|
||||
- { key: readability-identifier-naming.GlobalConstantCase, value: UPPER_CASE }
|
||||
|
||||
# Variables constexpr globales en UPPER_CASE
|
||||
- { key: readability-identifier-naming.ConstexprVariableCase, value: UPPER_CASE }
|
||||
|
||||
# Constantes locales en UPPER_CASE
|
||||
- { key: readability-identifier-naming.LocalConstantCase, value: UPPER_CASE }
|
||||
|
||||
# Constexpr miembros en UPPER_CASE (sin sufijo)
|
||||
- { key: readability-identifier-naming.ConstexprMemberCase, value: UPPER_CASE }
|
||||
|
||||
# Constexpr miembros privados/protegidos con sufijo _
|
||||
- { key: readability-identifier-naming.ConstexprMethodCase, value: UPPER_CASE }
|
||||
|
||||
# Clases, structs y enums en CamelCase
|
||||
- { key: readability-identifier-naming.ClassCase, value: CamelCase }
|
||||
- { key: readability-identifier-naming.StructCase, value: CamelCase }
|
||||
- { key: readability-identifier-naming.EnumCase, value: CamelCase }
|
||||
|
||||
# Valores de enums en UPPER_CASE
|
||||
- { key: readability-identifier-naming.EnumConstantCase, value: UPPER_CASE }
|
||||
|
||||
# Métodos en camelBack (sin sufijos)
|
||||
- { key: readability-identifier-naming.MethodCase, value: camelBack }
|
||||
- { key: readability-identifier-naming.PrivateMethodCase, value: camelBack }
|
||||
- { key: readability-identifier-naming.ProtectedMethodCase, value: camelBack }
|
||||
- { key: readability-identifier-naming.PublicMethodCase, value: camelBack }
|
||||
|
||||
# Funciones en camelBack
|
||||
- { key: readability-identifier-naming.FunctionCase, value: camelBack }
|
||||
|
||||
# Parámetros en lower_case
|
||||
- { key: readability-identifier-naming.ParameterCase, value: lower_case }
|
||||
97
.gitignore
vendored
Normal file
97
.gitignore
vendored
Normal file
@@ -0,0 +1,97 @@
|
||||
# Archivos ejecutables
|
||||
*.exe
|
||||
*.out
|
||||
*.app
|
||||
vibe3_physics
|
||||
vibe3_physics.exe
|
||||
|
||||
# Archivos objeto y bibliotecas
|
||||
*.o
|
||||
*.obj
|
||||
*.a
|
||||
*.lib
|
||||
*.so
|
||||
*.dylib
|
||||
*.dll
|
||||
|
||||
# Archivos de compilación y enlazado
|
||||
*.d
|
||||
*.dep
|
||||
*.gch
|
||||
*.pch
|
||||
|
||||
# Directorios de compilación
|
||||
build/
|
||||
Build/
|
||||
BUILD/
|
||||
cmake-build-*/
|
||||
.cmake/
|
||||
|
||||
# Archivos generados por CMake
|
||||
CMakeFiles/
|
||||
CMakeCache.txt
|
||||
cmake_install.cmake
|
||||
Makefile
|
||||
*.cmake
|
||||
!CMakeLists.txt
|
||||
|
||||
# Archivos de Visual Studio
|
||||
.vs/
|
||||
*.vcxproj
|
||||
*.vcxproj.filters
|
||||
*.vcxproj.user
|
||||
*.sln
|
||||
*.suo
|
||||
*.user
|
||||
*.userosscache
|
||||
*.sln.docstates
|
||||
|
||||
# Archivos de Code::Blocks
|
||||
*.cbp
|
||||
*.layout
|
||||
*.depend
|
||||
|
||||
# Archivos de Qt
|
||||
*.pro.user
|
||||
*.pro.user.*
|
||||
moc_*.cpp
|
||||
moc_*.h
|
||||
qrc_*.cpp
|
||||
ui_*.h
|
||||
*.qm
|
||||
.qmake.stash
|
||||
|
||||
# Archivos de depuración
|
||||
*.pdb
|
||||
*.ilk
|
||||
*.map
|
||||
*.exp
|
||||
|
||||
# Archivos temporales del sistema
|
||||
.DS_Store
|
||||
.DS_Store?
|
||||
._*
|
||||
.Spotlight-V100
|
||||
.Trashes
|
||||
ehthumbs.db
|
||||
Thumbs.db
|
||||
*~
|
||||
|
||||
# Archivos de IDEs
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
|
||||
# Archivos de logs
|
||||
*.log
|
||||
|
||||
# Archivos de backup
|
||||
*.bak
|
||||
*.backup
|
||||
*.tmp
|
||||
*.temp
|
||||
|
||||
# Claude Code
|
||||
.claude/
|
||||
76
CLAUDE.md
Normal file
76
CLAUDE.md
Normal file
@@ -0,0 +1,76 @@
|
||||
# Claude Code Session - ViBe1 Delta
|
||||
|
||||
## Estado del Proyecto
|
||||
|
||||
**Proyecto:** ViBe1 Delta - Simulador de sprites con fisica
|
||||
**Objetivo:** Implementar delta time para separar bucle de proceso del de renderizado
|
||||
|
||||
## Progreso Actual
|
||||
|
||||
### ✅ Completado
|
||||
|
||||
1. **Configuracion inicial**
|
||||
- Reestructurar codigo: movido utilidades a `source/external/`
|
||||
- Filtro nearest neighbor para texturas pixel-perfect
|
||||
- Compilacion funcionando (Make y CMake)
|
||||
|
||||
2. **Sistema de metricas**
|
||||
- Contador FPS en esquina superior derecha (amarillo)
|
||||
- Control V-Sync con tecla "V" (ON/OFF)
|
||||
- Display V-Sync en esquina superior izquierda (cian)
|
||||
|
||||
3. **Mejoras visuales**
|
||||
- Tamaño pelota: 8x8 → 10x10 pixels
|
||||
- Fondo aclarado: (32,32,32) → (64,64,64)
|
||||
- Textura pelota redibujada con mejor calidad
|
||||
|
||||
### 🚧 En Proceso
|
||||
|
||||
- **Proximos pasos:** Implementar sistema delta time
|
||||
- **Problema detectado:** Caracteres extraños en README.md (encoding)
|
||||
|
||||
### 📋 Controles Actuales
|
||||
|
||||
| Tecla | Accion |
|
||||
|-------|---------|
|
||||
| V | Alternar V-Sync ON/OFF |
|
||||
| 1-8 | Cambiar numero de pelotas (1 a 100,000) |
|
||||
| ESPACIO | Impulsar pelotas hacia arriba |
|
||||
| G | Alternar direccion gravedad |
|
||||
| ESC | Salir |
|
||||
|
||||
## Arquitectura Actual
|
||||
|
||||
```
|
||||
source/
|
||||
├── main.cpp # Bucle principal + FPS/V-Sync
|
||||
├── ball.h/.cpp # Logica fisica pelotas
|
||||
├── defines.h # Constantes (BALL_SIZE=10)
|
||||
└── external/ # Utilidades externas
|
||||
├── texture.h/.cpp # Gestion texturas + nearest filter
|
||||
├── sprite.h/.cpp # Sistema sprites
|
||||
├── dbgtxt.h # Debug text + nearest filter
|
||||
└── stb_image.h # Carga imagenes
|
||||
```
|
||||
|
||||
## Bucket Actual: FPS Acoplado
|
||||
|
||||
El sistema usa bucle acoplado a 60 FPS:
|
||||
```cpp
|
||||
if (SDL_GetTicks() - ticks > DEMO_SPEED) { // 16.67ms
|
||||
// Solo aqui se actualiza fisica
|
||||
}
|
||||
```
|
||||
|
||||
**Problema:** Fisica dependiente del framerate → Inconsistencia cross-platform
|
||||
|
||||
## Delta Time - Plan de Implementacion
|
||||
|
||||
1. **Sistema timing independiente**
|
||||
2. **Bucle desacoplado** logica vs renderizado
|
||||
3. **Interpolacion** para renderizado suave
|
||||
4. **Optimizaciones** rendimiento
|
||||
|
||||
---
|
||||
|
||||
*Archivo de seguimiento para sesiones Claude Code*
|
||||
49
CMakeLists.txt
Normal file
49
CMakeLists.txt
Normal file
@@ -0,0 +1,49 @@
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
project(vibe3_physics)
|
||||
|
||||
# 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 source/external/*.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})
|
||||
358
README.md
Normal file
358
README.md
Normal file
@@ -0,0 +1,358 @@
|
||||
# ViBe3 Physics - Simulador de Sprites con Fisica
|
||||
|
||||
**ViBe3 Physics** es una demo experimental de **vibe-coding** que implementa **nuevas fisicas** expandiendo sobre el sistema de delta time. Utiliza **SDL3** para mostrar sprites (pelotas) rebotando con fisica avanzada independiente del framerate.
|
||||
|
||||
El nombre refleja su proposito: **ViBe** (vibe-coding experimental) + **Physics** (nuevas fisicas experimentales). La demo sirve como sandbox para probar bucles de juego con timing independiente y renderizado optimizado.
|
||||
|
||||
## 🎯 Caracteristicas Actuales
|
||||
|
||||
- **Simulacion de fisica**: Gravedad, rebotes y colisiones con perdida de energia
|
||||
- **Multiples escenarios**: 8 configuraciones predefinidas (1 a 100,000 pelotas)
|
||||
- **Sistema de temas visuales**: 4 temas de colores con fondos degradados y paletas tematicas
|
||||
- **Interactividad**: Controles de teclado para modificar el comportamiento
|
||||
- **Renderizado batch optimizado**: Sistema de batch rendering con SDL_RenderGeometry para 50K+ sprites
|
||||
- **Colores tematicos**: Paletas de 8 colores por tema aplicadas proceduralmente
|
||||
- **Monitor de rendimiento**: Contador FPS en tiempo real
|
||||
- **Control V-Sync**: Activacion/desactivacion dinamica del V-Sync
|
||||
|
||||
## 🎮 Controles
|
||||
|
||||
| Tecla | Accion |
|
||||
|-------|--------|
|
||||
| `H` | **Alternar debug display (FPS, V-Sync, valores fisica)** |
|
||||
| `V` | **Alternar V-Sync ON/OFF** |
|
||||
| `F1-F4` | **Seleccion directa de tema de colores (Atardecer/Oceano/Neon/Bosque)** |
|
||||
| `T` | **Ciclar entre temas de colores** |
|
||||
| `1-8` | Cambiar numero de pelotas (1, 10, 100, 500, 1K, 10K, 50K, 100K) |
|
||||
| `ESPACIO` | Impulsar todas las pelotas hacia arriba |
|
||||
| `G` | Alternar direccion de la gravedad |
|
||||
| `ESC` | Salir del programa |
|
||||
|
||||
## 📊 Informacion en Pantalla
|
||||
|
||||
- **Centro**: Numero de pelotas activas en **blanco** (temporal)
|
||||
- **Centro**: Nombre del tema activo en **color tematico** (temporal, debajo del contador)
|
||||
|
||||
### Debug Display (Tecla `H`)
|
||||
|
||||
Cuando se activa el debug display con la tecla `H`:
|
||||
|
||||
- **Esquina superior izquierda**: Estado V-Sync (VSYNC ON/OFF) en **cian**
|
||||
- **Esquina superior derecha**: Contador FPS en tiempo real en **amarillo**
|
||||
- **Lineas 3-5**: Valores fisica primera pelota (GRAV, VY, FLOOR) en **magenta**
|
||||
- **Linea 6**: Tema activo (THEME SUNSET/OCEAN/NEON/FOREST) en **amarillo claro**
|
||||
|
||||
## 🎨 Sistema de Temas de Colores
|
||||
|
||||
**ViBe1 Delta** incluye 4 temas visuales que transforman completamente la apariencia del simulador:
|
||||
|
||||
### Temas Disponibles
|
||||
|
||||
| Tecla | Tema | Descripcion | Fondo | Paleta de Pelotas |
|
||||
|-------|------|-------------|-------|-------------------|
|
||||
| `F1` | **ATARDECER** | Colores calidos de puesta de sol | Degradado naranja-rojo | Tonos naranjas, rojos y amarillos |
|
||||
| `F2` | **OCEANO** | Ambiente marino refrescante | Degradado azul-cian | Azules, cianes y verdes agua |
|
||||
| `F3` | **NEON** | Colores vibrantes futuristas | Degradado magenta-cian | Magentas, cianes y rosas brillantes |
|
||||
| `F4` | **BOSQUE** | Naturaleza verde relajante | Degradado verde oscuro-claro | Verdes naturales y tierra |
|
||||
|
||||
### Controles de Temas
|
||||
|
||||
- **Seleccion directa**: Usa `F1`, `F2`, `F3` o `F4` para cambiar inmediatamente al tema deseado
|
||||
- **Ciclado secuencial**: Presiona `T` para avanzar al siguiente tema en orden
|
||||
- **Indicador visual**: El nombre del tema aparece temporalmente en el centro de la pantalla con colores tematicos
|
||||
- **Regeneracion automatica**: Las pelotas adoptan automaticamente la nueva paleta de colores al cambiar tema
|
||||
|
||||
### Detalles Tecnicos
|
||||
|
||||
- **Fondos degradados**: Implementados con `SDL_RenderGeometry` usando vertices con colores interpolados
|
||||
- **Paletas tematicas**: 8 colores unicos por tema aplicados aleatoriamente a las pelotas
|
||||
- **Rendimiento optimizado**: El cambio de tema solo regenera los colores, manteniendo la fisica
|
||||
- **Compatibilidad completa**: Funciona con todos los escenarios (1 a 100,000 pelotas)
|
||||
|
||||
## 🏗️ Estructura del Proyecto
|
||||
|
||||
```
|
||||
vibe3_physics/
|
||||
├── source/
|
||||
│ ├── main.cpp # Bucle principal y logica del juego
|
||||
│ ├── ball.h/cpp # Clase Ball - logica de las pelotas
|
||||
│ ├── defines.h # Constantes y configuracion
|
||||
│ └── external/ # Utilidades y bibliotecas externas
|
||||
│ ├── sprite.h/cpp # Clase Sprite - renderizado de texturas
|
||||
│ ├── texture.h/cpp # Clase Texture - gestion de imagenes
|
||||
│ ├── dbgtxt.h # Sistema de debug para texto en pantalla
|
||||
│ └── stb_image.h # Biblioteca para cargar imagenes
|
||||
├── data/
|
||||
│ └── ball.png # Textura de la pelota (10x10 pixeles)
|
||||
├── CMakeLists.txt # Configuracion de CMake
|
||||
├── Makefile # Configuracion de Make
|
||||
├── CLAUDE.md # Seguimiento de desarrollo
|
||||
└── .gitignore # Archivos ignorados por Git
|
||||
```
|
||||
|
||||
## 🔧 Requisitos del Sistema
|
||||
|
||||
- **SDL3** (Simple DirectMedia Layer 3)
|
||||
- **C++20** compatible compiler
|
||||
- **CMake 3.20+** o **Make**
|
||||
- Plataforma: Windows, Linux, macOS
|
||||
|
||||
### Instalacion de SDL3
|
||||
|
||||
#### Windows (MinGW)
|
||||
```bash
|
||||
# Usando vcpkg o compilar desde fuente
|
||||
vcpkg install sdl3
|
||||
```
|
||||
|
||||
#### Linux
|
||||
```bash
|
||||
# Ubuntu/Debian
|
||||
sudo apt install libsdl3-dev
|
||||
# Arch Linux
|
||||
sudo pacman -S sdl3
|
||||
```
|
||||
|
||||
#### macOS
|
||||
```bash
|
||||
brew install sdl3
|
||||
```
|
||||
|
||||
## 🚀 Compilacion
|
||||
|
||||
### Opcion 1: CMake (Recomendado)
|
||||
```bash
|
||||
mkdir build && cd build
|
||||
cmake ..
|
||||
make
|
||||
```
|
||||
|
||||
### Opcion 2: Make directo
|
||||
```bash
|
||||
make
|
||||
```
|
||||
|
||||
## ▶️ Ejecucion
|
||||
|
||||
```bash
|
||||
# Desde la raiz del proyecto
|
||||
./vibe3_physics # Linux/macOS
|
||||
./vibe3_physics.exe # Windows
|
||||
```
|
||||
|
||||
## 📊 Detalles Tecnicos
|
||||
|
||||
### Configuracion Actual
|
||||
- **Resolucion**: 320x240 pixeles (escalado x3 = 960x720)
|
||||
- **Sistema de timing**: Delta time independiente del framerate
|
||||
- **Fisica**: Gravedad constante (0.2f), rebotes con perdida de energia
|
||||
- **Tamaño de pelota**: 10x10 pixeles
|
||||
- **V-Sync**: Activado por defecto, controlable dinamicamente
|
||||
|
||||
### Arquitectura del Codigo
|
||||
|
||||
1. **main.cpp**: Contiene el bucle principal con cuatro fases:
|
||||
- `calculateDeltaTime()`: Calcula tiempo transcurrido entre frames
|
||||
- `update()`: Actualiza la logica del juego usando delta time + calculo FPS
|
||||
- `checkEvents()`: Procesa eventos de entrada
|
||||
- `render()`: Renderiza la escena + overlays informativos
|
||||
|
||||
2. **Ball**: Maneja la fisica de cada pelota individual con timing basado en delta time
|
||||
3. **Sprite**: Sistema de renderizado de texturas con filtro nearest neighbor
|
||||
4. **Texture**: Gestion de carga y renderizado de imagenes con filtro pixel-perfect
|
||||
|
||||
## ✅ Migracion a Delta Time (COMPLETADO)
|
||||
|
||||
### Sistema Anterior (Frame-Based)
|
||||
|
||||
El sistema original estaba **acoplado a 60 FPS** con logica dependiente del framerate:
|
||||
|
||||
```cpp
|
||||
// Sistema ANTIGUO en update()
|
||||
if (SDL_GetTicks() - ticks > DEMO_SPEED) { // DEMO_SPEED = 1000/60 = 16.67ms
|
||||
// Solo aqui se actualizaba la fisica cada 16.67ms
|
||||
for (auto &ball : balls) {
|
||||
ball->update(); // Sin parametros de tiempo
|
||||
}
|
||||
ticks = SDL_GetTicks();
|
||||
}
|
||||
```
|
||||
|
||||
**Problemas del sistema anterior:**
|
||||
- Velocidad inconsistente entre diferentes refresh rates (60Hz vs 75Hz vs 144Hz)
|
||||
- Logica de fisica acoplada a framerate fijo
|
||||
- V-Sync ON/OFF cambiaba la velocidad del juego
|
||||
- Rendimiento inconsistente en diferentes hardware
|
||||
|
||||
### Sistema Actual (Delta Time)
|
||||
|
||||
**Implementacion delta time** para simulacion independiente del framerate:
|
||||
|
||||
```cpp
|
||||
// Sistema NUEVO - Variables globales
|
||||
Uint64 last_frame_time = 0;
|
||||
float delta_time = 0.0f;
|
||||
|
||||
// Calculo de delta time
|
||||
void calculateDeltaTime() {
|
||||
Uint64 current_time = SDL_GetTicks();
|
||||
if (last_frame_time == 0) {
|
||||
last_frame_time = current_time;
|
||||
delta_time = 1.0f / 60.0f; // Primer frame a 60 FPS
|
||||
return;
|
||||
}
|
||||
|
||||
delta_time = (current_time - last_frame_time) / 1000.0f; // Convertir a segundos
|
||||
last_frame_time = current_time;
|
||||
|
||||
// Limitar delta time para evitar saltos grandes
|
||||
if (delta_time > 0.05f) {
|
||||
delta_time = 1.0f / 60.0f; // Fallback a 60 FPS
|
||||
}
|
||||
}
|
||||
|
||||
// Bucle principal actualizado
|
||||
while (!should_exit) {
|
||||
calculateDeltaTime(); // 1. Calcular tiempo transcurrido
|
||||
update(); // 2. Actualizar logica (usa delta_time)
|
||||
checkEvents(); // 3. Procesar entrada
|
||||
render(); // 4. Renderizar escena
|
||||
}
|
||||
```
|
||||
|
||||
### Conversion de Fisica: Frame-Based → Time-Based
|
||||
|
||||
#### 1. Conversion de Velocidades
|
||||
|
||||
```cpp
|
||||
// En Ball::Ball() constructor
|
||||
// ANTES: velocidades en pixeles/frame
|
||||
vx_ = vx;
|
||||
vy_ = vy;
|
||||
|
||||
// AHORA: convertir a pixeles/segundo (x60)
|
||||
vx_ = vx * 60.0f;
|
||||
vy_ = vy * 60.0f;
|
||||
```
|
||||
|
||||
#### 2. Conversion de Gravedad (Aceleracion)
|
||||
|
||||
```cpp
|
||||
// En Ball::Ball() constructor
|
||||
// ANTES: gravedad en pixeles/frame²
|
||||
gravity_force_ = GRAVITY_FORCE;
|
||||
|
||||
// AHORA: convertir a pixeles/segundo² (x60²)
|
||||
gravity_force_ = GRAVITY_FORCE * 60.0f * 60.0f; // 3600x multiplicador
|
||||
```
|
||||
|
||||
**¿Por que 60² para gravedad?**
|
||||
- Velocidad: `pixeles/frame * frame/segundo = pixeles/segundo` → **x60**
|
||||
- Aceleracion: `pixeles/frame² * frame²/segundo² = pixeles/segundo²` → **x60²**
|
||||
|
||||
#### 3. Aplicacion de Delta Time en Fisica
|
||||
|
||||
```cpp
|
||||
// En Ball::update(float deltaTime)
|
||||
// ANTES: incrementos fijos por frame
|
||||
vy_ += gravity_force_;
|
||||
pos_.x += vx_;
|
||||
pos_.y += vy_;
|
||||
|
||||
// AHORA: incrementos proporcionales al tiempo transcurrido
|
||||
vy_ += gravity_force_ * deltaTime; // Aceleracion * tiempo
|
||||
pos_.x += vx_ * deltaTime; // Velocidad * tiempo
|
||||
pos_.y += vy_ * deltaTime;
|
||||
```
|
||||
|
||||
### Valores de Debug: Antes vs Ahora
|
||||
|
||||
| Parametro | Sistema Anterior | Sistema Delta Time | Razon |
|
||||
|-----------|------------------|-------------------|-------|
|
||||
| **Velocidad X/Y** | 1.0 - 3.0 pixeles/frame | 60.0 - 180.0 pixeles/segundo | x60 conversion |
|
||||
| **Gravedad** | 0.2 pixeles/frame² | 720.0 pixeles/segundo² | x3600 conversion |
|
||||
| **Debug Display** | No disponible | GRAV: 720.000000 VY: -140.5 FLOOR: NO | Valores en tiempo real |
|
||||
|
||||
### Beneficios Conseguidos
|
||||
|
||||
- ✅ **Velocidad consistente** entre 60Hz, 75Hz, 144Hz y otros refresh rates
|
||||
- ✅ **V-Sync independiente**: misma velocidad con V-Sync ON/OFF
|
||||
- ✅ **Fisica precisa**: gravedad y movimiento calculados correctamente
|
||||
- ✅ **Escalabilidad**: preparado para futuras optimizaciones
|
||||
- ✅ **Debug en tiempo real**: monitoreo de valores de fisica
|
||||
|
||||
### Sistema de Debug Implementado
|
||||
|
||||
```cpp
|
||||
// Debug display para primera pelota
|
||||
if (!balls.empty()) {
|
||||
std::string debug_text = "GRAV: " + std::to_string(balls[0]->getGravityForce()) +
|
||||
" VY: " + std::to_string(balls[0]->getVelocityY()) +
|
||||
" FLOOR: " + (balls[0]->isOnFloor() ? "YES" : "NO");
|
||||
dbg_print(8, 24, debug_text.c_str(), 255, 0, 255); // Magenta
|
||||
}
|
||||
```
|
||||
|
||||
## 🚀 Sistema de Batch Rendering
|
||||
|
||||
### **Problema Original**
|
||||
El renderizado individual de sprites era el principal cuello de botella:
|
||||
- **50,000 bolas**: 50,000 llamadas `SDL_RenderTexture()` por frame
|
||||
- **Resultado**: ~10 FPS (inutilizable)
|
||||
|
||||
### **Solución Implementada: SDL_RenderGeometry**
|
||||
Batch rendering que agrupa todos los sprites en una sola llamada:
|
||||
|
||||
```cpp
|
||||
// Recopilar datos de todas las bolas
|
||||
for (auto &ball : balls) {
|
||||
SDL_FRect pos = ball->getPosition();
|
||||
Color color = ball->getColor();
|
||||
addSpriteToBatch(pos.x, pos.y, pos.w, pos.h, color.r, color.g, color.b);
|
||||
}
|
||||
|
||||
// Renderizar TODAS las bolas en una sola llamada
|
||||
SDL_RenderGeometry(renderer, texture->getSDLTexture(),
|
||||
batch_vertices.data(), batch_vertices.size(),
|
||||
batch_indices.data(), batch_indices.size());
|
||||
```
|
||||
|
||||
### **Arquitectura del Batch**
|
||||
1. **Vértices**: 4 vértices por sprite (quad) con posición, UV y color
|
||||
2. **Índices**: 6 índices por sprite (2 triángulos)
|
||||
3. **Acumulación**: Todos los sprites se acumulan en vectores globales
|
||||
4. **Renderizado**: Una sola llamada `SDL_RenderGeometry` por frame
|
||||
|
||||
### **Rendimiento Conseguido**
|
||||
- **50,000 bolas**: >75 FPS constante (mejora de 750%)
|
||||
- **100,000 bolas**: Fluido y jugable
|
||||
- **Escalabilidad**: Preparado para renderizado masivo de sprites
|
||||
|
||||
## 🛠️ Desarrollo
|
||||
|
||||
Para contribuir al proyecto:
|
||||
|
||||
1. Fork del repositorio
|
||||
2. Crear rama de feature (`git checkout -b feature/nueva-caracteristica`)
|
||||
3. Commit de cambios (`git commit -am 'Añadir nueva caracteristica'`)
|
||||
4. Push a la rama (`git push origin feature/nueva-caracteristica`)
|
||||
5. Crear Pull Request
|
||||
|
||||
## 📝 Notas Tecnicas
|
||||
|
||||
- El proyecto usa **smart pointers** (unique_ptr, shared_ptr) para gestion de memoria
|
||||
- **RAII** para recursos SDL
|
||||
- **Separacion de responsabilidades** entre clases
|
||||
- **Configuracion multiplataforma** (Windows, Linux, macOS)
|
||||
- **Filtro nearest neighbor** para texturas pixel-perfect
|
||||
- **Sistema de metricas** en tiempo real (FPS, V-Sync)
|
||||
|
||||
## 🐛 Problemas Conocidos
|
||||
|
||||
- FPS drops significativos con >10,000 pelotas
|
||||
- Timing dependiente del framerate (solucion en desarrollo)
|
||||
- Sin interpolacion en el renderizado
|
||||
|
||||
---
|
||||
|
||||
*Proyecto desarrollado como base para experimentacion con game loops y fisica en tiempo real usando SDL3.*
|
||||
BIN
data/ball.png
Normal file
BIN
data/ball.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 162 B |
200
source/ball.cpp
Normal file
200
source/ball.cpp
Normal file
@@ -0,0 +1,200 @@
|
||||
#include "ball.h"
|
||||
|
||||
#include <stdlib.h> // for rand
|
||||
|
||||
#include <cmath> // for fabs
|
||||
|
||||
#include "defines.h" // for BALL_SIZE, Color, SCREEN_HEIGHT, GRAVITY_FORCE
|
||||
class Texture;
|
||||
|
||||
// Constructor
|
||||
Ball::Ball(float x, float vx, float vy, Color color, std::shared_ptr<Texture> texture, GravityDirection gravity_dir)
|
||||
: sprite_(std::make_unique<Sprite>(texture)),
|
||||
pos_({x, 0.0f, BALL_SIZE, BALL_SIZE}) {
|
||||
// Convertir velocidades de píxeles/frame a píxeles/segundo (multiplicar por 60)
|
||||
vx_ = vx * 60.0f;
|
||||
vy_ = vy * 60.0f;
|
||||
sprite_->setPos({pos_.x, pos_.y});
|
||||
sprite_->setSize(BALL_SIZE, BALL_SIZE);
|
||||
sprite_->setClip({0, 0, BALL_SIZE, BALL_SIZE});
|
||||
color_ = color;
|
||||
// Convertir gravedad de píxeles/frame² a píxeles/segundo² (multiplicar por 60²)
|
||||
gravity_force_ = GRAVITY_FORCE * 60.0f * 60.0f;
|
||||
gravity_direction_ = gravity_dir;
|
||||
on_surface_ = false;
|
||||
stopped_ = false;
|
||||
loss_ = ((rand() % 30) * 0.01f) + 0.6f;
|
||||
}
|
||||
|
||||
// Actualiza la lógica de la clase
|
||||
void Ball::update(float deltaTime) {
|
||||
if (stopped_) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Aplica la gravedad según la dirección (píxeles/segundo²)
|
||||
if (!on_surface_) {
|
||||
switch (gravity_direction_) {
|
||||
case GravityDirection::DOWN:
|
||||
vy_ += gravity_force_ * deltaTime;
|
||||
break;
|
||||
case GravityDirection::UP:
|
||||
vy_ -= gravity_force_ * deltaTime;
|
||||
break;
|
||||
case GravityDirection::LEFT:
|
||||
vx_ -= gravity_force_ * deltaTime;
|
||||
break;
|
||||
case GravityDirection::RIGHT:
|
||||
vx_ += gravity_force_ * deltaTime;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Actualiza la posición en función de la velocidad (píxeles/segundo)
|
||||
if (!on_surface_) {
|
||||
pos_.x += vx_ * deltaTime;
|
||||
pos_.y += vy_ * deltaTime;
|
||||
} else {
|
||||
// Si está en superficie, mantener posición según dirección de gravedad
|
||||
switch (gravity_direction_) {
|
||||
case GravityDirection::DOWN:
|
||||
pos_.y = SCREEN_HEIGHT - pos_.h;
|
||||
pos_.x += vx_ * deltaTime; // Seguir moviéndose en X
|
||||
break;
|
||||
case GravityDirection::UP:
|
||||
pos_.y = 0;
|
||||
pos_.x += vx_ * deltaTime; // Seguir moviéndose en X
|
||||
break;
|
||||
case GravityDirection::LEFT:
|
||||
pos_.x = 0;
|
||||
pos_.y += vy_ * deltaTime; // Seguir moviéndose en Y
|
||||
break;
|
||||
case GravityDirection::RIGHT:
|
||||
pos_.x = SCREEN_WIDTH - pos_.w;
|
||||
pos_.y += vy_ * deltaTime; // Seguir moviéndose en Y
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Comprueba las colisiones con el lateral izquierdo
|
||||
if (pos_.x < 0) {
|
||||
pos_.x = 0;
|
||||
if (gravity_direction_ == GravityDirection::LEFT) {
|
||||
// Colisión con superficie de gravedad
|
||||
vx_ = -vx_ * loss_;
|
||||
if (std::fabs(vx_) < 6.0f) {
|
||||
vx_ = 0.0f;
|
||||
on_surface_ = true;
|
||||
}
|
||||
} else {
|
||||
// Rebote normal
|
||||
vx_ = -vx_;
|
||||
}
|
||||
}
|
||||
|
||||
// Comprueba las colisiones con el lateral derecho
|
||||
if (pos_.x + pos_.w > SCREEN_WIDTH) {
|
||||
pos_.x = SCREEN_WIDTH - pos_.w;
|
||||
if (gravity_direction_ == GravityDirection::RIGHT) {
|
||||
// Colisión con superficie de gravedad
|
||||
vx_ = -vx_ * loss_;
|
||||
if (std::fabs(vx_) < 6.0f) {
|
||||
vx_ = 0.0f;
|
||||
on_surface_ = true;
|
||||
}
|
||||
} else {
|
||||
// Rebote normal
|
||||
vx_ = -vx_;
|
||||
}
|
||||
}
|
||||
|
||||
// Comprueba las colisiones con la parte superior
|
||||
if (pos_.y < 0) {
|
||||
pos_.y = 0;
|
||||
if (gravity_direction_ == GravityDirection::UP) {
|
||||
// Colisión con superficie de gravedad
|
||||
vy_ = -vy_ * loss_;
|
||||
if (std::fabs(vy_) < 6.0f) {
|
||||
vy_ = 0.0f;
|
||||
on_surface_ = true;
|
||||
}
|
||||
} else {
|
||||
// Rebote normal
|
||||
vy_ = -vy_;
|
||||
}
|
||||
}
|
||||
|
||||
// Comprueba las colisiones con la parte inferior
|
||||
if (pos_.y + pos_.h > SCREEN_HEIGHT) {
|
||||
pos_.y = SCREEN_HEIGHT - pos_.h;
|
||||
if (gravity_direction_ == GravityDirection::DOWN) {
|
||||
// Colisión con superficie de gravedad
|
||||
vy_ = -vy_ * loss_;
|
||||
if (std::fabs(vy_) < 6.0f) {
|
||||
vy_ = 0.0f;
|
||||
on_surface_ = true;
|
||||
}
|
||||
} else {
|
||||
// Rebote normal
|
||||
vy_ = -vy_;
|
||||
}
|
||||
}
|
||||
|
||||
// Aplica rozamiento al estar en superficie
|
||||
if (on_surface_) {
|
||||
// Convertir rozamiento de frame-based a time-based
|
||||
float friction_factor = pow(0.97f, 60.0f * deltaTime);
|
||||
|
||||
switch (gravity_direction_) {
|
||||
case GravityDirection::DOWN:
|
||||
case GravityDirection::UP:
|
||||
// Fricción en X cuando gravedad es vertical
|
||||
vx_ = vx_ * friction_factor;
|
||||
if (std::fabs(vx_) < 6.0f) {
|
||||
vx_ = 0.0f;
|
||||
stopped_ = true;
|
||||
}
|
||||
break;
|
||||
case GravityDirection::LEFT:
|
||||
case GravityDirection::RIGHT:
|
||||
// Fricción en Y cuando gravedad es horizontal
|
||||
vy_ = vy_ * friction_factor;
|
||||
if (std::fabs(vy_) < 6.0f) {
|
||||
vy_ = 0.0f;
|
||||
stopped_ = true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Actualiza la posición del sprite
|
||||
sprite_->setPos({pos_.x, pos_.y});
|
||||
}
|
||||
|
||||
// Pinta la clase
|
||||
void Ball::render() {
|
||||
sprite_->setColor(color_.r, color_.g, color_.b);
|
||||
sprite_->render();
|
||||
}
|
||||
|
||||
// Modifica la velocidad (convierte de frame-based a time-based)
|
||||
void Ball::modVel(float vx, float vy) {
|
||||
if (stopped_) {
|
||||
vx_ = vx_ + (vx * 60.0f); // Convertir a píxeles/segundo
|
||||
}
|
||||
vy_ = vy_ + (vy * 60.0f); // Convertir a píxeles/segundo
|
||||
on_surface_ = false;
|
||||
stopped_ = false;
|
||||
}
|
||||
|
||||
// Cambia la gravedad (usa la versión convertida)
|
||||
void Ball::switchGravity() {
|
||||
gravity_force_ = gravity_force_ == 0.0f ? (GRAVITY_FORCE * 60.0f * 60.0f) : 0.0f;
|
||||
}
|
||||
|
||||
// Cambia la dirección de gravedad
|
||||
void Ball::setGravityDirection(GravityDirection direction) {
|
||||
gravity_direction_ = direction;
|
||||
on_surface_ = false; // Ya no está en superficie al cambiar dirección
|
||||
stopped_ = false; // Reactivar movimiento
|
||||
}
|
||||
55
source/ball.h
Normal file
55
source/ball.h
Normal file
@@ -0,0 +1,55 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL_rect.h> // for SDL_FRect
|
||||
|
||||
#include <memory> // for shared_ptr, unique_ptr
|
||||
|
||||
#include "defines.h" // for Color
|
||||
#include "external/sprite.h" // for Sprite
|
||||
class Texture;
|
||||
|
||||
class Ball {
|
||||
private:
|
||||
std::unique_ptr<Sprite> sprite_; // Sprite para pintar la clase
|
||||
SDL_FRect pos_; // Posición y tamaño de la pelota
|
||||
float vx_, vy_; // Velocidad
|
||||
float gravity_force_; // Gravedad
|
||||
GravityDirection gravity_direction_; // Direcci\u00f3n de la gravedad
|
||||
Color color_; // Color de la pelota
|
||||
bool on_surface_; // Indica si la pelota est\u00e1 en la superficie (suelo/techo/pared)
|
||||
bool stopped_; // Indica si la pelota ha terminado de moverse;
|
||||
float loss_; // Coeficiente de rebote. Pérdida de energía en cada rebote
|
||||
|
||||
public:
|
||||
// Constructor
|
||||
Ball(float x, float vx, float vy, Color color, std::shared_ptr<Texture> texture, GravityDirection gravity_dir = GravityDirection::DOWN);
|
||||
|
||||
// Destructor
|
||||
~Ball() = default;
|
||||
|
||||
// Actualiza la lógica de la clase
|
||||
void update(float deltaTime);
|
||||
|
||||
// Pinta la clase
|
||||
void render();
|
||||
|
||||
// Modifica la velocidad
|
||||
void modVel(float vx, float vy);
|
||||
|
||||
// Cambia la gravedad
|
||||
void switchGravity();
|
||||
|
||||
// Cambia la direcci\u00f3n de gravedad
|
||||
void setGravityDirection(GravityDirection direction);
|
||||
|
||||
// Getters para debug
|
||||
float getVelocityY() const { return vy_; }
|
||||
float getVelocityX() const { return vx_; }
|
||||
float getGravityForce() const { return gravity_force_; }
|
||||
GravityDirection getGravityDirection() const { return gravity_direction_; }
|
||||
bool isOnSurface() const { return on_surface_; }
|
||||
|
||||
// Getters para batch rendering
|
||||
SDL_FRect getPosition() const { return pos_; }
|
||||
Color getColor() const { return color_; }
|
||||
};
|
||||
24
source/defines.h
Normal file
24
source/defines.h
Normal file
@@ -0,0 +1,24 @@
|
||||
#pragma once
|
||||
|
||||
constexpr char WINDOW_CAPTION[] = "vibe3_physics";
|
||||
|
||||
constexpr int SCREEN_WIDTH = 320;
|
||||
constexpr int SCREEN_HEIGHT = 240;
|
||||
constexpr int WINDOW_SIZE = 3;
|
||||
constexpr int BALL_SIZE = 10;
|
||||
constexpr float GRAVITY_FORCE = 0.2f;
|
||||
|
||||
// DEMO_SPEED eliminado - ya no se usa con delta time
|
||||
constexpr Uint64 TEXT_DURATION = 2000;
|
||||
|
||||
struct Color {
|
||||
int r, g, b;
|
||||
};
|
||||
|
||||
// Enum para direcci\u00f3n de gravedad
|
||||
enum class GravityDirection {
|
||||
DOWN, // \u2193 Gravedad hacia abajo (por defecto)
|
||||
UP, // \u2191 Gravedad hacia arriba
|
||||
LEFT, // \u2190 Gravedad hacia la izquierda
|
||||
RIGHT // \u2192 Gravedad hacia la derecha
|
||||
};
|
||||
78
source/external/dbgtxt.h
vendored
Normal file
78
source/external/dbgtxt.h
vendored
Normal file
@@ -0,0 +1,78 @@
|
||||
#pragma once
|
||||
|
||||
namespace {
|
||||
SDL_Texture* dbg_tex = nullptr;
|
||||
SDL_Renderer* dbg_ren = nullptr;
|
||||
} // namespace
|
||||
|
||||
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};
|
||||
|
||||
// Cargar surface del bitmap font
|
||||
SDL_Surface* font_surface = SDL_LoadBMP_IO(SDL_IOFromMem(font, 448), 1);
|
||||
if (font_surface != nullptr) {
|
||||
// Crear una nueva surface de 32 bits con canal alpha
|
||||
SDL_Surface* rgba_surface = SDL_CreateSurface(font_surface->w, font_surface->h, SDL_PIXELFORMAT_RGBA8888);
|
||||
if (rgba_surface != nullptr) {
|
||||
// Obtener píxeles de ambas surfaces
|
||||
Uint8* src_pixels = (Uint8*)font_surface->pixels;
|
||||
Uint32* dst_pixels = (Uint32*)rgba_surface->pixels;
|
||||
|
||||
int width = font_surface->w;
|
||||
int height = font_surface->h;
|
||||
|
||||
// Procesar cada píxel
|
||||
for (int y = 0; y < height; y++) {
|
||||
for (int x = 0; x < width; x++) {
|
||||
int byte_index = y * font_surface->pitch + (x / 8);
|
||||
int bit_index = 7 - (x % 8);
|
||||
|
||||
// Extraer bit del bitmap monocromo
|
||||
bool is_white = (src_pixels[byte_index] >> bit_index) & 1;
|
||||
|
||||
if (is_white) // Fondo blanco original -> transparente
|
||||
{
|
||||
dst_pixels[y * width + x] = 0x00000000; // Transparente
|
||||
} else // Texto negro original -> blanco opaco
|
||||
{
|
||||
dst_pixels[y * width + x] = 0xFFFFFFFF; // Blanco opaco
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dbg_tex = SDL_CreateTextureFromSurface(dbg_ren, rgba_surface);
|
||||
SDL_DestroySurface(rgba_surface);
|
||||
}
|
||||
SDL_DestroySurface(font_surface);
|
||||
}
|
||||
|
||||
// Configurar filtro nearest neighbor para píxel perfect del texto
|
||||
if (dbg_tex != nullptr) {
|
||||
SDL_SetTextureScaleMode(dbg_tex, SDL_SCALEMODE_NEAREST);
|
||||
// Configurar blend mode para transparencia normal
|
||||
SDL_SetTextureBlendMode(dbg_tex, SDL_BLENDMODE_BLEND);
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
36
source/external/sprite.cpp
vendored
Normal file
36
source/external/sprite.cpp
vendored
Normal file
@@ -0,0 +1,36 @@
|
||||
#include "sprite.h"
|
||||
|
||||
#include "texture.h" // for Texture
|
||||
|
||||
// Constructor
|
||||
Sprite::Sprite(std::shared_ptr<Texture> texture)
|
||||
: texture_(texture),
|
||||
pos_{0.0f, 0.0f, 0.0f, 0.0f},
|
||||
clip_{0.0f, 0.0f, 0.0f, 0.0f} {}
|
||||
|
||||
// Establece la posición del sprite
|
||||
void Sprite::setPos(SDL_FPoint pos) {
|
||||
pos_.x = pos.x;
|
||||
pos_.y = pos.y;
|
||||
}
|
||||
|
||||
// Pinta el sprite
|
||||
void Sprite::render() {
|
||||
texture_->render(&clip_, &pos_);
|
||||
}
|
||||
|
||||
// Establece el rectangulo de la textura que se va a pintar
|
||||
void Sprite::setClip(SDL_FRect clip) {
|
||||
clip_ = clip;
|
||||
}
|
||||
|
||||
// Establece el tamaño del sprite
|
||||
void Sprite::setSize(float w, float h) {
|
||||
pos_.w = w;
|
||||
pos_.h = h;
|
||||
}
|
||||
|
||||
// Modulación de color
|
||||
void Sprite::setColor(int r, int g, int b) {
|
||||
texture_->setColor(r, g, b);
|
||||
}
|
||||
35
source/external/sprite.h
vendored
Normal file
35
source/external/sprite.h
vendored
Normal file
@@ -0,0 +1,35 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL_rect.h> // for SDL_FRect, SDL_FPoint
|
||||
|
||||
#include <memory> // for shared_ptr
|
||||
class Texture;
|
||||
|
||||
class Sprite {
|
||||
private:
|
||||
std::shared_ptr<Texture> texture_; // Textura con los gráficos del sprite
|
||||
SDL_FRect pos_; // Posición y tamaño del sprite
|
||||
SDL_FRect clip_; // Parte de la textura que se va a dibujar
|
||||
|
||||
public:
|
||||
// Constructor
|
||||
explicit Sprite(std::shared_ptr<Texture> texture);
|
||||
|
||||
// Destructor
|
||||
~Sprite() = default;
|
||||
|
||||
// Establece la posición del sprite
|
||||
void setPos(SDL_FPoint pos);
|
||||
|
||||
// Pinta el sprite
|
||||
void render();
|
||||
|
||||
// Establece el rectangulo de la textura que se va a pintar
|
||||
void setClip(SDL_FRect clip);
|
||||
|
||||
// Establece el tamaño del sprite
|
||||
void setSize(float w, float h);
|
||||
|
||||
// Modulación de color
|
||||
void setColor(int r, int g, int b);
|
||||
};
|
||||
7897
source/external/stb_image.h
vendored
Normal file
7897
source/external/stb_image.h
vendored
Normal file
File diff suppressed because it is too large
Load Diff
119
source/external/texture.cpp
vendored
Normal file
119
source/external/texture.cpp
vendored
Normal file
@@ -0,0 +1,119 @@
|
||||
#define STB_IMAGE_IMPLEMENTATION
|
||||
#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)
|
||||
: renderer_(renderer),
|
||||
texture_(nullptr),
|
||||
width_(0),
|
||||
height_(0) {}
|
||||
|
||||
Texture::Texture(SDL_Renderer *renderer, const std::string &file_path)
|
||||
: renderer_(renderer),
|
||||
texture_(nullptr),
|
||||
width_(0),
|
||||
height_(0) {
|
||||
loadFromFile(file_path);
|
||||
}
|
||||
|
||||
Texture::~Texture() {
|
||||
free();
|
||||
}
|
||||
|
||||
// Carga la imagen desde una ruta especificada
|
||||
bool Texture::loadFromFile(const std::string &file_path) {
|
||||
const std::string filename = file_path.substr(file_path.find_last_of("\\/") + 1);
|
||||
int req_format = STBI_rgb_alpha;
|
||||
int width, height, orig_format;
|
||||
unsigned char *data = stbi_load(file_path.c_str(), &width, &height, &orig_format, req_format);
|
||||
if (data == nullptr) {
|
||||
SDL_Log("Error al cargar la imagen: %s", stbi_failure_reason());
|
||||
exit(1);
|
||||
} else {
|
||||
std::cout << "Imagen cargada: " << filename.c_str() << std::endl;
|
||||
}
|
||||
|
||||
int pitch;
|
||||
SDL_PixelFormat pixel_format;
|
||||
if (req_format == STBI_rgb) {
|
||||
pitch = 3 * width; // 3 bytes por pixel * pixels por línea
|
||||
pixel_format = SDL_PIXELFORMAT_RGB24;
|
||||
} else { // STBI_rgb_alpha (RGBA)
|
||||
pitch = 4 * width;
|
||||
pixel_format = SDL_PIXELFORMAT_RGBA32;
|
||||
}
|
||||
|
||||
// Libera la memoria previa
|
||||
free();
|
||||
|
||||
// La textura final
|
||||
SDL_Texture *new_texture = nullptr;
|
||||
|
||||
// Crea la superficie de la imagen desde los datos cargados
|
||||
SDL_Surface *loaded_surface = SDL_CreateSurfaceFrom(width, height, pixel_format, (void *)data, pitch);
|
||||
if (loaded_surface == nullptr) {
|
||||
std::cout << "No se pudo cargar la imagen " << file_path << std::endl;
|
||||
} else {
|
||||
// Crea la textura desde los píxeles de la superficie
|
||||
new_texture = SDL_CreateTextureFromSurface(renderer_, loaded_surface);
|
||||
if (new_texture == nullptr) {
|
||||
std::cout << "No se pudo crear la textura desde " << file_path << "! Error de SDL: " << SDL_GetError() << std::endl;
|
||||
} else {
|
||||
// Obtiene las dimensiones de la imagen
|
||||
width_ = loaded_surface->w;
|
||||
height_ = loaded_surface->h;
|
||||
|
||||
// Configurar filtro nearest neighbor para píxel perfect
|
||||
SDL_SetTextureScaleMode(new_texture, SDL_SCALEMODE_NEAREST);
|
||||
}
|
||||
|
||||
// Destruye la superficie cargada
|
||||
SDL_DestroySurface(loaded_surface);
|
||||
}
|
||||
|
||||
// Devuelve el resultado del proceso
|
||||
stbi_image_free(data);
|
||||
texture_ = new_texture;
|
||||
return texture_ != nullptr;
|
||||
}
|
||||
|
||||
// Libera la textura si existe
|
||||
void Texture::free() {
|
||||
if (texture_ != nullptr) {
|
||||
SDL_DestroyTexture(texture_);
|
||||
texture_ = nullptr;
|
||||
width_ = 0;
|
||||
height_ = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Renderiza la textura en pantalla
|
||||
void Texture::render(SDL_FRect *src, SDL_FRect *dst) {
|
||||
SDL_RenderTexture(renderer_, texture_, src, dst);
|
||||
}
|
||||
|
||||
// Obtiene el ancho de la imagen
|
||||
int Texture::getWidth() {
|
||||
return width_;
|
||||
}
|
||||
|
||||
// Obtiene la altura de la imagen
|
||||
int Texture::getHeight() {
|
||||
return height_;
|
||||
}
|
||||
|
||||
// Modula el color de la textura
|
||||
void Texture::setColor(int r, int g, int b) {
|
||||
SDL_SetTextureColorMod(texture_, r, g, b);
|
||||
}
|
||||
43
source/external/texture.h
vendored
Normal file
43
source/external/texture.h
vendored
Normal file
@@ -0,0 +1,43 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL_rect.h> // Para SDL_FRect
|
||||
#include <SDL3/SDL_render.h> // Para SDL_Renderer, SDL_Texture
|
||||
|
||||
#include <string> // Para std::string
|
||||
|
||||
class Texture {
|
||||
private:
|
||||
SDL_Renderer *renderer_;
|
||||
SDL_Texture *texture_;
|
||||
|
||||
// Dimensiones de la imagen
|
||||
int width_;
|
||||
int height_;
|
||||
|
||||
public:
|
||||
// Inicializa las variables
|
||||
explicit Texture(SDL_Renderer *renderer);
|
||||
Texture(SDL_Renderer *renderer, const std::string &file_path);
|
||||
|
||||
// Libera la memoria
|
||||
~Texture();
|
||||
|
||||
// Carga una imagen desde la ruta especificada
|
||||
bool loadFromFile(const std::string &path);
|
||||
|
||||
// Libera la textura
|
||||
void free();
|
||||
|
||||
// Renderiza la textura en el punto especificado
|
||||
void render(SDL_FRect *src = nullptr, SDL_FRect *dst = nullptr);
|
||||
|
||||
// Obtiene las dimensiones de la imagen
|
||||
int getWidth();
|
||||
int getHeight();
|
||||
|
||||
// Modula el color de la textura
|
||||
void setColor(int r, int g, int b);
|
||||
|
||||
// Getter para batch rendering
|
||||
SDL_Texture *getSDLTexture() const { return texture_; }
|
||||
};
|
||||
596
source/main.cpp
Normal file
596
source/main.cpp
Normal file
@@ -0,0 +1,596 @@
|
||||
#include <SDL3/SDL_error.h> // for SDL_GetError
|
||||
#include <SDL3/SDL_events.h> // for SDL_EventType, SDL_PollEvent, SDL_Event
|
||||
#include <SDL3/SDL_init.h> // for SDL_Init, SDL_Quit, SDL_INIT_VIDEO
|
||||
#include <SDL3/SDL_keycode.h> // for SDLK_1, SDLK_2, SDLK_3, SDLK_4, SDLK_5
|
||||
#include <SDL3/SDL_render.h> // for SDL_SetRenderDrawColor, SDL_CreateRend...
|
||||
#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 "defines.h" // for SCREEN_WIDTH, SCREEN_HEIGHT, WINDOW_SIZE
|
||||
#include "external/dbgtxt.h" // for dbg_init, dbg_print
|
||||
#include "external/texture.h" // for Texture
|
||||
|
||||
// Variables globales
|
||||
SDL_Window *window = nullptr;
|
||||
SDL_Renderer *renderer = nullptr;
|
||||
std::shared_ptr<Texture> texture = nullptr;
|
||||
std::vector<std::unique_ptr<Ball>> balls;
|
||||
std::array<int, 8> test = {1, 10, 100, 500, 1000, 10000, 50000, 100000};
|
||||
|
||||
bool should_exit = false; // Controla si la aplicación debe cerrarse
|
||||
// ticks eliminado - reemplazado por delta time system
|
||||
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
|
||||
|
||||
// Variables para contador de FPS
|
||||
Uint64 fps_last_time = 0; // Último tiempo para cálculo de FPS
|
||||
int fps_frame_count = 0; // Contador de frames
|
||||
int fps_current = 0; // FPS actuales calculados
|
||||
std::string fps_text = "FPS: 0"; // Texto del contador de FPS
|
||||
|
||||
// Variables para V-Sync
|
||||
bool vsync_enabled = true; // Estado inicial del V-Sync (activado por defecto)
|
||||
std::string vsync_text = "VSYNC ON"; // Texto del estado V-Sync
|
||||
|
||||
// Variables para Delta Time
|
||||
Uint64 last_frame_time = 0; // Tiempo del último frame en milisegundos
|
||||
float delta_time = 0.0f; // Tiempo transcurrido desde el último frame en segundos
|
||||
|
||||
// Variables para Debug Display
|
||||
bool show_debug = false; // Debug display desactivado por defecto
|
||||
|
||||
// Variable para direcci\u00f3n de gravedad
|
||||
GravityDirection current_gravity = GravityDirection::DOWN; // Gravedad inicial hacia abajo
|
||||
|
||||
// Sistema de temas de colores
|
||||
enum class ColorTheme {
|
||||
SUNSET = 0,
|
||||
OCEAN = 1,
|
||||
NEON = 2,
|
||||
FOREST = 3
|
||||
};
|
||||
|
||||
ColorTheme current_theme = ColorTheme::SUNSET;
|
||||
std::string theme_names[] = {"SUNSET", "OCEAN", "NEON", "FOREST"};
|
||||
|
||||
struct ThemeColors {
|
||||
// Colores de fondo (superior -> inferior)
|
||||
float bg_top_r, bg_top_g, bg_top_b;
|
||||
float bg_bottom_r, bg_bottom_g, bg_bottom_b;
|
||||
|
||||
// Paletas de colores para bolas (RGB 0-255)
|
||||
int ball_colors[8][3]; // 8 colores por tema
|
||||
};
|
||||
|
||||
ThemeColors themes[4] = {
|
||||
// SUNSET: Naranjas, rojos, amarillos, rosas
|
||||
{180.0f / 255.0f, 140.0f / 255.0f, 100.0f / 255.0f, // Fondo superior (naranja suave)
|
||||
40.0f / 255.0f,
|
||||
20.0f / 255.0f,
|
||||
60.0f / 255.0f, // Fondo inferior (púrpura oscuro)
|
||||
{{255, 140, 0}, {255, 69, 0}, {255, 215, 0}, {255, 20, 147}, {255, 99, 71}, {255, 165, 0}, {255, 192, 203}, {220, 20, 60}}},
|
||||
// OCEAN: Azules, cianes, verdes agua, blancos
|
||||
{100.0f / 255.0f, 150.0f / 255.0f, 200.0f / 255.0f, // Fondo superior (azul cielo)
|
||||
20.0f / 255.0f,
|
||||
40.0f / 255.0f,
|
||||
80.0f / 255.0f, // Fondo inferior (azul marino)
|
||||
{{0, 191, 255}, {0, 255, 255}, {32, 178, 170}, {176, 224, 230}, {70, 130, 180}, {0, 206, 209}, {240, 248, 255}, {64, 224, 208}}},
|
||||
// NEON: Cian, magenta, verde lima, amarillo vibrante
|
||||
{20.0f / 255.0f, 20.0f / 255.0f, 40.0f / 255.0f, // Fondo superior (negro azulado)
|
||||
0.0f / 255.0f,
|
||||
0.0f / 255.0f,
|
||||
0.0f / 255.0f, // Fondo inferior (negro)
|
||||
{{0, 255, 255}, {255, 0, 255}, {50, 205, 50}, {255, 255, 0}, {255, 20, 147}, {0, 255, 127}, {138, 43, 226}, {255, 69, 0}}},
|
||||
// FOREST: Verdes, marrones, amarillos otoño
|
||||
{144.0f / 255.0f, 238.0f / 255.0f, 144.0f / 255.0f, // Fondo superior (verde claro)
|
||||
101.0f / 255.0f,
|
||||
67.0f / 255.0f,
|
||||
33.0f / 255.0f, // Fondo inferior (marrón tierra)
|
||||
{{34, 139, 34}, {107, 142, 35}, {154, 205, 50}, {255, 215, 0}, {210, 180, 140}, {160, 82, 45}, {218, 165, 32}, {50, 205, 50}}}};
|
||||
|
||||
// Variables para Batch Rendering
|
||||
std::vector<SDL_Vertex> batch_vertices;
|
||||
std::vector<int> batch_indices;
|
||||
|
||||
// Función para renderizar fondo degradado
|
||||
void renderGradientBackground() {
|
||||
// Crear quad de pantalla completa con degradado
|
||||
SDL_Vertex bg_vertices[4];
|
||||
|
||||
// Obtener colores del tema actual
|
||||
ThemeColors &theme = themes[static_cast<int>(current_theme)];
|
||||
|
||||
float top_r = theme.bg_top_r;
|
||||
float top_g = theme.bg_top_g;
|
||||
float top_b = theme.bg_top_b;
|
||||
|
||||
float bottom_r = theme.bg_bottom_r;
|
||||
float bottom_g = theme.bg_bottom_g;
|
||||
float bottom_b = theme.bg_bottom_b;
|
||||
|
||||
// Vértice superior izquierdo
|
||||
bg_vertices[0].position = {0, 0};
|
||||
bg_vertices[0].tex_coord = {0.0f, 0.0f};
|
||||
bg_vertices[0].color = {top_r, top_g, top_b, 1.0f};
|
||||
|
||||
// Vértice superior derecho
|
||||
bg_vertices[1].position = {SCREEN_WIDTH, 0};
|
||||
bg_vertices[1].tex_coord = {1.0f, 0.0f};
|
||||
bg_vertices[1].color = {top_r, top_g, top_b, 1.0f};
|
||||
|
||||
// Vértice inferior derecho
|
||||
bg_vertices[2].position = {SCREEN_WIDTH, SCREEN_HEIGHT};
|
||||
bg_vertices[2].tex_coord = {1.0f, 1.0f};
|
||||
bg_vertices[2].color = {bottom_r, bottom_g, bottom_b, 1.0f};
|
||||
|
||||
// Vértice inferior izquierdo
|
||||
bg_vertices[3].position = {0, SCREEN_HEIGHT};
|
||||
bg_vertices[3].tex_coord = {0.0f, 1.0f};
|
||||
bg_vertices[3].color = {bottom_r, bottom_g, bottom_b, 1.0f};
|
||||
|
||||
// Índices para 2 triángulos
|
||||
int bg_indices[6] = {0, 1, 2, 2, 3, 0};
|
||||
|
||||
// Renderizar sin textura (nullptr)
|
||||
SDL_RenderGeometry(renderer, nullptr, bg_vertices, 4, bg_indices, 6);
|
||||
}
|
||||
|
||||
// Función para añadir un sprite al batch
|
||||
void addSpriteToBatch(float x, float y, float w, float h, Uint8 r, Uint8 g, Uint8 b) {
|
||||
int vertex_index = static_cast<int>(batch_vertices.size());
|
||||
|
||||
// Crear 4 vértices para el quad (2 triángulos)
|
||||
SDL_Vertex vertices[4];
|
||||
|
||||
// Convertir colores de Uint8 (0-255) a float (0.0-1.0)
|
||||
float rf = r / 255.0f;
|
||||
float gf = g / 255.0f;
|
||||
float bf = b / 255.0f;
|
||||
|
||||
// Vértice superior izquierdo
|
||||
vertices[0].position = {x, y};
|
||||
vertices[0].tex_coord = {0.0f, 0.0f};
|
||||
vertices[0].color = {rf, gf, bf, 1.0f};
|
||||
|
||||
// Vértice superior derecho
|
||||
vertices[1].position = {x + w, y};
|
||||
vertices[1].tex_coord = {1.0f, 0.0f};
|
||||
vertices[1].color = {rf, gf, bf, 1.0f};
|
||||
|
||||
// Vértice inferior derecho
|
||||
vertices[2].position = {x + w, y + h};
|
||||
vertices[2].tex_coord = {1.0f, 1.0f};
|
||||
vertices[2].color = {rf, gf, bf, 1.0f};
|
||||
|
||||
// Vértice inferior izquierdo
|
||||
vertices[3].position = {x, y + h};
|
||||
vertices[3].tex_coord = {0.0f, 1.0f};
|
||||
vertices[3].color = {rf, gf, bf, 1.0f};
|
||||
|
||||
// Añadir vértices al batch
|
||||
for (int i = 0; i < 4; i++) {
|
||||
batch_vertices.push_back(vertices[i]);
|
||||
}
|
||||
|
||||
// Añadir índices para 2 triángulos (6 índices por sprite)
|
||||
// Triángulo 1: 0,1,2
|
||||
batch_indices.push_back(vertex_index + 0);
|
||||
batch_indices.push_back(vertex_index + 1);
|
||||
batch_indices.push_back(vertex_index + 2);
|
||||
|
||||
// Triángulo 2: 2,3,0
|
||||
batch_indices.push_back(vertex_index + 2);
|
||||
batch_indices.push_back(vertex_index + 3);
|
||||
batch_indices.push_back(vertex_index + 0);
|
||||
}
|
||||
|
||||
// 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) {
|
||||
balls.clear();
|
||||
for (int i = 0; i < test.at(value); ++i) {
|
||||
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 VX = (((rand() % 20) + 10) * 0.1f) * SIGN; // Velocidad en X
|
||||
const float VY = ((rand() % 60) - 30) * 0.1f; // Velocidad en Y
|
||||
// Seleccionar color de la paleta del tema actual
|
||||
ThemeColors &theme = themes[static_cast<int>(current_theme)];
|
||||
int color_index = rand() % 8; // 8 colores por tema
|
||||
const Color COLOR = {theme.ball_colors[color_index][0],
|
||||
theme.ball_colors[color_index][1],
|
||||
theme.ball_colors[color_index][2]};
|
||||
balls.emplace_back(std::make_unique<Ball>(X, VX, VY, COLOR, texture, current_gravity));
|
||||
}
|
||||
setText(); // Actualiza el texto
|
||||
}
|
||||
|
||||
// Aumenta la velocidad vertical de las bolas "hacia arriba"
|
||||
void pushUpBalls() {
|
||||
for (auto &ball : balls) {
|
||||
const int SIGNO = ((rand() % 2) * 2) - 1;
|
||||
const float VX = (((rand() % 20) + 10) * 0.1f) * SIGNO;
|
||||
const float VY = ((rand() % 40) * 0.1f) + 5;
|
||||
ball->modVel(VX, -VY); // Modifica la velocidad de la bola
|
||||
}
|
||||
}
|
||||
|
||||
// Cambia la gravedad de todas las bolas
|
||||
void switchBallsGravity() {
|
||||
for (auto &ball : balls) {
|
||||
ball->switchGravity();
|
||||
}
|
||||
}
|
||||
|
||||
// Cambia la direcci\u00f3n de gravedad de todas las bolas
|
||||
void changeGravityDirection(GravityDirection new_direction) {
|
||||
current_gravity = new_direction;
|
||||
for (auto &ball : balls) {
|
||||
ball->setGravityDirection(new_direction);
|
||||
}
|
||||
}
|
||||
|
||||
// Convierte dirección de gravedad a texto para debug
|
||||
std::string gravityDirectionToString(GravityDirection direction) {
|
||||
switch (direction) {
|
||||
case GravityDirection::DOWN: return "DOWN";
|
||||
case GravityDirection::UP: return "UP";
|
||||
case GravityDirection::LEFT: return "LEFT";
|
||||
case GravityDirection::RIGHT: return "RIGHT";
|
||||
default: return "UNKNOWN";
|
||||
}
|
||||
}
|
||||
|
||||
// Alterna el estado del V-Sync
|
||||
void toggleVSync() {
|
||||
vsync_enabled = !vsync_enabled;
|
||||
vsync_text = vsync_enabled ? "VSYNC ON" : "VSYNC OFF";
|
||||
|
||||
// Aplicar el cambio de V-Sync al renderizador
|
||||
SDL_SetRenderVSync(renderer, vsync_enabled ? 1 : 0);
|
||||
}
|
||||
|
||||
// Calcula el delta time entre frames
|
||||
void calculateDeltaTime() {
|
||||
Uint64 current_time = SDL_GetTicks();
|
||||
|
||||
// En el primer frame, inicializar el tiempo anterior
|
||||
if (last_frame_time == 0) {
|
||||
last_frame_time = current_time;
|
||||
delta_time = 1.0f / 60.0f; // Asumir 60 FPS para el primer frame
|
||||
return;
|
||||
}
|
||||
|
||||
// Calcular delta time en segundos
|
||||
delta_time = (current_time - last_frame_time) / 1000.0f;
|
||||
last_frame_time = current_time;
|
||||
|
||||
// Limitar delta time para evitar saltos grandes (pausa larga, depuración, etc.)
|
||||
if (delta_time > 0.05f) // Máximo 50ms (20 FPS mínimo)
|
||||
{
|
||||
delta_time = 1.0f / 60.0f; // Usar 60 FPS como fallback
|
||||
}
|
||||
}
|
||||
|
||||
// Inicializa SDL y configura los componentes principales
|
||||
bool init() {
|
||||
bool success = true;
|
||||
|
||||
// Inicializa SDL
|
||||
if (!SDL_Init(SDL_INIT_VIDEO)) {
|
||||
std::cout << "¡SDL no se pudo inicializar! Error de SDL: " << SDL_GetError() << std::endl;
|
||||
success = false;
|
||||
} else {
|
||||
// Crear ventana principal
|
||||
window = SDL_CreateWindow(WINDOW_CAPTION, SCREEN_WIDTH * WINDOW_SIZE, SCREEN_HEIGHT * WINDOW_SIZE, SDL_WINDOW_OPENGL);
|
||||
if (window == nullptr) {
|
||||
std::cout << "¡No se pudo crear la ventana! Error de SDL: " << SDL_GetError() << std::endl;
|
||||
success = false;
|
||||
} else {
|
||||
// Crear renderizador
|
||||
renderer = SDL_CreateRenderer(window, nullptr);
|
||||
if (renderer == nullptr) {
|
||||
std::cout << "¡No se pudo crear el renderizador! Error de SDL: " << SDL_GetError() << std::endl;
|
||||
success = false;
|
||||
} else {
|
||||
// Establecer color inicial del renderizador
|
||||
SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
|
||||
|
||||
// Establecer tamaño lógico para el renderizado
|
||||
SDL_SetRenderLogicalPresentation(renderer, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_LOGICAL_PRESENTATION_INTEGER_SCALE);
|
||||
|
||||
// Configurar V-Sync inicial
|
||||
SDL_SetRenderVSync(renderer, vsync_enabled ? 1 : 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Inicializar otros componentes
|
||||
texture = std::make_shared<Texture>(renderer, "data/ball.png");
|
||||
// ticks eliminado - delta time system se inicializa automáticamente
|
||||
srand(static_cast<unsigned>(time(nullptr)));
|
||||
dbg_init(renderer);
|
||||
initBalls(scenario);
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
// Limpia todos los recursos y cierra SDL
|
||||
void close() {
|
||||
SDL_DestroyRenderer(renderer);
|
||||
SDL_DestroyWindow(window);
|
||||
SDL_Quit();
|
||||
}
|
||||
|
||||
// Verifica los eventos en la cola
|
||||
void checkEvents() {
|
||||
SDL_Event event;
|
||||
while (SDL_PollEvent(&event) != 0) {
|
||||
// Evento de salida
|
||||
if (event.type == SDL_EVENT_QUIT) {
|
||||
should_exit = true;
|
||||
break;
|
||||
}
|
||||
|
||||
// Procesar eventos de teclado
|
||||
if (event.type == SDL_EVENT_KEY_DOWN && event.key.repeat == 0) {
|
||||
switch (event.key.key) {
|
||||
case SDLK_ESCAPE:
|
||||
should_exit = true;
|
||||
break;
|
||||
|
||||
case SDLK_SPACE:
|
||||
pushUpBalls();
|
||||
break;
|
||||
|
||||
case SDLK_G:
|
||||
switchBallsGravity();
|
||||
break;
|
||||
|
||||
// Controles de direcci\u00f3n de gravedad con teclas de cursor
|
||||
case SDLK_UP:
|
||||
changeGravityDirection(GravityDirection::UP);
|
||||
break;
|
||||
|
||||
case SDLK_DOWN:
|
||||
changeGravityDirection(GravityDirection::DOWN);
|
||||
break;
|
||||
|
||||
case SDLK_LEFT:
|
||||
changeGravityDirection(GravityDirection::LEFT);
|
||||
break;
|
||||
|
||||
case SDLK_RIGHT:
|
||||
changeGravityDirection(GravityDirection::RIGHT);
|
||||
break;
|
||||
|
||||
case SDLK_V:
|
||||
toggleVSync();
|
||||
break;
|
||||
|
||||
case SDLK_H:
|
||||
show_debug = !show_debug;
|
||||
break;
|
||||
|
||||
case SDLK_T:
|
||||
// Ciclar al siguiente tema
|
||||
current_theme = static_cast<ColorTheme>((static_cast<int>(current_theme) + 1) % 4);
|
||||
initBalls(scenario); // Regenerar bolas con nueva paleta
|
||||
break;
|
||||
|
||||
case SDLK_F1:
|
||||
current_theme = ColorTheme::SUNSET;
|
||||
initBalls(scenario);
|
||||
break;
|
||||
|
||||
case SDLK_F2:
|
||||
current_theme = ColorTheme::OCEAN;
|
||||
initBalls(scenario);
|
||||
break;
|
||||
|
||||
case SDLK_F3:
|
||||
current_theme = ColorTheme::NEON;
|
||||
initBalls(scenario);
|
||||
break;
|
||||
|
||||
case SDLK_F4:
|
||||
current_theme = ColorTheme::FOREST;
|
||||
initBalls(scenario);
|
||||
break;
|
||||
|
||||
case SDLK_1:
|
||||
scenario = 0;
|
||||
initBalls(scenario);
|
||||
break;
|
||||
|
||||
case SDLK_2:
|
||||
scenario = 1;
|
||||
initBalls(scenario);
|
||||
break;
|
||||
|
||||
case SDLK_3:
|
||||
scenario = 2;
|
||||
initBalls(scenario);
|
||||
break;
|
||||
|
||||
case SDLK_4:
|
||||
scenario = 3;
|
||||
initBalls(scenario);
|
||||
break;
|
||||
|
||||
case SDLK_5:
|
||||
scenario = 4;
|
||||
initBalls(scenario);
|
||||
break;
|
||||
|
||||
case SDLK_6:
|
||||
scenario = 5;
|
||||
initBalls(scenario);
|
||||
break;
|
||||
|
||||
case SDLK_7:
|
||||
scenario = 6;
|
||||
initBalls(scenario);
|
||||
break;
|
||||
|
||||
case SDLK_8:
|
||||
scenario = 7;
|
||||
initBalls(scenario);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Actualiza la lógica del juego
|
||||
void update() {
|
||||
// Calcular FPS
|
||||
fps_frame_count++;
|
||||
Uint64 current_time = SDL_GetTicks();
|
||||
if (current_time - fps_last_time >= 1000) // Actualizar cada segundo
|
||||
{
|
||||
fps_current = fps_frame_count;
|
||||
fps_frame_count = 0;
|
||||
fps_last_time = current_time;
|
||||
fps_text = "FPS: " + std::to_string(fps_current);
|
||||
}
|
||||
|
||||
// ¡DELTA TIME! Actualizar física siempre, usando tiempo transcurrido
|
||||
for (auto &ball : balls) {
|
||||
ball->update(delta_time); // Pasar delta time a cada pelota
|
||||
}
|
||||
|
||||
// Actualizar texto (sin cambios en la lógica)
|
||||
if (show_text) {
|
||||
show_text = !(SDL_GetTicks() - text_init_time > TEXT_DURATION);
|
||||
}
|
||||
}
|
||||
|
||||
// Renderiza el contenido en la pantalla
|
||||
void render() {
|
||||
// Renderizar fondo degradado en lugar de color sólido
|
||||
renderGradientBackground();
|
||||
|
||||
// Limpiar batches del frame anterior
|
||||
batch_vertices.clear();
|
||||
batch_indices.clear();
|
||||
|
||||
// Recopilar datos de todas las bolas para batch rendering
|
||||
for (auto &ball : balls) {
|
||||
// En lugar de ball->render(), obtener datos para batch
|
||||
SDL_FRect pos = ball->getPosition();
|
||||
Color color = ball->getColor();
|
||||
addSpriteToBatch(pos.x, pos.y, pos.w, pos.h, color.r, color.g, color.b);
|
||||
}
|
||||
|
||||
// Renderizar todas las bolas en una sola llamada
|
||||
if (!batch_vertices.empty()) {
|
||||
SDL_RenderGeometry(renderer, texture->getSDLTexture(), batch_vertices.data(), static_cast<int>(batch_vertices.size()), batch_indices.data(), static_cast<int>(batch_indices.size()));
|
||||
}
|
||||
|
||||
if (show_text) {
|
||||
dbg_print(text_pos, 8, text.c_str(), 255, 255, 255);
|
||||
|
||||
// Mostrar nombre del tema en castellano debajo del número de pelotas
|
||||
std::string theme_names_es[] = {"ATARDECER", "OCEANO", "NEON", "BOSQUE"};
|
||||
std::string theme_name = theme_names_es[static_cast<int>(current_theme)];
|
||||
int theme_text_width = static_cast<int>(theme_name.length() * 8); // 8 píxeles por carácter
|
||||
int theme_x = (SCREEN_WIDTH - theme_text_width) / 2; // Centrar horizontalmente
|
||||
|
||||
// Colores acordes a cada tema
|
||||
int theme_colors[][3] = {
|
||||
{255, 140, 60}, // ATARDECER: Naranja cálido
|
||||
{80, 200, 255}, // OCEANO: Azul océano
|
||||
{255, 60, 255}, // NEON: Magenta brillante
|
||||
{100, 255, 100} // BOSQUE: Verde natural
|
||||
};
|
||||
int theme_idx = static_cast<int>(current_theme);
|
||||
dbg_print(theme_x, 24, theme_name.c_str(), theme_colors[theme_idx][0], theme_colors[theme_idx][1], theme_colors[theme_idx][2]);
|
||||
}
|
||||
|
||||
// Debug display (solo si está activado con tecla H)
|
||||
if (show_debug) {
|
||||
// Mostrar contador de FPS en esquina superior derecha
|
||||
int fps_text_width = static_cast<int>(fps_text.length() * 8); // 8 píxeles por carácter
|
||||
int fps_x = SCREEN_WIDTH - fps_text_width - 8; // 8 píxeles de margen
|
||||
dbg_print(fps_x, 8, fps_text.c_str(), 255, 255, 0); // Amarillo para distinguir
|
||||
|
||||
// Mostrar estado V-Sync en esquina superior izquierda
|
||||
dbg_print(8, 8, vsync_text.c_str(), 0, 255, 255); // Cian para distinguir
|
||||
|
||||
// Debug: Mostrar valores de la primera pelota (si existe)
|
||||
if (!balls.empty()) {
|
||||
// Línea 1: Gravedad (solo números enteros)
|
||||
int grav_int = static_cast<int>(balls[0]->getGravityForce());
|
||||
std::string grav_text = "GRAV " + std::to_string(grav_int);
|
||||
dbg_print(8, 24, grav_text.c_str(), 255, 0, 255); // Magenta para debug
|
||||
|
||||
// Línea 2: Velocidad Y (solo números enteros)
|
||||
int vy_int = static_cast<int>(balls[0]->getVelocityY());
|
||||
std::string vy_text = "VY " + std::to_string(vy_int);
|
||||
dbg_print(8, 32, vy_text.c_str(), 255, 0, 255); // Magenta para debug
|
||||
|
||||
// Línea 3: Estado superficie
|
||||
std::string surface_text = balls[0]->isOnSurface() ? "SURFACE YES" : "SURFACE NO";
|
||||
dbg_print(8, 40, surface_text.c_str(), 255, 0, 255); // Magenta para debug
|
||||
|
||||
// Línea 4: Dirección de gravedad
|
||||
std::string gravity_dir_text = "GRAVITY " + gravityDirectionToString(current_gravity);
|
||||
dbg_print(8, 48, gravity_dir_text.c_str(), 255, 255, 0); // Amarillo para dirección
|
||||
}
|
||||
|
||||
// Debug: Mostrar tema actual
|
||||
std::string theme_names[] = {"SUNSET", "OCEAN", "NEON", "FOREST"};
|
||||
std::string theme_text = "THEME " + theme_names[static_cast<int>(current_theme)];
|
||||
dbg_print(8, 56, theme_text.c_str(), 255, 255, 128); // Amarillo claro para tema
|
||||
}
|
||||
|
||||
SDL_RenderPresent(renderer);
|
||||
}
|
||||
|
||||
// Función principal
|
||||
int main(int argc, char *args[]) {
|
||||
if (!init()) {
|
||||
std::cout << "Ocurrió un error durante la inicialización." << std::endl;
|
||||
return 1;
|
||||
}
|
||||
|
||||
while (!should_exit) {
|
||||
// 1. Calcular delta time antes de actualizar la lógica
|
||||
calculateDeltaTime();
|
||||
|
||||
// 2. Actualizar lógica del juego con delta time
|
||||
update();
|
||||
|
||||
// 3. Procesar eventos de entrada
|
||||
checkEvents();
|
||||
|
||||
// 4. Renderizar la escena
|
||||
render();
|
||||
}
|
||||
|
||||
close();
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user