#include "SDL2/SDL_events.h" #include "SDL2/SDL_timer.h" #include "backend.h" #include "defs.h" #include "logger.h" #include #include typedef struct { SDL_Window *window; SDL_Surface *surface; } SDL_Internal; inline f32 backend_get_time(void) { return SDL_GetTicks64() / 1000.0; }; bool backend_init(ve_context *ctx, const char *title, u32 w, u32 h) { if (SDL_Init(SDL_INIT_VIDEO) < 0) return false; logger_log("SDL INIT", INFO); SDL_Internal *sdl = malloc(sizeof(SDL_Internal)); sdl->window = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, w, h, SDL_WINDOW_SHOWN); sdl->surface = SDL_GetWindowSurface(sdl->window); ctx->internal_data = sdl; ctx->ve_fb.pixels = (u32 *)sdl->surface->pixels; ctx->ve_fb.width = w; ctx->ve_fb.height = h; ctx->ve_fb.pitch = sdl->surface->pitch; ctx->last_time = backend_get_time(); logger_log("VOID CONTEXT INIT", INFO); char max_fps_str[64]; snprintf(max_fps_str, sizeof(max_fps_str), "MAX FPS: %d", MAX_FPS); logger_log(max_fps_str, INFO); return true; } void backend_update(ve_context *ctx) { SDL_Internal *sdl = (SDL_Internal *)ctx->internal_data; SDL_UpdateWindowSurface(sdl->window); f32 current_time = backend_get_time(); ctx->dt = current_time - ctx->last_time; // Calcular cuánto tiempo esperar para mantener 120 FPS f32 frame_time = ctx->dt * 1000.0; // Convertir a ms if (frame_time < FRAME_TIME_MS) { u32 delay_time = (u32)(FRAME_TIME_MS - frame_time); SDL_Delay(delay_time); // Actualizar el tiempo después del delay current_time = SDL_GetTicks64() / 1000.0; ctx->dt = current_time - ctx->last_time; } ctx->last_time = current_time; } void backend_cleanup(ve_context *ctx) { SDL_Internal *sdl = (SDL_Internal *)ctx->internal_data; SDL_DestroyWindow(sdl->window); SDL_Quit(); free(sdl); logger_log("VOID CLEANUP", INFO); logger_log("WINDOW DESTROY", INFO); logger_log("SDL QUIT", INFO); } bool backend_event_loop(ve_context *ctx) { SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: backend_cleanup(ctx); return false; break; case SDL_KEYDOWN: char fps_str[64]; u32 fps = 1 / ctx->dt; snprintf(fps_str, sizeof(fps_str), "fps: %d", fps); logger_log(fps_str, DEBUG); break; default: break; }; } backend_update(ctx); return true; }