wander.c 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdbool.h>
  4. #include <SDL2/SDL.h>
  5. typedef struct {
  6. SDL_Window *win;
  7. SDL_Renderer *ren;
  8. SDL_Event *ev;
  9. bool is_initialized;
  10. int flags;
  11. bool running;
  12. } env;
  13. typedef struct {
  14. int x;
  15. int y;
  16. } vec2d;
  17. bool init_env(
  18. env *env,
  19. int sdl_flags,
  20. char* win_name,
  21. vec2d win_size,
  22. int renderer_flags)
  23. {
  24. if (env->is_initialized)
  25. return false;
  26. SDL_Init(sdl_flags);
  27. env->flags = sdl_flags;
  28. env->win = SDL_CreateWindow(win_name,
  29. SDL_WINDOWPOS_UNDEFINED,
  30. SDL_WINDOWPOS_UNDEFINED,
  31. win_size.x,
  32. win_size.y,
  33. SDL_WINDOW_OPENGL);
  34. if (!env->win) {
  35. fprintf(stderr, "could not create window: %s\n", SDL_GetError());
  36. return false;
  37. }
  38. env->ren = SDL_CreateRenderer(env->win,
  39. -1,
  40. renderer_flags);
  41. if (!env->win) {
  42. fprintf(stderr, "could not create renderer: %s\n", SDL_GetError());
  43. return false;
  44. }
  45. env->running = false;
  46. return true;
  47. }
  48. void process_event(env *env){
  49. switch(env->ev->type)
  50. {
  51. case SDL_QUIT:
  52. env->running = false;
  53. break;
  54. }
  55. }
  56. void run(env *env)
  57. {
  58. if (!env->is_initialized) {
  59. fprintf(stderr, "event not initialized.");
  60. return;
  61. }
  62. env->running = true;
  63. while (env->running) {
  64. while(SDL_PollEvent(env->ev))
  65. process_event(env);
  66. }
  67. }
  68. void destroy_env(env *env)
  69. {
  70. env->is_initialized = false;
  71. SDL_DestroyRenderer(env->ren);
  72. SDL_DestroyWindow(env->win);
  73. env->flags = 0;
  74. }
  75. int main(int argc, char** argv)
  76. {
  77. env e;
  78. e.is_initialized = false;
  79. vec2d win_size = { .x = 800, .y = 600 };
  80. if (init_env(&e,
  81. SDL_INIT_VIDEO,
  82. "Wander",
  83. win_size,
  84. SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC)){
  85. fprintf(stdout, "cannot initialize, exiting\n");
  86. return 1;
  87. }
  88. run(&e);
  89. destroy_env(&e);
  90. }