Math_lol/sdlinit.c
2025-02-14 12:59:12 +01:00

119 lines
3.5 KiB
C

#include <SDL2/SDL.h>
#include <SDL2/SDL_events.h>
extern void keydownHandler(SDL_Scancode);
/* Predefined Screen Size */
#define SCREEN_WIDTH 640
#define SCREEN_HEIGHT 480
static float sdlUpdate = 33.f;
/* Video Memory */
static uint32_t videoMemory[SCREEN_WIDTH * SCREEN_HEIGHT];
/* SDL static stuff */
static SDL_Window *window;
static SDL_Renderer *renderer;
static SDL_Texture *texture;
static SDL_Cursor *cursor;
static SDL_Event event;
/* Function to init the SDL Window and dependencies */
void initWindow(){
if (SDL_Init(SDL_INIT_VIDEO)){
printf("Could not init SDL: %s\n", SDL_GetError());
exit(EXIT_FAILURE);
}
/* When we exit(CODE), then SDL_Quit is ran */
atexit(SDL_Quit);
/* Init Window */
window = SDL_CreateWindow("Program",
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
SCREEN_WIDTH, SCREEN_HEIGHT, 0);
if (window == NULL){
printf("Fatal! Could not create SDL Window: %s\n", SDL_GetError());
exit(EXIT_FAILURE);
}
/* Init Renderer */
renderer = SDL_CreateRenderer(window, -1, 2);
if (renderer == NULL){
printf("Fatal! Could not create SDL Renderer: %s\n", SDL_GetError());
exit(EXIT_FAILURE);
}
/* Init Texture */
texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888,
SDL_TEXTUREACCESS_STREAMING,
SCREEN_WIDTH, SCREEN_HEIGHT);
if (texture == NULL){
printf("Fatal! Could not create SDL Texture: %s\n", SDL_GetError());
exit(EXIT_FAILURE);
}
if (SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_NONE)){
printf("Fatal! Could not set SDL blend mode: %s\n", SDL_GetError());
exit(EXIT_FAILURE);
}
/* Init the Cursor */
cursor = SDL_CreateSystemCursor(0);
if (cursor == NULL){
printf("Fatal! Could not create SDL cursor: %s\n", SDL_GetError());
exit(EXIT_FAILURE);
}
SDL_SetCursor(cursor);
}
/* Clear the framebuffer with a color */
void clearScreen(uint32_t pixels[], uint32_t color){
for (uint32_t i = 0; i < SCREEN_WIDTH * SCREEN_HEIGHT; i++) pixels[i] = color;
}
/* Get next events and do sm with it */
void pollEvents(){
while (SDL_PollEvent(&event)){
switch(event.type){
/* If Quit, we quit the Application lul */
case SDL_QUIT:
printf("Quit at users request\n");
exit(EXIT_SUCCESS);
break;
/* Fetch pressed Keys */
case SDL_KEYDOWN:
switch (event.key.keysym.scancode){
case SDL_SCANCODE_ESCAPE:
printf("Quit at users request\n");
exit(0);
break;
default:
keydownHandler(event.key.keysym.scancode);
break;
}
break;
default:
break;
}
}
}
/* Update SDL Texture and Renderer with framebuffer */
void updateSDL(){
if (SDL_UpdateTexture(texture, NULL, videoMemory, (sizeof(uint32_t) * SCREEN_WIDTH))) {
fprintf(stderr, "Could not update SDL texture: %s.\n", SDL_GetError());
exit(EXIT_FAILURE);
}
if (SDL_RenderCopy(renderer, texture, NULL, NULL)) {
fprintf(stderr, "Could not display SDL texture: %s.\n", SDL_GetError());
exit(EXIT_FAILURE);
}
}