SDL little example

 avatar
unknown
c_cpp
a month ago
1.6 kB
7
Indexable
#include <stdio.h>
#include <stdlib.h>

#include <SDL3/SDL.h>
#include <SDL3/SDL_opengl.h>

SDL_Window* window = NULL;
SDL_GLContext glcontext = NULL;

void panicError() {
	SDL_GL_DestroyContext(glcontext);
	SDL_DestroyWindow(window);
	SDL_Quit();
	exit(EXIT_FAILURE);
}

int main(int argc, char *argv[]) {
	int value = 0;
	bool run = false;
	const int WIDTH = 640;
	const int HEIGHT = 480;

	SDL_SetHint(SDL_HINT_RENDER_VSYNC, 0);
		if (!SDL_Init(SDL_INIT_VIDEO)) {
		SDL_Log("SDL_Init failed: %s.", SDL_GetError());
		panicError();
	}

	if (!SDL_GL_SetAttribute(SDL_GL_CONTEXT_RELEASE_BEHAVIOR, SDL_GL_CONTEXT_RELEASE_BEHAVIOR_NONE)) {
		SDL_Log("ERROR: %s", SDL_GetError());
		panicError();
	}

	window = SDL_CreateWindow("Hello SDL", WIDTH, HEIGHT, SDL_WINDOW_OPENGL| SDL_WINDOW_RESIZABLE);
	if (!window) {
		SDL_Log("SDL_CreateWindow: %s.", SDL_GetError());
		panicError();
	}
	
	glcontext = SDL_GL_CreateContext(window);
	if (!glcontext) {
		SDL_Log("SDL_GL_CreateContext: %s.", SDL_GetError());
		panicError();
	}

	SDL_GL_GetAttribute(SDL_GL_CONTEXT_RELEASE_BEHAVIOR, &value);
	SDL_Log("OpenGL Release: %d", value);

	while (!run) {
		SDL_Event e;
		SDL_zero(e);
		while (SDL_PollEvent(&e)) {
			if (e.type == SDL_EVENT_QUIT) {
				run = true;
			}
			else if (e.type == SDL_EVENT_KEY_DOWN) {
					if (e.key.key == SDLK_ESCAPE)
					run = true;
			}
		}
		if (!SDL_GL_SwapWindow(window)) {
			SDL_Log("SDL_GL_SwapWwindow: %s.", SDL_GetError());
			panicError();
		}
	}
	SDL_DestroyWindow(window);
	SDL_GL_DestroyContext(glcontext);
	SDL_Quit();
	exit(EXIT_SUCCESS);
}