diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 0000000..0f0ee28 --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,150 @@ +name: Build y despliegue (GitHub Pages) + +on: + push: + branches: ['**'] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +env: + # Version fija de Emscripten (la misma con la que se verifico el build web) + EMSDK_VERSION: "6.0.13" + +jobs: + # --------------------------------------------------------------------------- + # 1) Pruebas de QA nativas (Modulos 1-3) con AddressSanitizer + UBSan + # --------------------------------------------------------------------------- + nativo: + name: Pruebas nativas (ASan + UBSan) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Instalar dependencias + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends cmake g++ libsdl2-dev + + - name: Configurar y compilar + run: | + cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug -DBGE_SANITIZE=ON + cmake --build build --parallel + + - name: Ejecutar pruebas (SDL_VIDEODRIVER=dummy, sin pantalla) + run: ctest --test-dir build --output-on-failure + + # --------------------------------------------------------------------------- + # 2) Compilacion cruzada a WebAssembly + prueba de integridad HTTP + # --------------------------------------------------------------------------- + web: + name: Compilar WebAssembly (Emscripten) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Cachear el SDK de Emscripten + uses: actions/cache@v4 + with: + path: ~/emsdk + key: emsdk-${{ runner.os }}-${{ env.EMSDK_VERSION }} + + - name: Instalar y activar Emscripten + run: | + if [ ! -d "$HOME/emsdk" ]; then + git clone --depth 1 https://github.com/emscripten-core/emsdk.git "$HOME/emsdk" + fi + cd "$HOME/emsdk" + ./emsdk install "$EMSDK_VERSION" + ./emsdk activate "$EMSDK_VERSION" + + - name: Configurar (emcmake) y compilar + run: | + source "$HOME/emsdk/emsdk_env.sh" + emcc --version | head -1 + emcmake cmake -S . -B build-web -DCMAKE_BUILD_TYPE=Release + cmake --build build-web --parallel + + - name: Verificar que se generaron index.html, index.js e index.wasm + run: | + for f in index.html index.js index.wasm; do + test -s "build-web/$f" || { echo "::error::falta build-web/$f"; exit 1; } + done + ls -la build-web/index.* + + - name: Ensamblar el sitio + run: | + mkdir site + cp build-web/index.html build-web/index.js build-web/index.wasm site/ + touch site/.nojekyll + + - name: Prueba de integridad (servidor HTTP local) + run: | + python3 -m http.server 8080 --directory site >/dev/null 2>&1 & + SERVER_PID=$! + trap 'kill "$SERVER_PID" 2>/dev/null || true' EXIT + + # Esperar a que el servidor responda (en vez de un sleep fijo) + for i in $(seq 1 20); do + curl -sf -o /dev/null http://127.0.0.1:8080/index.html && break + sleep 0.5 + done + + for f in index.html index.js index.wasm; do + code=$(curl -s -o "/tmp/$f" -w '%{http_code}' "http://127.0.0.1:8080/$f") + echo "$f -> HTTP $code" + test "$code" = "200" + done + + # Un .wasm valido empieza por los bytes 00 61 73 6d ("\0asm"). + # Se valida con Python: xxd no esta garantizado en todos los runners. + python3 - <<'PY' + with open('/tmp/index.wasm', 'rb') as f: + header = f.read(4) + assert header == b'\x00asm', f'Cabecera WASM invalida: {header!r}' + print('Cabecera WASM verificada') + PY + + # emcc minimiza el HTML y elimina las comillas (), + # por eso se busca la etiqueta y no el atributo con comillas. + grep -qi ' encontrada en index.html" + + - name: Subir artefacto para GitHub Pages + if: github.ref == format('refs/heads/{0}', github.event.repository.default_branch) + uses: actions/upload-pages-artifact@v3 + with: + path: site + + - name: Subir artefacto de revision (ramas y PR) + if: github.ref != format('refs/heads/{0}', github.event.repository.default_branch) + uses: actions/upload-artifact@v4 + with: + name: sitio-web + path: site + retention-days: 7 + + # --------------------------------------------------------------------------- + # 3) Despliegue a GitHub Pages (solo desde la rama por defecto) + # --------------------------------------------------------------------------- + deploy: + name: Desplegar en GitHub Pages + if: github.ref == format('refs/heads/{0}', github.event.repository.default_branch) + needs: [nativo, web] + runs-on: ubuntu-latest + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.despliegue.outputs.page_url }} + steps: + - name: Desplegar + id: despliegue + uses: actions/deploy-pages@v4 diff --git a/.gitignore b/.gitignore index dfcfd56..a87bcc1 100644 --- a/.gitignore +++ b/.gitignore @@ -348,3 +348,7 @@ MigrationBackup/ # Ionide (cross platform F# VS Code tools) working folder .ionide/ + +# CMake / build +build/ +build-*/ diff --git a/BasicGameEngine/BasicGameEngine.sln b/BasicGameEngine/BasicGameEngine.sln deleted file mode 100644 index a5e936b..0000000 --- a/BasicGameEngine/BasicGameEngine.sln +++ /dev/null @@ -1,31 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.30804.86 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "BasicGameEngine", "BasicGameEngine\BasicGameEngine.vcxproj", "{4898A56D-8B95-4A2E-A6CE-43F77EB2903E}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {4898A56D-8B95-4A2E-A6CE-43F77EB2903E}.Debug|x64.ActiveCfg = Debug|x64 - {4898A56D-8B95-4A2E-A6CE-43F77EB2903E}.Debug|x64.Build.0 = Debug|x64 - {4898A56D-8B95-4A2E-A6CE-43F77EB2903E}.Debug|x86.ActiveCfg = Debug|Win32 - {4898A56D-8B95-4A2E-A6CE-43F77EB2903E}.Debug|x86.Build.0 = Debug|Win32 - {4898A56D-8B95-4A2E-A6CE-43F77EB2903E}.Release|x64.ActiveCfg = Release|x64 - {4898A56D-8B95-4A2E-A6CE-43F77EB2903E}.Release|x64.Build.0 = Release|x64 - {4898A56D-8B95-4A2E-A6CE-43F77EB2903E}.Release|x86.ActiveCfg = Release|Win32 - {4898A56D-8B95-4A2E-A6CE-43F77EB2903E}.Release|x86.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {32723B2A-9D70-40CE-AB70-180B40974AEB} - EndGlobalSection -EndGlobal diff --git a/BasicGameEngine/BasicGameEngine/BasicGameEngine.vcxproj b/BasicGameEngine/BasicGameEngine/BasicGameEngine.vcxproj deleted file mode 100644 index 303019b..0000000 --- a/BasicGameEngine/BasicGameEngine/BasicGameEngine.vcxproj +++ /dev/null @@ -1,150 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - 16.0 - Win32Proj - {4898a56d-8b95-4a2e-a6ce-43f77eb2903e} - BasicGameEngine - 10.0 - - - - Application - true - v142 - Unicode - - - Application - false - v142 - true - Unicode - - - Application - true - v142 - Unicode - - - Application - false - v142 - true - Unicode - - - - - - - - - - - - - - - - - - - - - true - - - false - - - true - - - false - - - - Level3 - true - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - - - Console - true - - - - - Level3 - true - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - - - Console - true - true - true - - - - - Level3 - true - _DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - - - Console - true - - - - - Level3 - true - true - true - NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - - - Console - true - true - true - - - - - - - - - - - - \ No newline at end of file diff --git a/BasicGameEngine/BasicGameEngine/BasicGameEngine.vcxproj.filters b/BasicGameEngine/BasicGameEngine/BasicGameEngine.vcxproj.filters deleted file mode 100644 index 0cda911..0000000 --- a/BasicGameEngine/BasicGameEngine/BasicGameEngine.vcxproj.filters +++ /dev/null @@ -1,27 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - Header Files - - - - - Source Files - - - \ No newline at end of file diff --git a/BasicGameEngine/BasicGameEngine/NucleoMotor.cpp b/BasicGameEngine/BasicGameEngine/NucleoMotor.cpp deleted file mode 100644 index 97be9dc..0000000 --- a/BasicGameEngine/BasicGameEngine/NucleoMotor.cpp +++ /dev/null @@ -1,233 +0,0 @@ -//------------------------------------------------------------------------------------------ -// Objto NucleoMotor -// Codigo fuente C++ - NucleoMotor.cpp -//------------------------------------------------------------------------------------------ - -//------------------------------------------------------------------------------------------ -// Archivos de inclusion -//------------------------------------------------------------------------------------------ -#include "NucleoMotor.h" - -//------------------------------------------------------------------------------------------ -// Inicializacion de variables estaticas -//------------------------------------------------------------------------------------------ -NucleoMotor* NucleoMotor::m_pNucleoMotor = NULL; - -//------------------------------------------------------------------------------------------ -// Funciones Windows -//------------------------------------------------------------------------------------------ -int WINAPI WinMain(HINSTANCE hInstancia, HINSTANCE hInstanciaPrev, PSTR szCmdLine, int iMostrar) -{ - MSG msg; - static int iSiguienteCiclo = 0; - int iTicsPasados; - - if (FJ_InicializarJuego(hInstancia)) - { - // Inicializa el nucleo motor - // (crea ventana y la muestra en pantalla) - if (!NucleoMotor::ObtenerNucleoMotor()->Inicializar(iMostrar)) - return FALSE; - // Bucle principal de mensajes - while (TRUE) - { - if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) - { - // Proceso del mensaje - // El mensaje WM_QUIT hace salir del bucle - // La funcion PeekMessage entrega los mensajes que hay en la cola - if (msg.message == WM_QUIT) - break; - - // Traduce los mensajes de teclas virtuales - TranslateMessage(&msg); - - // Envia el mensaje al procedimiento de ventana - // donde seran tratados por el metodo TratarMensajes() - DispatchMessage(&msg); - } - - // Cuando hay mensajes pendientes - // verifica si ya se debe ejecutar un ciclo - else - { - // Se verifica que el juego no este en pausa - if (!NucleoMotor::ObtenerNucleoMotor()->ObtenerEnEspera()) - { - // Se verifica la cuenta de tics para ver si - // ha pasado el cliclo del juego - iTicsPasados = GetTickCount(); - - if (iTicsPasados > iSiguienteCiclo) - { - // Antes de ir al ciclo del juego - // actualiza el tiempo del ciclo siguiente - iSiguienteCiclo = iTicsPasados + 1000 / NucleoMotor::ObtenerNucleoMotor()->ObtenerFrecuencia(); - - //Ejecucion del ciclo del juego - FJ_CicloJuego(); - } - } - } - } - - return (int)msg.wParam; - } - - // Final del juego - FJ_FinalizarJuego(); - - return TRUE; -} - -LRESULT CALLBACK WindowProc(HWND hVentana, UINT msg, WPARAM wParam, LPARAM lParam) -{ - //Procedimiento de ventana - // Envia los mensajes a la funcion de tratamiento de los eventos - return NucleoMotor::ObtenerNucleoMotor()->TratarMensajes(hVentana, msg, wParam, lParam); -} - -//------------------------------------------------------------------------------------------------------------- -// NucleoMotor Constructor(s)/Destructor -//------------------------------------------------------------------------------------------------------------- -NucleoMotor::NucleoMotor(HINSTANCE hInstancia, LPTSTR szClaseVentana, LPTSTR szTitulo, WORD wIcono, WORD wIconoSm, int iAncho, int iAltura, int iFrecuencia) -{ - // Asigna las varialbes miembro del objeto NucleoMotor - m_pNucleoMotor = this; - m_hInstancia = hInstancia; - - // Queda pendiente asignar el handle de la ventana - m_hVentana = NULL; - - // Copia la cadena cuando hay informacion - if (lstrlen(szClaseVentana) > 0) - lstrcpy(m_szClaseVentana, szClaseVentana); - - // Copia la cadena cuando hay informacion - if (lstrlen(szTitulo) > 0) - lstrcpy(m_szTitulo, szTitulo); - - // Identificadores del recurso Icono - m_wIcono = wIcono; - m_wIconoSm = wIconoSm; - - // Dimensiones de la ventana - m_iAncho = iAncho; - m_iAltura = iAltura; - - // La frecuencia del ciclo es en fps - m_iFrecuencia = iFrecuencia; - - // El juego comienza en pausa - m_bEnEspera = TRUE; -} - -NucleoMotor::~NucleoMotor() -{ - //De momento no hace nada en particular -} - -//------------------------------------------------------------------------------------------- -// Metodos del objeto NucleoMotor -//------------------------------------------------------------------------------------------- -BOOL NucleoMotor::Inicializar(int iMostrar) -{ - WNDCLASSEX wndclass; - - // Crea la clase ventana para la ventana principal - wndclass.cbSize = sizeof(wndclass); - wndclass.style = CS_HREDRAW | CS_VREDRAW; - wndclass.lpfnWndProc = WindowProc; - wndclass.cbClsExtra = 0; - wndclass.cbWndExtra = 0; - wndclass.hInstance = m_hInstancia; - wndclass.hIcon = LoadIcon(m_hInstancia, MAKEINTRESOURCE(ObtenerIcono())); - wndclass.hIconSm = LoadIcon(m_hInstancia, MAKEINTRESOURCE(ObtenerIconoSm())); - wndclass.hCursor = LoadCursor(NULL, IDC_ARROW); - wndclass.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); - wndclass.lpszMenuName = NULL; - wndclass.lpszClassName = m_szClaseVentana; - - // Registra la clase de ventanas - if (!RegisterClassEx(&wndclass)) - return FALSE; - - // Calcula el tamaño de la ventana - int iAncho = m_iAncho + GetSystemMetrics(SM_CXFIXEDFRAME) * 2; - int iAltura = m_iAltura + GetSystemMetrics(SM_CXFIXEDFRAME) * 2 + GetSystemMetrics(SM_CYCAPTION); - - // Verifica si hay titulo de ventana - // en ese caso corrige la altura - if (wndclass.lpszMenuName != NULL) - iAltura += GetSystemMetrics(SM_CYMENU); - - // Posicionamiento de la ventana en el centro de la pantalla - int iPosX = (GetSystemMetrics(SM_CXSCREEN) - iAncho) / 2; - int iPosY = (GetSystemMetrics(SM_CYSCREEN) - iAltura) / 2; - - // Crea la ventana - // No se puede redimensionar pero se puede minimizar y tiene barra de titulo - m_hVentana = CreateWindow(m_szClaseVentana, m_szTitulo, WS_POPUPWINDOW | WS_CAPTION | WS_MINIMIZEBOX, iPosX, iPosY, iAncho, iAltura, NULL, NULL, m_hInstancia, NULL); - - // Si no puede crear la ventana devuelve false - if (!m_hVentana) - return FALSE; - - // Mostrar y actualizar ventana - ShowWindow(m_hVentana, iMostrar); - UpdateWindow(m_hVentana); - - return TRUE; -} - -LRESULT NucleoMotor::TratarMensajes(HWND hVentana, UINT msg, WPARAM wParam, LPARAM lParam) -{ - // Tratamiento de los mensajes - switch (msg) - { - //----------------------------------------- - case WM_CREATE: - // Asigna la ventana y comienza el juego - AsignarVentana(hVentana); - FJ_ComenzarJuego(hVentana); - return 0; - - //----------------------------------------- - case WM_KILLFOCUS: - // Desactiva el juego y actualiza el estado de pausa - FJ_DetenerJuego(hVentana); - AsignarEnEspera(TRUE); - return 0; - - //----------------------------------------- - case WM_PAINT: - HDC hDC; - PAINTSTRUCT ps; - hDC = BeginPaint(hVentana, &ps); - - // Dibuja el juego - FJ_PintarJuego(hDC); - - EndPaint(hVentana, &ps); - return 0; - - //----------------------------------------- - case WM_SETFOCUS: - // Activa el juego y actualiza el estado en pausa - FJ_ReactivarJuego(hVentana); - AsignarEnEspera(FALSE); - return 0; - - //----------------------------------------- - case WM_DESTROY: - // Final del juego y sale de la aplicacion - FJ_FinalizarJuego(); - PostQuitMessage(0); - return 0; - - } - - // Tratamiento del resto de los mensajes - // no gestionados por NucleoMotor - return DefWindowProc(hVentana, msg, wParam, lParam); -} \ No newline at end of file diff --git a/BasicGameEngine/BasicGameEngine/NucleoMotor.h b/BasicGameEngine/BasicGameEngine/NucleoMotor.h deleted file mode 100644 index e63dd25..0000000 --- a/BasicGameEngine/BasicGameEngine/NucleoMotor.h +++ /dev/null @@ -1,144 +0,0 @@ -//------------------------------------------------------------------------------------ -// NucleoMotor -// Encabezado C++ - NucleoMotor.h -//------------------------------------------------------------------------------------ -// Para evitar la doble inclusion de archivos -#pragma once - -//------------------------------------------------------------------------------------ -// Inclusion de archivos -//------------------------------------------------------------------------------------ -#include -#include - -//------------------------------------------------------------------------------------ -// Declaraciones de funciones -//------------------------------------------------------------------------------------ -// punto de entrada de los programas Windows -int WINAPI WinMain(HINSTANCE HInstancia, HINSTANCE hInstanciaPrev, PSTR szCmdLine, int iMostrar); - -// procedimiento de ventana -LRESULT CALLBACK WindowProc(HWND, UINT, WPARAM, LPARAM); - -//------------------------------------------------------------------------------------ -// Funciones auxiliares del nuecleo motor -//------------------------------------------------------------------------------------ -BOOL FJ_InicializarJuego(HINSTANCE hInstancia); -void FJ_ComenzarJuego(HWND hVentana); -void FJ_CicloJuego(); -void FJ_ReactivarJuego(HWND hVentana); -void FJ_DetenerJuego(HWND hVentana); -void FJ_PintarJuego(HDC hDC); -void FJ_FinalizarJuego(); - -//------------------------------------------------------------------------------------ -// Clase NucleoMotor -//------------------------------------------------------------------------------------ -class NucleoMotor -{ -protected: - //----------------------------------------------------- - // miembros protegidos de la clase - //----------------------------------------------------- - static NucleoMotor* m_pNucleoMotor; - HINSTANCE m_hInstancia; // handle de la instancia - HWND m_hVentana; // handle de ventana - TCHAR m_szClaseVentana[32]; // Clase de la ventana - TCHAR m_szTitulo[12]; // Titulo - int m_iAncho; // Ancho de ventana - int m_iAltura; // Altura de ventana - WORD m_wIcono; // Icono normal - WORD m_wIconoSm; // Icono pequeño - int m_iFrecuencia; // Frecuencia del ciclo (fps) - BOOL m_bEnEspera; // Indicador de estado - -public: - //----------------------------------------------------- - // miembros publicos de la clase - //----------------------------------------------------- - // Constructor y Destructor - //----------------------------------------------------- - NucleoMotor(HINSTANCE hInstancia, LPTSTR szClaseVentana, LPTSTR szTitulo, WORD wIcono, WORD wIconoSm, int iAncho = 640, int iAltura = 480, int iFrecuencia = 50); - - virtual ~NucleoMotor(); // Destructor de la clase - - //--------------------------------------------------------------------------------------------------------- - // Metodos auxiliares - //--------------------------------------------------------------------------------------------------------- - // Crea la clase ventan y despues crea la ventana - BOOL Inicializar(int iMostrar); - - // Tratamiento de los mensakes - LRESULT TratarMensajes(HWND hVentana, UINT msg, WPARAM wParam, LPARAM lParam); - - //--------------------------------------------------------------------------------------------------------- - // Metodos de acceso a los miembros protegidos - //--------------------------------------------------------------------------------------------------------- - // Devuelve el puntero del objeto - static NucleoMotor* ObtenerNucleoMotor() - { - return m_pNucleoMotor; - }; - - // Obtencion o asignacion de los miembros protegidos - HINSTANCE ObtenerInstancia() - { - return m_hInstancia; - }; - - //Handle de la ventanan - HWND ObtenerVentana() - { - return m_hVentana; - }; - void AsignarVentana(HWND hVentana) - { - m_hVentana = hVentana; - }; - - // Titulo de la ventana - LPTSTR ObtenerTitulo() - { - return m_szTitulo; - }; - - // Iconos del programa - WORD ObtenerIcono() - { - return m_wIcono; - }; - WORD ObtenerIconoSm() - { - return m_wIconoSm; - }; - - // Tamaño de la ventana - int ObtenerAncho() - { - return m_iAncho; - }; - int ObtenerAltura() - { - return m_iAltura; - }; - - // Frecuencia en frames por segundo (fps) - int ObtenerFrecuencia() - { - return m_iFrecuencia; - }; - void AsignarFrecuencia(int iFrecuencia) - { - m_iFrecuencia = iFrecuencia; - }; - - // Indicador de estado - BOOL ObtenerEnEspera() - { - return m_bEnEspera; - }; - void AsignarEnEspera(BOOL bEnEspera) - { - m_bEnEspera = bEnEspera; - }; -}; \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..a019d04 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,66 @@ +cmake_minimum_required(VERSION 3.16) +project(BasicGameEngine LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE Release CACHE STRING "Tipo de build" FORCE) +endif() + +option(BGE_SANITIZE "Compilar con AddressSanitizer/UBSan (solo nativo)" OFF) + +# --- Biblioteca del motor (Modulos 1, 2 y 3) ------------------------------------ +add_library(nucleo STATIC src/Ventana.cpp src/NucleoMotor.cpp src/Dibujante.cpp) +target_include_directories(nucleo PUBLIC src) + +if(EMSCRIPTEN) + # SDL2 viene como "port" de Emscripten (se descarga y cachea la primera vez) + target_compile_options(nucleo PUBLIC -sUSE_SDL=2) + target_link_options(nucleo PUBLIC -sUSE_SDL=2 -sALLOW_MEMORY_GROWTH=1) +else() + find_package(SDL2 REQUIRED) + target_link_libraries(nucleo PUBLIC SDL2::SDL2) + if(MSVC) + target_compile_options(nucleo PRIVATE /W4) + else() + target_compile_options(nucleo PRIVATE -Wall -Wextra -Wpedantic) + endif() + if(BGE_SANITIZE AND NOT MSVC) + target_compile_options(nucleo PUBLIC -fsanitize=address,undefined -fno-omit-frame-pointer) + target_link_options(nucleo PUBLIC -fsanitize=address,undefined) + endif() +endif() + +# --- Ejecutable de demostracion -------------------------------------------------- +add_executable(juego src/main.cpp) +target_link_libraries(juego PRIVATE nucleo) + +if(EMSCRIPTEN) + # Salida: index.html + index.js + index.wasm (en el directorio de build) + set(BGE_SHELL "${CMAKE_SOURCE_DIR}/web/minimal_shell.html") + set_target_properties(juego PROPERTIES + OUTPUT_NAME index + SUFFIX ".html" + LINK_DEPENDS "${BGE_SHELL}") # re-enlaza si cambia la plantilla + target_link_options(juego PRIVATE + "SHELL:--shell-file ${BGE_SHELL}" + $<$:-sASSERTIONS=1>) +endif() + +# --- Pruebas de QA (solo nativo) --------------------------------------------------- +if(NOT EMSCRIPTEN) + enable_testing() + set(BGE_TEST_ENV "SDL_VIDEODRIVER=dummy;SDL_RENDER_DRIVER=software;SDL_AUDIODRIVER=dummy") + + add_executable(test_motor tests/test_motor.cpp) + target_link_libraries(test_motor PRIVATE nucleo) + add_test(NAME qa_modulos_1_2 COMMAND test_motor) + + add_executable(test_graficos tests/test_graficos.cpp) + target_link_libraries(test_graficos PRIVATE nucleo) + add_test(NAME qa_modulo_3 COMMAND test_graficos) + + set_tests_properties(qa_modulos_1_2 qa_modulo_3 PROPERTIES ENVIRONMENT "${BGE_TEST_ENV}") +endif() diff --git a/README.md b/README.md index 3dfe756..b0b1a30 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,74 @@ # BasicGameEngine -Basic Engine for Games for C++ + +Motor básico de juegos 2D en C++17 sobre **SDL2**, que se ejecuta en escritorio (nativo) y +en el navegador (WebAssembly con Emscripten, publicado en GitHub Pages). +Migrado desde la versión original basada en Win32. + +## Módulos + +| Módulo | Contenido | QA | +|---|---|---| +| 1. Plataforma y ventana | `src/Ventana.*` — SDL2 RAII, foco, cierre, ESC, teclado/ratón | `tests/test_motor.cpp` (1.1–1.3) | +| 2. Núcleo y bucle de paso fijo | `src/NucleoMotor.*` — 60 Hz lógicos, `emscripten_set_main_loop_arg` | `tests/test_motor.cpp` (2.1) | +| 3. Renderizado 2D | `src/Dibujante.*` — primitivas, texto bitmap 5x7; el motor limpia el fondo en cada frame | `tests/test_graficos.cpp` (3.1, 3.2) | +| 4. Build y CI/CD | `CMakeLists.txt`, `web/minimal_shell.html`, `.github/workflows/deploy.yml` | CI (4.1, 4.2) | + +## Compilar y probar en nativo + +```bash +sudo apt install libsdl2-dev cmake g++ +cmake -S . -B build -DBGE_SANITIZE=ON +cmake --build build +ctest --test-dir build --output-on-failure # SDL_VIDEODRIVER=dummy: no necesita pantalla +./build/juego # demo (ESC para salir) +``` + +## Compilar a WebAssembly en local + +Instala el SDK de Emscripten (una sola vez): + +```bash +git clone https://github.com/emscripten-core/emsdk.git ~/emsdk +~/emsdk/emsdk install 6.0.13 +~/emsdk/emsdk activate 6.0.13 +``` + +Cada vez que abras una terminal nueva, carga el entorno y compila: + +```bash +source ~/emsdk/emsdk_env.sh +emcmake cmake -S . -B build-web -DCMAKE_BUILD_TYPE=Release +cmake --build build-web +``` + +Genera `build-web/index.html`, `index.js` e `index.wasm`. Para probarlo (los navegadores no +cargan `.wasm` desde `file://`, hay que servirlo por HTTP): + +```bash +python3 -m http.server 8000 --directory build-web +# abre http://localhost:8000 +``` + +Equivalente directo con `emcc`, sin CMake: + +```bash +emcc -std=c++17 -O2 src/*.cpp -Isrc -sUSE_SDL=2 -sALLOW_MEMORY_GROWTH=1 \ + --shell-file web/minimal_shell.html -o index.html +``` + +> La primera compilación descarga el *port* de SDL2 desde GitHub y lo cachea; necesita acceso a internet. + +## Publicar en GitHub Pages + +1. En el repositorio: **Settings → Pages → Build and deployment → Source: GitHub Actions** (una sola vez). +2. Cada push a la rama por defecto ejecuta `.github/workflows/deploy.yml`: pruebas nativas con + ASan/UBSan, compilación con Emscripten, prueba de integridad por HTTP y despliegue. + En otras ramas y PR solo se compila y se sube el sitio como artefacto de revisión. + +## Uso del motor + +Implementa la interfaz `Juego` (`Comenzar`, `Actualizar(dt)`, `Pintar(SDL_Renderer*)`, +`Detener`, `Reactivar`, `Finalizar`) y pásala a `NucleoMotor`; dentro de `Pintar` usa +`Dibujante(renderizador)` para dibujar. Ver `src/main.cpp`. +En Emscripten, `NucleoMotor` y el `Juego` deben tener duración estática (el bucle sigue vivo +después de que `main()` retorne). diff --git a/src/Dibujante.cpp b/src/Dibujante.cpp new file mode 100644 index 0000000..c7156fa --- /dev/null +++ b/src/Dibujante.cpp @@ -0,0 +1,171 @@ +//------------------------------------------------------------------------------------ +// Dibujante (Modulo 3: Renderizado 2D y helpers graficos) +// Codigo fuente C++ - Dibujante.cpp +//------------------------------------------------------------------------------------ +#include "Dibujante.h" + +#include +#include +#include + +namespace +{ +// Fuente 5x7: cada glifo son 7 filas de 5 bits (bit 4 = columna izquierda). +struct Glifo +{ + char caracter; + std::uint8_t filas[Dibujante::kAltoGlifo]; +}; + +constexpr Glifo kFuente[] = { + { '0', { 0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110 } }, + { '1', { 0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110 } }, + { '2', { 0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0b01000, 0b11111 } }, + { '3', { 0b11110, 0b00001, 0b00001, 0b01110, 0b00001, 0b00001, 0b11110 } }, + { '4', { 0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010 } }, + { '5', { 0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110 } }, + { '6', { 0b00110, 0b01000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110 } }, + { '7', { 0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b01000, 0b01000 } }, + { '8', { 0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110 } }, + { '9', { 0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00010, 0b01100 } }, + { 'A', { 0b01110, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001 } }, + { 'B', { 0b11110, 0b10001, 0b10001, 0b11110, 0b10001, 0b10001, 0b11110 } }, + { 'C', { 0b01110, 0b10001, 0b10000, 0b10000, 0b10000, 0b10001, 0b01110 } }, + { 'D', { 0b11100, 0b10010, 0b10001, 0b10001, 0b10001, 0b10010, 0b11100 } }, + { 'E', { 0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b11111 } }, + { 'F', { 0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b10000 } }, + { 'G', { 0b01110, 0b10001, 0b10000, 0b10111, 0b10001, 0b10001, 0b01111 } }, + { 'H', { 0b10001, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001 } }, + { 'I', { 0b01110, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110 } }, + { 'J', { 0b00111, 0b00010, 0b00010, 0b00010, 0b00010, 0b10010, 0b01100 } }, + { 'K', { 0b10001, 0b10010, 0b10100, 0b11000, 0b10100, 0b10010, 0b10001 } }, + { 'L', { 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b11111 } }, + { 'M', { 0b10001, 0b11011, 0b10101, 0b10101, 0b10001, 0b10001, 0b10001 } }, + { 'N', { 0b10001, 0b10001, 0b11001, 0b10101, 0b10011, 0b10001, 0b10001 } }, + { 'O', { 0b01110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110 } }, + { 'P', { 0b11110, 0b10001, 0b10001, 0b11110, 0b10000, 0b10000, 0b10000 } }, + { 'Q', { 0b01110, 0b10001, 0b10001, 0b10001, 0b10101, 0b10010, 0b01101 } }, + { 'R', { 0b11110, 0b10001, 0b10001, 0b11110, 0b10100, 0b10010, 0b10001 } }, + { 'S', { 0b01111, 0b10000, 0b10000, 0b01110, 0b00001, 0b00001, 0b11110 } }, + { 'T', { 0b11111, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100 } }, + { 'U', { 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110 } }, + { 'V', { 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01010, 0b00100 } }, + { 'W', { 0b10001, 0b10001, 0b10001, 0b10101, 0b10101, 0b10101, 0b01010 } }, + { 'X', { 0b10001, 0b10001, 0b01010, 0b00100, 0b01010, 0b10001, 0b10001 } }, + { 'Y', { 0b10001, 0b10001, 0b01010, 0b00100, 0b00100, 0b00100, 0b00100 } }, + { 'Z', { 0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b10000, 0b11111 } }, + { '.', { 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b01100, 0b01100 } }, + { ',', { 0b00000, 0b00000, 0b00000, 0b00000, 0b01100, 0b00100, 0b01000 } }, + { ':', { 0b00000, 0b01100, 0b01100, 0b00000, 0b01100, 0b01100, 0b00000 } }, + { '-', { 0b00000, 0b00000, 0b00000, 0b11111, 0b00000, 0b00000, 0b00000 } }, + { '+', { 0b00000, 0b00100, 0b00100, 0b11111, 0b00100, 0b00100, 0b00000 } }, + { '/', { 0b00001, 0b00010, 0b00010, 0b00100, 0b01000, 0b01000, 0b10000 } }, + { '%', { 0b11001, 0b11010, 0b00010, 0b00100, 0b01000, 0b01011, 0b10011 } }, + { '(', { 0b00010, 0b00100, 0b01000, 0b01000, 0b01000, 0b00100, 0b00010 } }, + { ')', { 0b01000, 0b00100, 0b00010, 0b00010, 0b00010, 0b00100, 0b01000 } }, + { '!', { 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00000, 0b00100 } }, + { '?', { 0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0b00000, 0b00100 } }, + { '=', { 0b00000, 0b00000, 0b11111, 0b00000, 0b11111, 0b00000, 0b00000 } }, + { '_', { 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b11111 } }, +}; + +// Glifo para un caracter; nullptr si no esta en la fuente (el espacio no dibuja nada) +const Glifo* BuscarGlifo(char c) noexcept +{ + const char mayuscula = static_cast(std::toupper(static_cast(c))); + for (const Glifo& g : kFuente) + if (g.caracter == mayuscula) + return &g; + return nullptr; +} + +constexpr int kSeparacion = 1; // pixeles (escala 1) entre glifos +} // namespace + +//------------------------------------------------------------------------------------ +// Primitivas +//------------------------------------------------------------------------------------ +void Dibujante::Color_(Color c) const +{ + SDL_SetRenderDrawColor(m_r, c.r, c.g, c.b, c.a); +} + +void Dibujante::Limpiar(Color c) const +{ + Color_(c); + SDL_RenderClear(m_r); +} + +void Dibujante::Punto(int x, int y, Color c) const +{ + Color_(c); + SDL_RenderDrawPoint(m_r, x, y); +} + +void Dibujante::Linea(int x1, int y1, int x2, int y2, Color c) const +{ + Color_(c); + SDL_RenderDrawLine(m_r, x1, y1, x2, y2); +} + +void Dibujante::Rectangulo(const SDL_Rect& r, Color c) const +{ + Color_(c); + SDL_RenderDrawRect(m_r, &r); +} + +void Dibujante::RectanguloRelleno(const SDL_Rect& r, Color c) const +{ + Color_(c); + SDL_RenderFillRect(m_r, &r); +} + +//------------------------------------------------------------------------------------ +// Texto +//------------------------------------------------------------------------------------ +int Dibujante::AnchoTexto(const std::string& texto, int escala) noexcept +{ + int maximo = 0, actual = 0; + for (char c : texto) + { + if (c == '\n') { maximo = std::max(maximo, actual); actual = 0; continue; } + actual += kAnchoGlifo + kSeparacion; + } + maximo = std::max(maximo, actual); + return maximo > 0 ? (maximo - kSeparacion) * escala : 0; +} + +int Dibujante::Texto(int x, int y, const std::string& texto, Color c, int escala) const +{ + if (escala < 1) + escala = 1; + + std::vector pixeles; // un unico SDL_RenderFillRects para todo el texto + pixeles.reserve(texto.size() * 16); + + int cx = x, cy = y; + for (char ch : texto) + { + if (ch == '\n') + { + cx = x; + cy += (kAltoGlifo + 2) * escala; + continue; + } + if (const Glifo* g = BuscarGlifo(ch)) + { + for (int fila = 0; fila < kAltoGlifo; ++fila) + for (int col = 0; col < kAnchoGlifo; ++col) + if (g->filas[fila] & (1 << (kAnchoGlifo - 1 - col))) + pixeles.push_back(SDL_Rect{ cx + col * escala, cy + fila * escala, escala, escala }); + } + cx += (kAnchoGlifo + kSeparacion) * escala; + } + + if (!pixeles.empty()) + { + Color_(c); + SDL_RenderFillRects(m_r, pixeles.data(), static_cast(pixeles.size())); + } + return AnchoTexto(texto, escala); +} diff --git a/src/Dibujante.h b/src/Dibujante.h new file mode 100644 index 0000000..17411a9 --- /dev/null +++ b/src/Dibujante.h @@ -0,0 +1,62 @@ +//------------------------------------------------------------------------------------ +// Dibujante (Modulo 3: Renderizado 2D y helpers graficos) +// Encabezado C++ - Dibujante.h +//------------------------------------------------------------------------------------ +// Capa fina y sin propiedad sobre SDL_Renderer: primitivas (punto, linea, rectangulo, +// rectangulo relleno) y texto con una fuente bitmap 5x7 incorporada (no necesita +// SDL_ttf ni archivos de recursos, asi funciona igual en nativo y en Emscripten). +// Es barata de construir: crear una instancia por frame dentro de Juego::Pintar. +//------------------------------------------------------------------------------------ +#pragma once + +#include + +#include +#include + +struct Color +{ + std::uint8_t r = 0, g = 0, b = 0, a = 255; +}; + +namespace Colores +{ + inline constexpr Color Negro { 0, 0, 0, 255 }; + inline constexpr Color Blanco { 255, 255, 255, 255 }; + inline constexpr Color Rojo { 220, 50, 47, 255 }; + inline constexpr Color Verde { 80, 200, 120, 255 }; + inline constexpr Color Azul { 60, 120, 220, 255 }; + inline constexpr Color Amarillo { 240, 180, 40, 255 }; + inline constexpr Color Gris { 140, 140, 150, 255 }; + inline constexpr Color Fondo { 20, 24, 40, 255 }; +} + +class Dibujante +{ +public: + // Ancho / alto de una celda de la fuente bitmap (en pixeles, escala 1) + static constexpr int kAnchoGlifo = 5; + static constexpr int kAltoGlifo = 7; + + explicit Dibujante(SDL_Renderer* renderizador) noexcept : m_r(renderizador) {} + + // Limpia TODO el back buffer con un color plano (SetRenderDrawColor + RenderClear) + void Limpiar(Color c) const; + + void Punto(int x, int y, Color c) const; + void Linea(int x1, int y1, int x2, int y2, Color c) const; + void Rectangulo(const SDL_Rect& r, Color c) const; // solo el borde + void RectanguloRelleno(const SDL_Rect& r, Color c) const; + + // Texto con fuente 5x7. Soporta A-Z (las minusculas se dibujan como mayusculas), + // 0-9 y . , : - + / % ( ) ! ? = _ y espacio; '\n' baja de linea. + // Devuelve el ancho dibujado de la linea mas larga. + int Texto(int x, int y, const std::string& texto, Color c, int escala = 1) const; + + // Ancho en pixeles que ocuparia 'texto' (linea mas larga) con esa escala + static int AnchoTexto(const std::string& texto, int escala = 1) noexcept; + +private: + void Color_(Color c) const; + SDL_Renderer* m_r; +}; diff --git a/src/NucleoMotor.cpp b/src/NucleoMotor.cpp new file mode 100644 index 0000000..3f6d60c --- /dev/null +++ b/src/NucleoMotor.cpp @@ -0,0 +1,158 @@ +//------------------------------------------------------------------------------------ +// NucleoMotor (Modulo 2: Nucleo y bucle de juego con paso fijo) +// Codigo fuente C++ - NucleoMotor.cpp +//------------------------------------------------------------------------------------ +#include "NucleoMotor.h" + +#include +#include + +#ifdef __EMSCRIPTEN__ +#include +#endif + +//------------------------------------------------------------------------------------ +// Constructor / Destructor +//------------------------------------------------------------------------------------ +NucleoMotor::NucleoMotor(const ConfigMotor& config, Juego& juego) + : m_config(config) + , m_juego(juego) + , m_ventana(config.ventana) +{ + if (m_config.frecuencia == 0) + throw std::invalid_argument("NucleoMotor: la frecuencia debe ser > 0"); + if (m_config.maxPasosPorFrame == 0) + m_config.maxPasosPorFrame = 1; + + m_paso = 1000.0 / static_cast(m_config.frecuencia); +} + +NucleoMotor::~NucleoMotor() +{ + Terminar(); +} + +void NucleoMotor::Terminar() +{ + if (m_comenzado && !m_finalizado) + { + m_finalizado = true; + m_juego.Finalizar(); + } +} + +//------------------------------------------------------------------------------------ +// Bucle principal: nativo = while; navegador = callback asincrono +//------------------------------------------------------------------------------------ +bool NucleoMotor::Arrancar() +{ + if (!m_juego.Comenzar(*this)) + return false; + + m_comenzado = true; + m_ejecutando = true; + m_enEspera = !m_ventana.TieneFoco(); + m_acumulador = 0.0; + m_ultimoTick = SDL_GetTicks(); + return true; +} + +int NucleoMotor::Ejecutar() +{ + if (!Arrancar()) + return 1; + +#ifdef __EMSCRIPTEN__ + // fps = 0 -> usa requestAnimationFrame; simulate_infinite_loop = 0 -> main() + // retorna y el navegador sigue llamando al callback sin bloquear la pestana. + emscripten_set_main_loop_arg(&NucleoMotor::CallbackWeb, this, 0, 0); + return 0; +#else + while (m_ejecutando) + EjecutarFrame(); + + Terminar(); + return 0; +#endif +} + +#ifdef __EMSCRIPTEN__ +void NucleoMotor::CallbackWeb(void* arg) +{ + auto* motor = static_cast(arg); + motor->EjecutarFrame(); + + if (!motor->m_ejecutando) + { + emscripten_cancel_main_loop(); + motor->Terminar(); + } +} +#endif + +//------------------------------------------------------------------------------------ +// Un frame: eventos -> logica a paso fijo -> render +//------------------------------------------------------------------------------------ +void NucleoMotor::EjecutarFrame() +{ + // Aritmetica sin signo: correcta aunque SDL_GetTicks() desborde (~49 dias) + const std::uint32_t ahora = SDL_GetTicks(); + std::uint32_t delta = ahora - m_ultimoTick; + m_ultimoTick = ahora; + + // 1) Eventos de la plataforma + if (m_ventana.ProcesarEventos().salir) + m_ejecutando = false; + if (!m_ejecutando) + return; + + // 2) Pausa / reanudacion segun el foco (WM_KILLFOCUS / WM_SETFOCUS) + const bool foco = m_ventana.TieneFoco(); + if (!foco && !m_enEspera) + { + m_enEspera = true; + m_juego.Detener(); + } + else if (foco && m_enEspera) + { + m_enEspera = false; + m_acumulador = 0.0; // el tiempo en pausa no se "recupera" a rafagas + delta = 0; // ni siquiera el de este frame (incluye la espera en pausa) + m_juego.Reactivar(); + } + + if (m_enEspera) + { +#ifndef __EMSCRIPTEN__ + SDL_Delay(50); // sin foco: casi 0% de CPU (el navegador ya limita rAF) +#endif + return; + } + + // 3) Logica a tics fijos. El delta se acota para evitar la espiral de la muerte. + const double maxAcumulado = m_paso * static_cast(m_config.maxPasosPorFrame); + m_acumulador = std::min(m_acumulador + static_cast(delta), maxAcumulado); + + const double dt = m_paso / 1000.0; + while (m_ejecutando && m_acumulador >= m_paso) + { + m_juego.Actualizar(dt); + m_acumulador -= m_paso; + ++m_estadisticas.actualizaciones; + } + if (!m_ejecutando) + return; + + // 4) Renderizado libre: una vez por iteracion. Se limpia todo el back buffer, + // se pinta y se presenta (doble buffer de SDL: nunca se ve un frame a medias). + if (m_config.limpiarCadaFrame) + Dibujante(m_ventana.Renderizador()).Limpiar(m_config.colorFondo); + m_juego.Pintar(m_ventana.Renderizador()); + SDL_RenderPresent(m_ventana.Renderizador()); + ++m_estadisticas.frames; + +#ifndef __EMSCRIPTEN__ + if (!m_ventana.VsyncActivo()) + SDL_Delay(1); // sin vsync: no quemar un nucleo al 100% +#endif +} diff --git a/src/NucleoMotor.h b/src/NucleoMotor.h new file mode 100644 index 0000000..e9dea66 --- /dev/null +++ b/src/NucleoMotor.h @@ -0,0 +1,124 @@ +//------------------------------------------------------------------------------------ +// NucleoMotor (Modulo 2: Nucleo y bucle de juego con paso fijo) +// Encabezado C++ - NucleoMotor.h +//------------------------------------------------------------------------------------ +// - La logica se actualiza a tics fijos (por defecto 60 Hz) con un acumulador. +// - El renderizado es libre: una vez por iteracion del bucle. +// - Nativo: bucle while estandar. Navegador: emscripten_set_main_loop_arg +// (callback asincrono, nunca bloquea la pestana). +// - Sin Windows.h: el tiempo se mide con SDL_GetTicks(). +// +// IMPORTANTE (Emscripten): Ejecutar() registra el callback y DEVUELVE de inmediato. +// El NucleoMotor y el Juego deben tener duracion estatica (o en el heap), nunca +// vivir en la pila de main(), porque el bucle continua despues de que main() acabe. +//------------------------------------------------------------------------------------ +#pragma once + +#include "Dibujante.h" +#include "Ventana.h" + +#include + +class NucleoMotor; + +//------------------------------------------------------------------------------------ +// Interfaz que implementa el juego (sustituye a las antiguas funciones FJ_*) +//------------------------------------------------------------------------------------ +class Juego +{ +public: + virtual ~Juego() = default; + + // FJ_InicializarJuego + FJ_ComenzarJuego. Devolver false aborta el arranque. + virtual bool Comenzar(NucleoMotor& motor) = 0; + + // FJ_CicloJuego: un tic de logica a paso fijo. 'dt' son segundos (1/frecuencia). + virtual void Actualizar(double dt) = 0; + + // FJ_PintarJuego(HDC) -> FJ_PintarJuego(SDL_Renderer*). El motor limpia el fondo + // antes (ConfigMotor::colorFondo) y llama a SDL_RenderPresent() despues. + // Usa Dibujante(renderizador) para primitivas y texto. + virtual void Pintar(SDL_Renderer* renderizador) = 0; + + // FJ_DetenerJuego / FJ_ReactivarJuego: la ventana pierde / recupera el foco. + virtual void Detener() {} + virtual void Reactivar() {} + + // FJ_FinalizarJuego + virtual void Finalizar() {} +}; + +//------------------------------------------------------------------------------------ +// Configuracion y estadisticas +//------------------------------------------------------------------------------------ +struct ConfigMotor +{ + ConfigVentana ventana; + std::uint32_t frecuencia = 60; // tics de logica por segundo + std::uint32_t maxPasosPorFrame = 5; // evita la "espiral de la muerte" + + // Modulo 3: el motor limpia el back buffer con este color ANTES de cada Pintar(), + // de modo que ningun frame arrastra restos del anterior (causa tipica de parpadeo). + Color colorFondo = Colores::Fondo; + bool limpiarCadaFrame = true; +}; + +struct EstadisticasMotor +{ + std::uint64_t actualizaciones = 0; // tics de logica ejecutados + std::uint64_t frames = 0; // frames renderizados +}; + +//------------------------------------------------------------------------------------ +// Clase NucleoMotor +//------------------------------------------------------------------------------------ +class NucleoMotor +{ +public: + // 'juego' debe sobrevivir al motor. Lanza excepcion si la ventana falla. + NucleoMotor(const ConfigMotor& config, Juego& juego); + ~NucleoMotor(); + + NucleoMotor(const NucleoMotor&) = delete; + NucleoMotor& operator=(const NucleoMotor&) = delete; + + // Nativo: bloquea hasta que termina el juego y devuelve el codigo de salida. + // Web: registra el callback y devuelve 0 enseguida (ver nota de cabecera). + int Ejecutar(); + + // Llama a Juego::Comenzar y deja el motor listo para EjecutarFrame(). + // Ejecutar() ya lo invoca; es publico para poder avanzar frame a frame en pruebas. + bool Arrancar(); + + // Un frame completo: eventos -> N tics de logica -> pintar. Publico para pruebas. + void EjecutarFrame(); + + // Solicita terminar (equivalente a PostQuitMessage) + void Detener() noexcept { m_ejecutando = false; } + + bool EnEjecucion() const noexcept { return m_ejecutando; } + bool EnEspera() const noexcept { return m_enEspera; } // pausado por perdida de foco + + Ventana& ObtenerVentana() noexcept { return m_ventana; } + const EstadisticasMotor& Estadisticas() const noexcept { return m_estadisticas; } + std::uint32_t Frecuencia() const noexcept { return m_config.frecuencia; } + +private: + void Terminar(); // llama a Juego::Finalizar una sola vez +#ifdef __EMSCRIPTEN__ + static void CallbackWeb(void* arg); +#endif + + ConfigMotor m_config; + Juego& m_juego; + Ventana m_ventana; + + double m_paso = 0.0; // ms por tic de logica + double m_acumulador = 0.0; // ms pendientes de simular + std::uint32_t m_ultimoTick = 0; + bool m_ejecutando = false; + bool m_enEspera = false; + bool m_comenzado = false; + bool m_finalizado = false; + EstadisticasMotor m_estadisticas; +}; diff --git a/src/Ventana.cpp b/src/Ventana.cpp new file mode 100644 index 0000000..7eaf0ac --- /dev/null +++ b/src/Ventana.cpp @@ -0,0 +1,145 @@ +//------------------------------------------------------------------------------------ +// Ventana (Modulo 1: Plataforma y Ventana) +// Codigo fuente C++ - Ventana.cpp +//------------------------------------------------------------------------------------ +#include "Ventana.h" + +#include + +//------------------------------------------------------------------------------------ +// ContextoSdl +//------------------------------------------------------------------------------------ +Ventana::ContextoSdl::ContextoSdl() +{ + if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) != 0) + throw std::runtime_error(std::string("SDL_Init fallo: ") + SDL_GetError()); +} + +Ventana::ContextoSdl::~ContextoSdl() +{ + SDL_Quit(); +} + +//------------------------------------------------------------------------------------ +// Constructor: crea ventana y renderizador (reemplaza RegisterClassEx/CreateWindow) +//------------------------------------------------------------------------------------ +Ventana::Ventana(const ConfigVentana& config) + : m_config(config) +{ + if (m_config.ancho <= 0 || m_config.altura <= 0) + throw std::invalid_argument("Ventana: dimensiones invalidas"); + + m_ventana.reset(SDL_CreateWindow(m_config.titulo.c_str(), + SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, + m_config.ancho, m_config.altura, + SDL_WINDOW_SHOWN)); + if (!m_ventana) + throw std::runtime_error(std::string("SDL_CreateWindow fallo: ") + SDL_GetError()); + + // Renderizador acelerado; si no existe, se recurre al de software + Uint32 flags = SDL_RENDERER_ACCELERATED; + if (m_config.vsync) + flags |= SDL_RENDERER_PRESENTVSYNC; + + m_renderizador.reset(SDL_CreateRenderer(m_ventana.get(), -1, flags)); + if (!m_renderizador) + m_renderizador.reset(SDL_CreateRenderer(m_ventana.get(), -1, SDL_RENDERER_SOFTWARE)); + if (!m_renderizador) + throw std::runtime_error(std::string("SDL_CreateRenderer fallo: ") + SDL_GetError()); + + SDL_RendererInfo info; + if (SDL_GetRendererInfo(m_renderizador.get(), &info) == 0) + // El renderizador de software informa PRESENTVSYNC aunque no se pida: solo se + // considera activo si se solicito Y el renderizador lo confirma. + m_vsyncActivo = m_config.vsync && (info.flags & SDL_RENDERER_PRESENTVSYNC) != 0; +} + +//------------------------------------------------------------------------------------ +// Eventos (reemplaza WindowProc / TratarMensajes) +//------------------------------------------------------------------------------------ +EventosFrame Ventana::ProcesarEventos() +{ + EventosFrame resultado; + SDL_Event e; + + while (SDL_PollEvent(&e)) + { + switch (e.type) + { + case SDL_QUIT: + resultado.salir = true; + break; + + case SDL_WINDOWEVENT: + switch (e.window.event) + { + case SDL_WINDOWEVENT_CLOSE: + resultado.salir = true; + break; + case SDL_WINDOWEVENT_FOCUS_LOST: + m_tieneFoco = false; + LiberarEntrada(); // evita teclas "pegadas" al perder el foco + break; + case SDL_WINDOWEVENT_FOCUS_GAINED: + m_tieneFoco = true; + break; + default: + break; + } + break; + + case SDL_KEYDOWN: + if (m_config.escSale && e.key.keysym.scancode == SDL_SCANCODE_ESCAPE) + resultado.salir = true; + if (e.key.keysym.scancode < SDL_NUM_SCANCODES) + m_teclas[e.key.keysym.scancode] = true; + break; + + case SDL_KEYUP: + if (e.key.keysym.scancode < SDL_NUM_SCANCODES) + m_teclas[e.key.keysym.scancode] = false; + break; + + case SDL_MOUSEMOTION: + m_ratonX = e.motion.x; + m_ratonY = e.motion.y; + break; + + case SDL_MOUSEBUTTONDOWN: + m_ratonX = e.button.x; + m_ratonY = e.button.y; + m_botonesRaton |= SDL_BUTTON(e.button.button); + break; + + case SDL_MOUSEBUTTONUP: + m_ratonX = e.button.x; + m_ratonY = e.button.y; + m_botonesRaton &= ~SDL_BUTTON(e.button.button); + break; + + default: + break; + } + } + + return resultado; +} + +//------------------------------------------------------------------------------------ +// Entrada +//------------------------------------------------------------------------------------ +bool Ventana::TeclaPulsada(SDL_Scancode tecla) const noexcept +{ + return tecla >= 0 && tecla < SDL_NUM_SCANCODES && m_teclas[tecla]; +} + +bool Ventana::BotonRaton(std::uint8_t boton) const noexcept +{ + return (m_botonesRaton & SDL_BUTTON(boton)) != 0; +} + +void Ventana::LiberarEntrada() noexcept +{ + m_teclas.fill(false); + m_botonesRaton = 0; +} diff --git a/src/Ventana.h b/src/Ventana.h new file mode 100644 index 0000000..2e7097b --- /dev/null +++ b/src/Ventana.h @@ -0,0 +1,108 @@ +//------------------------------------------------------------------------------------ +// Ventana (Modulo 1: Plataforma y Ventana) +// Encabezado C++ - Ventana.h +//------------------------------------------------------------------------------------ +// Envoltorio RAII de SDL2: inicializa el subsistema de video/eventos, crea la +// ventana y el renderizador, traduce los eventos del sistema (cierre, foco, +// teclado y raton) y libera todo en orden inverso al destruirse. +// Sin dependencias de Windows; funciona en nativo y en Emscripten. +//------------------------------------------------------------------------------------ +#pragma once + +#include + +#include +#include +#include +#include + +//------------------------------------------------------------------------------------ +// Configuracion de la ventana +//------------------------------------------------------------------------------------ +struct ConfigVentana +{ + std::string titulo = "BasicGameEngine"; + int ancho = 640; + int altura = 480; + bool vsync = true; // se pide sincronizacion vertical si esta disponible + bool escSale = true; // ESC cierra el programa (en web conviene false) +}; + +//------------------------------------------------------------------------------------ +// Resultado de procesar la cola de eventos en un frame +//------------------------------------------------------------------------------------ +struct EventosFrame +{ + bool salir = false; // SDL_QUIT, cierre de ventana o tecla ESC +}; + +//------------------------------------------------------------------------------------ +// Clase Ventana +//------------------------------------------------------------------------------------ +class Ventana +{ +public: + // Lanza std::runtime_error si SDL no puede inicializarse o crear la ventana + explicit Ventana(const ConfigVentana& config); + ~Ventana() = default; + + Ventana(const Ventana&) = delete; + Ventana& operator=(const Ventana&) = delete; + Ventana(Ventana&&) = delete; + Ventana& operator=(Ventana&&) = delete; + + // Vacia la cola de eventos de SDL y actualiza el estado interno + EventosFrame ProcesarEventos(); + + // Acceso (no propietario) a los objetos de SDL + SDL_Window* VentanaSdl() const noexcept { return m_ventana.get(); } + SDL_Renderer* Renderizador() const noexcept { return m_renderizador.get(); } + + // Datos de la ventana + const std::string& Titulo() const noexcept { return m_config.titulo; } + int Ancho() const noexcept { return m_config.ancho; } + int Altura() const noexcept { return m_config.altura; } + bool VsyncActivo() const noexcept { return m_vsyncActivo; } + + // Foco de la ventana (SDL_WINDOWEVENT_FOCUS_GAINED / FOCUS_LOST) + bool TieneFoco() const noexcept { return m_tieneFoco; } + + // Entrada de teclado y raton + bool TeclaPulsada(SDL_Scancode tecla) const noexcept; + bool BotonRaton(std::uint8_t boton) const noexcept; // SDL_BUTTON_LEFT, ... + int RatonX() const noexcept { return m_ratonX; } + int RatonY() const noexcept { return m_ratonY; } + +private: + // Subsistema SDL: se declara primero para destruirse el ultimo + struct ContextoSdl + { + ContextoSdl(); + ~ContextoSdl(); + ContextoSdl(const ContextoSdl&) = delete; + ContextoSdl& operator=(const ContextoSdl&) = delete; + }; + + struct EliminaVentana + { + void operator()(SDL_Window* v) const noexcept { SDL_DestroyWindow(v); } + }; + struct EliminaRenderizador + { + void operator()(SDL_Renderer* r) const noexcept { SDL_DestroyRenderer(r); } + }; + + void LiberarEntrada() noexcept; + + ConfigVentana m_config; + ContextoSdl m_contexto; + std::unique_ptr m_ventana; + std::unique_ptr m_renderizador; + + bool m_vsyncActivo = false; + bool m_tieneFoco = true; + int m_ratonX = 0; + int m_ratonY = 0; + std::uint32_t m_botonesRaton = 0; + std::array m_teclas{}; +}; diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..7d39d2d --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,113 @@ +//------------------------------------------------------------------------------------ +// main.cpp - Juego de demostracion (nativo y Emscripten) +// - Cuadrado amarillo que rebota (logica a paso fijo, 60 Hz) +// - Cuadrado azul controlable con las flechas / WASD +// - Texto con FPS y tics de logica, rejilla de fondo y marco +//------------------------------------------------------------------------------------ +#include "NucleoMotor.h" + +#include +#include +#include +#include + +namespace +{ +class JuegoDemo : public Juego +{ +public: + bool Comenzar(NucleoMotor& motor) override + { + m_motor = &motor; + m_ventana = &motor.ObtenerVentana(); + m_ancho = m_ventana->Ancho(); + m_altura = m_ventana->Altura(); + m_jx = m_ancho / 2.0; + m_jy = m_altura / 2.0; + m_marcaFps = SDL_GetTicks(); + return true; + } + + void Actualizar(double dt) override + { + // Cuadrado que rebota + m_x += m_vx * dt; + m_y += m_vy * dt; + if (m_x < 0 || m_x + kLado > m_ancho) { m_vx = -m_vx; m_x = std::clamp(m_x, 0, m_ancho - kLado); } + if (m_y < 0 || m_y + kLado > m_altura) { m_vy = -m_vy; m_y = std::clamp(m_y, 0, m_altura - kLado); } + + // Cuadrado del jugador (flechas o WASD) + const Ventana& v = *m_ventana; + const double dx = (v.TeclaPulsada(SDL_SCANCODE_RIGHT) || v.TeclaPulsada(SDL_SCANCODE_D) ? 1 : 0) + - (v.TeclaPulsada(SDL_SCANCODE_LEFT) || v.TeclaPulsada(SDL_SCANCODE_A) ? 1 : 0); + const double dy = (v.TeclaPulsada(SDL_SCANCODE_DOWN) || v.TeclaPulsada(SDL_SCANCODE_S) ? 1 : 0) + - (v.TeclaPulsada(SDL_SCANCODE_UP) || v.TeclaPulsada(SDL_SCANCODE_W) ? 1 : 0); + m_jx = std::clamp(m_jx + dx * 260.0 * dt, 0, m_ancho - kLado); + m_jy = std::clamp(m_jy + dy * 260.0 * dt, 0, m_altura - kLado); + } + + void Pintar(SDL_Renderer* renderizador) override + { + const Dibujante d(renderizador); // el motor ya limpio el fondo + + // Rejilla + for (int x = 0; x <= m_ancho; x += 80) d.Linea(x, 0, x, m_altura, Color{ 36, 42, 66, 255 }); + for (int y = 0; y <= m_altura; y += 80) d.Linea(0, y, m_ancho, y, Color{ 36, 42, 66, 255 }); + + // Cuadrados + d.RectanguloRelleno(SDL_Rect{ int(m_x), int(m_y), kLado, kLado }, Colores::Amarillo); + d.RectanguloRelleno(SDL_Rect{ int(m_jx), int(m_jy), kLado, kLado }, Colores::Azul); + d.Rectangulo(SDL_Rect{ int(m_jx), int(m_jy), kLado, kLado }, Colores::Blanco); + d.Rectangulo(SDL_Rect{ 0, 0, m_ancho, m_altura }, Colores::Gris); + + // FPS (se recalcula cada segundo) + ++m_framesVentana; + const std::uint32_t ahora = SDL_GetTicks(); + if (ahora - m_marcaFps >= 1000) + { + m_fps = m_framesVentana * 1000.0 / (ahora - m_marcaFps); + m_framesVentana = 0; + m_marcaFps = ahora; + } + d.Texto(10, 10, "BASICGAMEENGINE", Colores::Blanco, 2); + d.Texto(10, 34, "FPS: " + std::to_string(int(m_fps + 0.5)) + + " LOGICA: " + std::to_string(m_motor->Frecuencia()) + " HZ", Colores::Verde, 1); + d.Texto(10, m_altura - 18, "FLECHAS / WASD: MOVER EL CUADRADO AZUL", Colores::Gris, 1); + } + +private: + static constexpr int kLado = 48; + NucleoMotor* m_motor = nullptr; + Ventana* m_ventana = nullptr; + int m_ancho = 0, m_altura = 0; + double m_x = 50, m_y = 90, m_vx = 180, m_vy = 130; // pixeles por segundo + double m_jx = 0, m_jy = 0; + std::uint32_t m_marcaFps = 0, m_framesVentana = 0; + double m_fps = 0; +}; +} // namespace + +int main(int, char**) +{ + try + { + ConfigMotor config; + config.ventana = ConfigVentana{ "BasicGameEngine", 640, 480, true, +#ifdef __EMSCRIPTEN__ + false // en el navegador ESC no cierra el juego (sale de pantalla completa) +#else + true +#endif + }; + + // Duracion estatica: en Emscripten el bucle sigue vivo cuando main() retorna. + static JuegoDemo juego; + static NucleoMotor motor(config, juego); + return motor.Ejecutar(); + } + catch (const std::exception& e) + { + std::cerr << "Error fatal: " << e.what() << std::endl; + return 1; + } +} diff --git a/tests/test_graficos.cpp b/tests/test_graficos.cpp new file mode 100644 index 0000000..eb58e1b --- /dev/null +++ b/tests/test_graficos.cpp @@ -0,0 +1,171 @@ +//------------------------------------------------------------------------------------ +// Pruebas de QA del Modulo 3 (Dibujante + limpieza/presentacion por frame) +// Se ejecutan sin pantalla: SDL_VIDEODRIVER=dummy, SDL_RENDER_DRIVER=software. +//------------------------------------------------------------------------------------ +#include "NucleoMotor.h" + +#include +#include + +static int g_fallos = 0; +#define CHECK(cond, msg) \ + do { \ + if (cond) std::printf(" [ OK ] %s\n", msg); \ + else { std::printf(" [FAIL] %s (%s:%d)\n", msg, __FILE__, __LINE__); ++g_fallos; } \ + } while (0) + +namespace +{ +constexpr int kAncho = 320, kAlto = 200, kLado = 32; +constexpr std::uint32_t Pack(Color c) { return 0xFF000000u | (c.r << 16) | (c.g << 8) | c.b; } +constexpr std::uint32_t kFondo = Pack(Colores::Fondo); +constexpr std::uint32_t kRojo = Pack(Colores::Rojo); + +// Lee el framebuffer actual del renderizador (ARGB8888) +std::vector Leer(SDL_Renderer* r) +{ + std::vector px(static_cast(kAncho) * kAlto, 0); + SDL_RenderReadPixels(r, nullptr, SDL_PIXELFORMAT_ARGB8888, px.data(), kAncho * 4); + return px; +} + +struct Analisis { int distintos = 0; bool coincide = false; }; + +// Cuenta pixeles distintos del fondo y comprueba que son exactamente el rectangulo esperado +Analisis Analizar(const std::vector& px, const SDL_Rect& esperado) +{ + Analisis a; + bool todoRojoDentro = true; + for (int y = 0; y < kAlto; ++y) + for (int x = 0; x < kAncho; ++x) + { + const std::uint32_t p = px[static_cast(y) * kAncho + x]; + const bool dentro = x >= esperado.x && x < esperado.x + esperado.w && + y >= esperado.y && y < esperado.y + esperado.h; + if (p != kFondo) ++a.distintos; + if (dentro && p != kRojo) todoRojoDentro = false; + if (!dentro && p != kFondo) todoRojoDentro = false; // resto/rastro fuera del rectangulo + } + a.coincide = todoRojoDentro; + return a; +} + +// Rectangulo que se mueve cada tic de logica; se verifica en cada frame +class JuegoFlicker : public Juego +{ +public: + int framesVerificados = 0, framesMalosBack = 0, framesMalosPresent = 0, posicionesDistintas = 0; + SDL_Rect ultimo{ 0, 0, kLado, kLado }; + + bool Comenzar(NucleoMotor&) override { return true; } + void Actualizar(double) override + { + m_x += 4; + if (m_x + kLado > kAncho) m_x = 0; + } + void Pintar(SDL_Renderer* r) override + { + const SDL_Rect nuevo{ m_x, 60 + (m_x / 8) % 40, kLado, kLado }; // se mueve en X e Y + if (nuevo.x != ultimo.x || nuevo.y != ultimo.y) ++posicionesDistintas; + ultimo = nuevo; + Dibujante(r).RectanguloRelleno(ultimo, Colores::Rojo); + + // Back buffer, antes de presentar + if (!Analizar(Leer(r), ultimo).coincide) ++framesMalosBack; + ++framesVerificados; + } + int m_x = 0; +}; + +// Ejecuta 'frames' frames a ~60 FPS reales y verifica tambien el buffer tras Present +void CorrerYVerificar(NucleoMotor& m, JuegoFlicker& j, int frames) +{ + m.Arrancar(); + while (j.framesVerificados < frames) + { + const int antes = j.framesVerificados; + m.EjecutarFrame(); + if (j.framesVerificados != antes && !Analizar(Leer(m.ObtenerVentana().Renderizador()), j.ultimo).coincide) + ++j.framesMalosPresent; + SDL_Delay(16); // ~60 FPS + } +} + +ConfigMotor Config(bool limpiar) +{ + ConfigMotor c; + c.ventana = ConfigVentana{ "grafico", kAncho, kAlto, false, true }; + c.limpiarCadaFrame = limpiar; + return c; +} + +//---------------------------------------------------------------- Test 3.1 +void Test_3_1_SinParpadeo() +{ + std::puts("Test 3.1: sin parpadeo ni rastros (back buffer y tras Present), ~60 FPS"); + { + JuegoFlicker j; NucleoMotor m(Config(true), j); + CorrerYVerificar(m, j, 120); + std::printf(" %d frames, %d posiciones distintas\n", j.framesVerificados, j.posicionesDistintas); + CHECK(j.framesMalosBack == 0, "back buffer: solo fondo + rectangulo exacto en los 120 frames"); + CHECK(j.framesMalosPresent == 0, "tras Present: identico al frame pintado en los 120 frames"); + CHECK(j.posicionesDistintas >= 100, "el rectangulo se mueve casi cada frame (animacion real)"); + } + { + // Control negativo: sin limpiar el fondo DEBEN aparecer rastros; si no, la prueba no sirve + JuegoFlicker j; NucleoMotor m(Config(false), j); + CorrerYVerificar(m, j, 30); + CHECK(j.framesMalosBack > 0, "control negativo: sin limpiar, la prueba detecta los rastros"); + } +} + +//---------------------------------------------------------------- Helpers de dibujo +void Test_3_x_Primitivas() +{ + std::puts("Test 3.2: primitivas y texto del Dibujante"); + Ventana v(ConfigVentana{ "prim", kAncho, kAlto, false, true }); + SDL_Renderer* r = v.Renderizador(); + const Dibujante d(r); + auto contar = [&] { int n = 0; for (auto p : Leer(r)) n += (p != kFondo); return n; }; + auto pix = [&](int x, int y) { return Leer(r)[static_cast(y) * kAncho + x]; }; + + d.Limpiar(Colores::Fondo); + CHECK(contar() == 0, "Limpiar deja todo el buffer con el color de fondo"); + + d.RectanguloRelleno(SDL_Rect{ 10, 10, 20, 10 }, Colores::Rojo); + CHECK(contar() == 200, "RectanguloRelleno 20x10 = 200 pixeles"); + + d.Limpiar(Colores::Fondo); + d.Rectangulo(SDL_Rect{ 10, 10, 20, 10 }, Colores::Rojo); + CHECK(contar() == 2 * 20 + 2 * 10 - 4, "Rectangulo (borde) 20x10 = 56 pixeles"); + + d.Limpiar(Colores::Fondo); + d.Linea(0, 5, 99, 5, Colores::Rojo); + CHECK(contar() == 100, "Linea horizontal de 100 pixeles"); + + d.Limpiar(Colores::Fondo); + d.Punto(7, 9, Colores::Rojo); + CHECK(contar() == 1 && pix(7, 9) == kRojo, "Punto dibuja exactamente un pixel"); + + d.Limpiar(Colores::Fondo); + const int ancho = d.Texto(20, 20, "0", Colores::Rojo, 2); + CHECK(ancho == 10, "Texto('0', escala 2) devuelve ancho 10"); + CHECK(pix(20 + 2 * 2, 20) == kRojo && pix(20, 20) == kFondo, "glifo '0': arriba-centro encendido, esquina apagada"); + CHECK(Dibujante::AnchoTexto("AB") == 11 && Dibujante::AnchoTexto("A\nABC") == 17, "AnchoTexto con y sin saltos de linea"); + + d.Limpiar(Colores::Fondo); + d.Texto(0, 0, "abc", Colores::Rojo); + const int minusculas = contar(); + d.Limpiar(Colores::Fondo); + d.Texto(0, 0, "ABC", Colores::Rojo); + CHECK(minusculas > 0 && minusculas == contar(), "las minusculas se dibujan como mayusculas"); +} +} // namespace + +int main() +{ + Test_3_1_SinParpadeo(); + Test_3_x_Primitivas(); + std::printf("\n%s (%d fallos)\n", g_fallos == 0 ? "TODAS LAS PRUEBAS PASARON" : "HAY FALLOS", g_fallos); + return g_fallos == 0 ? 0 : 1; +} diff --git a/tests/test_motor.cpp b/tests/test_motor.cpp new file mode 100644 index 0000000..8f388dc --- /dev/null +++ b/tests/test_motor.cpp @@ -0,0 +1,170 @@ +//------------------------------------------------------------------------------------ +// Pruebas de QA de los Modulos 1 y 2 (se ejecutan sin pantalla real: +// SDL_VIDEODRIVER=dummy, SDL_RENDER_DRIVER=software; ver CMakeLists.txt) +//------------------------------------------------------------------------------------ +#include "NucleoMotor.h" + +#include +#include +#include +#include + +static int g_fallos = 0; +#define CHECK(cond, msg) \ + do { \ + if (cond) std::printf(" [ OK ] %s\n", msg); \ + else { std::printf(" [FAIL] %s (%s:%d)\n", msg, __FILE__, __LINE__); ++g_fallos; } \ + } while (0) + +namespace +{ +class JuegoPrueba : public Juego +{ +public: + std::uint32_t retardoPintarMs = 0; // simula un render lento + std::uint64_t pausas = 0, reanudaciones = 0, pintados = 0; + std::uint64_t paraAlLlegar = 0; // si > 0: pide SDL_QUIT al alcanzar N tics + bool finalizado = false; + std::uint64_t tics = 0; + + bool Comenzar(NucleoMotor&) override { return true; } + void Actualizar(double) override + { + if (++tics == paraAlLlegar) + { + SDL_Event e{}; e.type = SDL_QUIT; SDL_PushEvent(&e); + } + } + void Pintar(SDL_Renderer* r) override + { + ++pintados; + SDL_SetRenderDrawColor(r, 0, 0, 0, 255); + SDL_RenderClear(r); + if (retardoPintarMs) SDL_Delay(retardoPintarMs); + } + void Detener() override { ++pausas; } + void Reactivar() override { ++reanudaciones; } + void Finalizar() override { finalizado = true; } +}; + +ConfigMotor Config(bool vsync = false) +{ + return ConfigMotor{ ConfigVentana{ "Titulo de prueba", 320, 200, vsync }, 60, 5 }; +} + +void PushFoco(Uint8 evento) +{ + SDL_Event e{}; + e.type = SDL_WINDOWEVENT; + e.window.event = evento; + SDL_PushEvent(&e); +} + +// Ejecuta frames durante 'ms' milisegundos reales +void Correr(NucleoMotor& m, std::uint32_t ms) +{ + const std::uint32_t t0 = SDL_GetTicks(); + while (SDL_GetTicks() - t0 < ms) m.EjecutarFrame(); +} + +//---------------------------------------------------------------- Test 1.1 +void Test_1_1_VentanaSeAbre() +{ + std::puts("Test 1.1: ventana con titulo y resolucion configurados"); + JuegoPrueba j; + NucleoMotor m(Config(), j); + m.Arrancar(); + SDL_Window* v = m.ObtenerVentana().VentanaSdl(); + int w = 0, h = 0; + SDL_GetWindowSize(v, &w, &h); + CHECK(v != nullptr && m.ObtenerVentana().Renderizador() != nullptr, "ventana y renderizador creados"); + CHECK(std::string(SDL_GetWindowTitle(v)) == "Titulo de prueba", "titulo correcto"); + CHECK(w == 320 && h == 200, "resolucion 320x200"); +} + +//---------------------------------------------------------------- Test 1.2 +void Test_1_2_Cierre() +{ + std::puts("Test 1.2: cierre por SDL_QUIT / ESC / ventana y liberacion limpia"); + { // SDL_QUIT durante Ejecutar() (bucle nativo completo) + JuegoPrueba j; j.paraAlLlegar = 10; + NucleoMotor m(Config(), j); + const int codigo = m.Ejecutar(); + CHECK(codigo == 0 && !m.EnEjecucion(), "SDL_QUIT termina Ejecutar() con codigo 0"); + CHECK(j.finalizado, "Juego::Finalizar() se llamo"); + } + { // ESC + JuegoPrueba j; + Ventana v(ConfigVentana{ "esc", 100, 100, false }); + SDL_Event e{}; e.type = SDL_KEYDOWN; e.key.keysym.scancode = SDL_SCANCODE_ESCAPE; + SDL_PushEvent(&e); + CHECK(v.ProcesarEventos().salir, "tecla ESC solicita salir"); + } + { // Boton de cierre de la ventana + Ventana v(ConfigVentana{ "x", 100, 100, false }); + PushFoco(SDL_WINDOWEVENT_CLOSE); + CHECK(v.ProcesarEventos().salir, "boton X (WINDOWEVENT_CLOSE) solicita salir"); + } + { // Crear/destruir varias veces: sin fugas (verificado con ASan/LSan) + for (int i = 0; i < 5; ++i) { JuegoPrueba j; NucleoMotor m(Config(), j); m.Arrancar(); m.EjecutarFrame(); } + CHECK(true, "5 ciclos crear/destruir sin errores (ASan/LSan detectaria fugas)"); + } +} + +//---------------------------------------------------------------- Test 1.3 +void Test_1_3_Foco() +{ + std::puts("Test 1.3: perdida y recuperacion de foco"); + JuegoPrueba j; + NucleoMotor m(Config(), j); + m.Arrancar(); + + Correr(m, 200); + CHECK(j.tics > 0 && !m.EnEspera(), "con foco la logica avanza"); + + PushFoco(SDL_WINDOWEVENT_FOCUS_LOST); + m.EjecutarFrame(); + CHECK(m.EnEspera() && j.pausas == 1, "FOCUS_LOST pausa el motor y llama a Juego::Detener"); + + const std::uint64_t ticsPausa = j.tics, pintadosPausa = j.pintados; + const std::uint32_t t0 = SDL_GetTicks(); + std::uint64_t iteraciones = 0; + while (SDL_GetTicks() - t0 < 500) { m.EjecutarFrame(); ++iteraciones; } + CHECK(j.tics == ticsPausa && j.pintados == pintadosPausa, "en pausa no hay logica ni render"); + CHECK(iteraciones < 30, "en pausa el bucle duerme (poca CPU: <30 iteraciones en 500 ms)"); + + PushFoco(SDL_WINDOWEVENT_FOCUS_GAINED); + m.EjecutarFrame(); + CHECK(!m.EnEspera() && j.reanudaciones == 1, "FOCUS_GAINED reanuda y llama a Juego::Reactivar"); + CHECK(j.tics - ticsPausa <= 1, "al reanudar no hay rafaga de tics por el tiempo en pausa"); +} + +//---------------------------------------------------------------- Test 2.1 +void Test_2_1_FrameratEstable() +{ + std::puts("Test 2.1: tasa logica estable (60 Hz) aunque el render fluctue"); + for (std::uint32_t retardo : { 0u, 10u, 30u }) + { + JuegoPrueba j; j.retardoPintarMs = retardo; + NucleoMotor m(Config(), j); + m.Arrancar(); + const std::uint32_t t0 = SDL_GetTicks(); + Correr(m, 2000); + const double seg = (SDL_GetTicks() - t0) / 1000.0; + const double hz = static_cast(m.Estadisticas().actualizaciones) / seg; + const double fps = static_cast(m.Estadisticas().frames) / seg; + std::printf(" render=%2u ms/frame -> logica %.1f Hz, render %.1f fps\n", retardo, hz, fps); + CHECK(std::fabs(hz - 60.0) <= 2.0, "logica = 60 Hz +/- 2"); + } +} +} // namespace + +int main() +{ + Test_1_1_VentanaSeAbre(); + Test_1_2_Cierre(); + Test_1_3_Foco(); + Test_2_1_FrameratEstable(); + std::printf("\n%s (%d fallos)\n", g_fallos == 0 ? "TODAS LAS PRUEBAS PASARON" : "HAY FALLOS", g_fallos); + return g_fallos == 0 ? 0 : 1; +} diff --git a/web/minimal_shell.html b/web/minimal_shell.html new file mode 100644 index 0000000..3fbd0ee --- /dev/null +++ b/web/minimal_shell.html @@ -0,0 +1,128 @@ + + + + + + BasicGameEngine + + + +

BasicGameEngine

+ +
+ +
+
Cargando…
+
+
+ +
+ + Flechas / WASD para mover el cuadrado azul. Haz clic en el juego para darle el foco. + + + + {{{ SCRIPT }}} + +