renderer-clear.c 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. * This example code creates an SDL window and renderer, and then clears the
  3. * window to a different color every frame, so you'll effectively get a window
  4. * that's smoothly fading between colors.
  5. *
  6. * This code is public domain. Feel free to use it for any purpose!
  7. */
  8. #define SDL_MAIN_USE_CALLBACKS 1 /* use the callbacks instead of main() */
  9. #include <SDL3/SDL.h>
  10. #include <SDL3/SDL_main.h>
  11. /* We will use this renderer to draw into this window every frame. */
  12. static SDL_Window *window = NULL;
  13. static SDL_Renderer *renderer = NULL;
  14. /* the current red color we're clearing to. */
  15. static Uint8 red = 0;
  16. /* When fading up, this is 1, when fading down, it's -1. */
  17. static int fade_direction = 1;
  18. /* This function runs once at startup. */
  19. int SDL_AppInit(void **appstate, int argc, char *argv[])
  20. {
  21. if (SDL_CreateWindowAndRenderer("examples/renderer/clear", 640, 480, 0, &window, &renderer) == -1) {
  22. SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Couldn't create window/renderer!", SDL_GetError(), NULL);
  23. return SDL_APP_FAILURE;
  24. }
  25. SDL_SetRenderVSync(renderer, 1); /* try to show frames at the monitor refresh rate. */
  26. return SDL_APP_CONTINUE; /* carry on with the program! */
  27. }
  28. /* This function runs when a new event (mouse input, keypresses, etc) occurs. */
  29. int SDL_AppEvent(void *appstate, const SDL_Event *event)
  30. {
  31. if (event->type == SDL_EVENT_QUIT) {
  32. return SDL_APP_SUCCESS; /* end the program, reporting success to the OS. */
  33. }
  34. return SDL_APP_CONTINUE; /* carry on with the program! */
  35. }
  36. /* This function runs once per frame, and is the heart of the program. */
  37. int SDL_AppIterate(void *appstate)
  38. {
  39. /* since we're always fading red, we leave green and blue at zero.
  40. alpha doesn't mean much here, so leave it at full (255, no transparency). */
  41. SDL_SetRenderDrawColor(renderer, red, 0, 0, 255);
  42. /* clear the window to the draw color. */
  43. SDL_RenderClear(renderer);
  44. /* put the newly-cleared rendering on the screen. */
  45. SDL_RenderPresent(renderer);
  46. /* update the color for the next frame we will draw. */
  47. if (fade_direction > 0) {
  48. if (red == 255) {
  49. fade_direction = -1;
  50. } else {
  51. red++;
  52. }
  53. } else if (fade_direction < 0) {
  54. if (red == 0) {
  55. fade_direction = 1;
  56. } else {
  57. red--;
  58. }
  59. }
  60. return SDL_APP_CONTINUE; /* carry on with the program! */
  61. }
  62. /* This function runs once at shutdown. */
  63. void SDL_AppQuit(void *appstate)
  64. {
  65. /* SDL will clean up the window/renderer for us. */
  66. }