Warning: Undefined array key "HTTP_ACCEPT_LANGUAGE" in /var/www/vhosts/bilgigunlugum.net/httpdocs/index.php on line 43
SDL Oyun Programlama

SDL3 Oyun Programlama sayfalarımız yayında...

Ana sayfa > Oyun programlama > SDL3 programming > SDL3 basic program

SDL3 basic program

In this section, we create a basic template that we use continuously in the SDL3 programs with the C Programming Language. New code lines will be added to this template at each new step.

The program creates a rectangle with dimensions of 160 x 120 pixels, exactly in the middle of the main window it creates.

The template we will create will contain the codes that will perform the operations shown below:

  1. At the beginning of the program, the global variables shown below are first defined:
    • WINDOW_WIDTH: A macro that shows the window size.
    • WINDOW_HEIGHT: A macro that shows the window height.
    • is_running: An integer variable that determines whether the while loop, which is the main loop of the program, will continue to run.
    • window: SDL_Window variable defined for the program main window.
    • renderer: SDL_Renderer variable used to render images.
  2. Function prototypes that we will use as standard in all the codes we will develop are defined. Some of the functions will not contain any code if they are not used:
    • int init_window(void): It is run only once at the beginning of the program, initializes the SDL library, and creates the program's main window and 2D renderer.
    • void init_vals(void): It is run only once at the beginning of the program, and is used to assign initial values ​​to variables in the program.
    • void process_event(void): It is run once at each iteration of the program's main loop, and processes user inputs.
    • void update_screen(): It is run once at each iteration of the program's main loop, and adjusts variable values ​​according to user inputs or automatically changing values.
    • void draw_screen(void): It is executed once in each iteration of the program's main loop and draws the main window.
    • void destroy_window(void): It exits SDL by destroying the renderer variable and the SDL window.
  3. In the main function that comes into play with the program execution,
    • The init_window() function is run,
      • The SDL library is initialized with the SDL_Init() function.
      • The program's main window is created with the SDL_CreateWindow() function.
      • A 2D renderer is created with the SDL_CreateRenderer() function.
      • If all three operations shown above are successful, the value true is entered, otherwise the value false is entered into the is_running variable. If this variable is false, the program ends without entering the main loop.
    • The init_vals() function is run to initialize the program variables, if any.
    • The while loop, which is the main loop of the program, is entered. This loop repeats as long as the user does not terminate the program, and performs the following operations on each iteration:
      • The process_event() function is run,
        • An SDL_Event variable named event is created.
        • A while loop that processes user inputs is created with the SDL_PollEvent() function.
        • An SDL_Event variable named event is created.
        • When the user clicks the close button in the upper right corner of the program's main window, the SDL_EVENT_QUIT option is activated, and when the user presses the ESC key, the SDL_EVENT_KEY_DOWN option is activated, and the is_running variable is assigned the value false. In this case, the program ends because the variable that ensures the repetition of the while loop is false.
      • The update_screen() function is run, and if there are any, the variable values ​​are set according to user inputs or automatically changing values.
      • The draw_screen() function is run,
        • The color for drawing operations is set with the SDL_SetRenderDrawColor() function.
        • The background is painted with the selected color with the SDL_RenderClear() function.
        • A rectangle is defined with the frect variable of the SDL_FRect variable type, with the size of 160 x 120 pixels and located in the exact center of the main window.
        • The rectangle fill color is defined with the SDL_SetRenderDrawColor() function.
        • The rectangle is created with the selected color with the SDL_RenderFillRect() function and painted.
        • With the SDL_RenderPresent() function, all objects drawn one by one in the back buffer are loaded into the front buffer and the screen at the same time. This process prevents each drawn object from being displayed on the screen one by one. All operations performed since the previous call are updated on the screen.
      • The destroy_window() function is run,
        • The renderer is destroyed with the SDL_DestroyRenderer() function.
        • The program main window is destroyed with the SDL_DestroyWindow() function.
        • The SDL_Quit() function exits SDL.

main.c file content will be as follows:


#include <SDL3/SDL.h>

// Window width and height
#define WINDOW_WIDTH 640
#define WINDOW_HEIGHT 480

// Global variables
int is_running = false;        // Variable that controls the execution of the main loop of the program
SDL_Window *window = NULL;     // Main window variable
SDL_Renderer *renderer = NULL; // Renderer variable

// Function prototypes
int init_window(void);         // Create window and renderer
void init_vals(void);          // Initialize values
void process_event(void);      // Process events
void update_screen();          // Update values
void draw_screen(void);        // Draw screen
void destroy_window(void);     // Destroy window

int main(int argc, char* argv[])
{
    // Create window and renderer
    is_running = init_window();

    // Initialize values
    init_vals();

    // Main loop
    while (is_running) {
        process_event();       // Processing SDL events (Here keyboard inputs).
        update_screen();       // Updating variables
        draw_screen();         // Drawing objects on the window (Rendering)
    }

    // Destroy renderer and SDL window
    destroy_window();

    return 0;
}

// Create window and renderer
int init_window(void)
{
    // Initialize the SDL library.
    if(SDL_Init(SDL_INIT_VIDEO) == false) {
       SDL_Log("SDL init error: %s\n", SDL_GetError());
       return false;
    }

    // Create a window with the specified dimensions and flags.
    window = SDL_CreateWindow("SDL3 window", 640, 480, SDL_WINDOW_OPENGL);

    // Check window
    if(window == NULL) {
       SDL_Log("Window creation error: %s\n", SDL_GetError());
       return false;
    }

    // Create a 2D rendering context for the window.
    renderer = SDL_CreateRenderer(window, NULL);

    // Check renderer
    if(renderer == NULL) {
       SDL_Log("Renderer creation error: %s\n", SDL_GetError());
       return false;
    }

    return true;
}

// Initialization function that runs only once at the beginning of the program
void init_vals(void)
{

}

// Function to control SDL events and process keyboard inputs
void process_event(void)
{
     SDL_Event event;

     // Creating a loop to process user inputs
     while (SDL_PollEvent(&event)) {
        switch (event.type) {
            case SDL_EVENT_QUIT: // Logout action by the user (x button at the top right of the window)
                 is_running = false; // Terminates the execution of the program main loop.
                 break;

            case SDL_EVENT_KEY_DOWN: // Indicate that a key was pressed.
                 if(event.key.key == SDLK_ESCAPE) { // Indicates that the pressed key is the Esc key.
                    is_running = false; // Terminates the execution of the program main loop.
                 }
                 break;
        }
     }
}

// Updates objects in the main window
void update_screen(void)
{

}

// Render function used to draw game objects in the main window
void draw_screen(void)
{
     SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); // Set the color used for drawing operations.
     SDL_RenderClear(renderer); // Clear the current rendering target with the drawing color.

     // Setting rectangle dimensions
     SDL_FRect frect = { (WINDOW_WIDTH-160)/2, (WINDOW_HEIGHT-120)/2, 160, 120 };
     SDL_SetRenderDrawColor(renderer, 255, 0, 255, 255); // Set the color to fill rectangle.
     SDL_RenderFillRect(renderer, &frect); // Fill a rectangle on the current rendering target with the drawing color at subpixel precision.

     // Loading all objects drawn one by one to the back buffer to the front buffer at once and loading them onto the screen
     // This process prevents each drawn object from being displayed on the screen one by one.
     SDL_RenderPresent(renderer); // Update on screen all operations performed since the previous call
}

// Destroy Renderer and SDL window, exit from SDL3
void destroy_window(void)
{
     SDL_DestroyRenderer(renderer);
     SDL_DestroyWindow(window);
     SDL_Quit();
}