Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

Write a program in C and SDL2. This program displays the ./map/world/background.png…

  1. User

    Write a program in C and SDL2. This program displays the ./map/world/background.png image in a window called "OpenAge MapEditor". The program should implement a smooth zoom when scrolling the mouse wheel. The target of the zoom should be the cursor position. When right-clicking and dragging, the camera can be moved smoothly. The camera should never go beyond the image boundaries when zooming and moving. The aspect ratio of the view area should always be as the aspect ratio of the window. The main file is Editor.c Camera control file - EditorCamera.c and EditorCamera.h

  2. Assistant

    Certainly! Below is a complete C program using SDL2 that fulfills your requirements. The program is divided into three files:

    1. EditorCamera.h - Header file for camera controls.
    2. EditorCamera.c - Implementation of camera controls.
    3. Editor.c - Main file that initializes SDL, handles events, and renders the image.

    Prerequisites

    Before compiling the code, ensure you have the following installed:

    • SDL2
    • SDL2_image

    You can install these on most systems using package managers. For example, on Ubuntu:

    sudo apt-get install libsdl2-dev libsdl2-image-dev
    

    Directory Structure

    Assuming your project directory looks like this:

    /project
    │
    ├── Editor.c
    ├── EditorCamera.h
    ├── EditorCamera.c
    └── map
        └── world
            └── background.png
    

    1. EditorCamera.h

    This header file declares the Camera structure and associated functions for handling camera operations like zooming and panning.

    // EditorCamera.h
    #ifndef EDITOR_CAMERA_H
    #define EDITOR_CAMERA_H
    
    #include <SDL.h>
    
    typedef struct {
        float x;          // Camera position X
        float y;          // Camera position Y
        float zoom;       // Zoom level (scale)
        int window_width; // Window width in pixels
        int window_height;// Window height in pixels
        int img_width;    // Image (background) width in pixels
        int img_height;   // Image (background) height in pixels
    } Camera;
    
    // Initializes the camera with default values
    void Camera_Init(Camera *cam, int window_width, int window_height, int img_width, int img_height);
    
    // Handles zooming the camera centered on (mouse_x, mouse_y) with a zoom factor
    void Camera_Zoom(Camera *cam, float zoom_factor, int mouse_x, int mouse_y);
    
    // Handles panning the camera by delta amounts
    void Camera_Pan(Camera *cam, float delta_x, float delta_y);
    
    // Gets the current camera view as a SDL_Rect (source rectangle from the image)
    SDL_Rect Camera_GetView(Camera *cam);
    
    // Updates the camera to ensure it stays within image boundaries
    void Camera_Clamp(Camera *cam);
    
    #endif // EDITOR_CAMERA_H
    

    2. EditorCamera.c

    This source file implements the camera functionalities declared in EditorCamera.h.

    // EditorCamera.c
    #include "EditorCamera.h"
    
    void Camera_Init(Camera *cam, int window_width, int window_height, int img_width, int img_height) {
        cam->x = 0.0f;
        cam->y = 0.0f;
        cam->zoom = 1.0f;
        cam->window_width = window_width;
        cam->window_height = window_height;
        cam->img_width = img_width;
        cam->img_height = img_height;
        Camera_Clamp(cam);
    }
    
    void Camera_Clamp(Camera *cam) {
        // Calculate the size of the view in image coordinates
        float view_w = cam->window_width / cam->zoom;
        float view_h = cam->window_height / cam->zoom;
    
        // Clamp camera x
        if (view_w >= cam->img_width) {
            cam->x = (cam->img_width - view_w) / 2.0f;
        } else {
            if (cam->x < 0)
                cam->x = 0;
            if (cam->x + view_w > cam->img_width)
                cam->x = cam->img_width - view_w;
        }
    
        // Clamp camera y
        if (view_h >= cam->img_height) {
            cam->y = (cam->img_height - view_h) / 2.0f;
        } else {
            if (cam->y < 0)
                cam->y = 0;
            if (cam->y + view_h > cam->img_height)
                cam->y = cam->img_height - view_h;
        }
    }
    
    void Camera_Zoom(Camera *cam, float zoom_factor, int mouse_x, int mouse_y) {
        // Calculate mouse position in world coordinates before zoom
        float world_x_before = cam->x + mouse_x / cam->zoom;
        float world_y_before = cam->y + mouse_y / cam->zoom;
    
        // Apply zoom
        cam->zoom *= zoom_factor;
        if (cam->zoom < 0.1f) cam->zoom = 0.1f;
        if (cam->zoom > 10.0f) cam->zoom = 10.0f;
    
        // Calculate world position after zoom to keep the point under cursor stationary
        cam->x = world_x_before - mouse_x / cam->zoom;
        cam->y = world_y_before - mouse_y / cam->zoom;
    
        Camera_Clamp(cam);
    }
    
    void Camera_Pan(Camera *cam, float delta_x, float delta_y) {
        cam->x += delta_x / cam->zoom;
        cam->y += delta_y / cam->zoom;
        Camera_Clamp(cam);
    }
    
    SDL_Rect Camera_GetView(Camera *cam) {
        SDL_Rect view;
        view.x = (int)cam->x;
        view.y = (int)cam->y;
        view.w = (int)(cam->window_width / cam->zoom);
        view.h = (int)(cam->window_height / cam->zoom);
        return view;
    }
    

    3. Editor.c

    This is the main file that initializes SDL, loads the image, handles user input for zooming and panning, and renders the image based on the camera's state.

    // Editor.c
    #include <SDL.h>
    #include <SDL_image.h>
    #include <stdio.h>
    #include "EditorCamera.h"
    
    // Screen dimension constants
    const int SCREEN_WIDTH = 800;
    const int SCREEN_HEIGHT = 600;
    
    // Function declarations
    int InitializeSDL(SDL_Window **window, SDL_Renderer **renderer, const char *title, int width, int height);
    SDL_Texture* LoadTexture(const char* path, SDL_Renderer *renderer, int *width, int *height);
    void HandleEvents(int *quit, Camera *cam, float *dragging, int *last_mouse_x, int *last_mouse_y);
    
    int main(int argc, char* argv[]) {
        SDL_Window *window = NULL;
        SDL_Renderer *renderer = NULL;
    
        if (InitializeSDL(&window, &renderer, "OpenAge MapEditor", SCREEN_WIDTH, SCREEN_HEIGHT) != 0) {
            return 1;
        }
    
        // Load the background image
        int img_width, img_height;
        SDL_Texture *background = LoadTexture("./map/world/background.png", renderer, &img_width, &img_height);
        if (background == NULL) {
            SDL_DestroyRenderer(renderer);
            SDL_DestroyWindow(window);
            IMG_Quit();
            SDL_Quit();
            return 1;
        }
    
        // Initialize camera
        Camera cam;
        Camera_Init(&cam, SCREEN_WIDTH, SCREEN_HEIGHT, img_width, img_height);
    
        int quit = 0;
        int dragging = 0;
        int last_mouse_x = 0, last_mouse_y = 0;
    
        // Enable high DPI events
        SDL_SetHint(SDL_HINT_MOUSE_DOUBLE_CLICK_RADIUS, "0");
        
        // Main loop
        while (!quit) {
            // Handle events
            HandleEvents(&quit, &cam, &dragging, &last_mouse_x, &last_mouse_y);
    
            // Clear screen
            SDL_SetRenderDrawColor(renderer, 50, 50, 50, 255); // Dark gray background
            SDL_RenderClear(renderer);
    
            // Get the current view from the camera
            SDL_Rect srcRect = Camera_GetView(&cam);
    
            // Destination rectangle (full window)
            SDL_Rect destRect = {0, 0, cam.window_width, cam.window_height};
    
            // Render the background texture with the current camera view and zoom
            SDL_RenderCopy(renderer, background, &srcRect, &destRect);
    
            // Update the screen
            SDL_RenderPresent(renderer);
        }
    
        // Clean up
        SDL_DestroyTexture(background);
        SDL_DestroyRenderer(renderer);
        SDL_DestroyWindow(window);
        IMG_Quit();
        SDL_Quit();
    
        return 0;
    }
    
    int InitializeSDL(SDL_Window **window, SDL_Renderer **renderer, const char *title, int width, int height) {
        if (SDL_Init(SDL_INIT_VIDEO) != 0) {
            printf("SDL_Init Error: %s\n", SDL_GetError());
            return -1;
        }
    
        // Initialize SDL_image
        if(!(IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG)) {
            printf("IMG_Init Error: %s\n", IMG_GetError());
            SDL_Quit();
            return -1;
        }
    
        *window = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                                   width, height, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);
        if (*window == NULL) {
            printf("SDL_CreateWindow Error: %s\n", SDL_GetError());
            IMG_Quit();
            SDL_Quit();
            return -1;
        }
    
        // Create renderer with hardware acceleration and vsync
        *renderer = SDL_CreateRenderer(*window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
        if (*renderer == NULL) {
            SDL_DestroyWindow(*window);
            printf("SDL_CreateRenderer Error: %s\n", SDL_GetError());
            IMG_Quit();
            SDL_Quit();
            return -1;
        }
    
        return 0;
    }
    
    SDL_Texture* LoadTexture(const char* path, SDL_Renderer *renderer, int *width, int *height) {
        SDL_Surface *surface = IMG_Load(path);
        if (surface == NULL) {
            printf("IMG_Load Error: %s\n", IMG_GetError());
            return NULL;
        }
    
        // Get image dimensions
        *width = surface->w;
        *height = surface->h;
    
        // Create texture from surface
        SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, surface);
        if (texture == NULL) {
            printf("SDL_CreateTextureFromSurface Error: %s\n", SDL_GetError());
        }
    
        SDL_FreeSurface(surface);
        return texture;
    }
    
    void HandleEvents(int *quit, Camera *cam, float *dragging, int *last_mouse_x, int *last_mouse_y) {
        SDL_Event e;
        while (SDL_PollEvent(&e)) {
            switch(e.type) {
                case SDL_QUIT:
                    *quit = 1;
                    break;
                case SDL_MOUSEWHEEL:
                    {
                        // Get mouse position
                        int mouse_x, mouse_y;
                        SDL_GetMouseState(&mouse_x, &mouse_y);
    
                        // Determine zoom factor
                        float zoom_factor = 1.0f;
                        if (e.wheel.y > 0) { // Scroll up
                            zoom_factor = 1.1f;
                        } else if (e.wheel.y < 0) { // Scroll down
                            zoom_factor = 0.9f;
                        }
    
                        Camera_Zoom(cam, zoom_factor, mouse_x, mouse_y);
                    }
                    break;
                case SDL_MOUSEBUTTONDOWN:
                    if (e.button.button == SDL_BUTTON_RIGHT) {
                        *dragging = 1;
                        *last_mouse_x = e.button.x;
                        *last_mouse_y = e.button.y;
                    }
                    break;
                case SDL_MOUSEBUTTONUP:
                    if (e.button.button == SDL_BUTTON_RIGHT) {
                        *dragging = 0;
                    }
                    break;
                case SDL_MOUSEMOTION:
                    if (*dragging) {
                        int dx = e.motion.x - *last_mouse_x;
                        int dy = e.motion.y - *last_mouse_y;
                        Camera_Pan(cam, -dx, -dy); // Negative because moving mouse right should move camera left
                        *last_mouse_x = e.motion.x;
                        *last_mouse_y = e.motion.y;
                    }
                    break;
                case SDL_WINDOWEVENT:
                    if (e.window.event == SDL_WINDOWEVENT_RESIZED) {
                        // Update camera's window size
                        cam->window_width = e.window.data1;
                        cam->window_height = e.window.data2;
                        Camera_Clamp(cam);
                    }
                    break;
                default:
                    break;
            }
        }
    }
    

    Explanation of Key Components

    1. Camera Structure (Camera)

      • Position (x, y): Represents the top-left corner of the view in the image's coordinate system.
      • Zoom (zoom): Represents the scaling factor. A zoom of 1.0 means no scaling. Greater than 1.0 zooms in, and less than 1.0 zooms out.
      • Window Dimensions (window_width, window_height): Current size of the window, updated on resize.
      • Image Dimensions (img_width, img_height): Dimensions of the background image to ensure the camera doesn't show areas outside the image.
    2. Camera Initialization (Camera_Init)

      Sets the initial camera position and zoom, then clamps the camera to ensure it doesn't show areas outside the image boundaries.

    3. Camera Clamping (Camera_Clamp)

      Ensures that the camera view does not go beyond the boundaries of the image. Adjusts x and y accordingly based on the current zoom level and window size.

    4. Zooming (Camera_Zoom)

      • Zoom Factor: Determines how much to zoom in or out. For example, a factor of 1.1 zooms in by 10%, while 0.9 zooms out by 10%.
      • Cursor-Centered Zoom: Calculates the world coordinates under the cursor before and after zooming to adjust the camera position so that the point under the cursor remains stationary.
    5. Panning (Camera_Pan)

      Adjusts the camera's x and y based on mouse movement. The movement is inversely proportional to the zoom level to provide a smooth panning experience.

    6. Event Handling (HandleEvents)

      • Mouse Wheel: Triggers zoom in/out centered on the mouse cursor position.
      • Right Mouse Button: Initiates panning. While the right button is held down and the mouse moves, the camera pans accordingly.
      • Window Resize: Updates the camera's window dimensions and clamps the view.
    7. Rendering

      • Source Rectangle (srcRect): Defines the portion of the image to display based on the camera's position and zoom.
      • Destination Rectangle (destRect): Always spans the entire window but scales the source rectangle based on zoom.
      • SDL_RenderCopy: Renders the specified portion of the image texture to the window.

    Compilation Instructions

    Assuming all three files (Editor.c, EditorCamera.c, EditorCamera.h) are in the project directory, and the background image is located at ./map/world/background.png, you can compile the program using the following command:

    gcc Editor.c EditorCamera.c -o OpenAgeMapEditor -lSDL2 -lSDL2_image
    

    Running the Program

    After successful compilation, run the program using:

    ./OpenAgeMapEditor
    

    A window titled "OpenAge MapEditor" will open, displaying the background.png image. You can interact with the map as follows:

    • Zooming: Scroll the mouse wheel up to zoom in and down to zoom out. The zoom action is centered around the current mouse cursor position.
    • Panning: Right-click and drag to move the camera across the map. The camera movement is smooth, and it will not allow you to pan beyond the image boundaries.
    • Window Resize: The aspect ratio of the view matches the window's aspect ratio. Resizing the window will adjust the view accordingly while maintaining the aspect ratio and boundary constraints.

    Notes

    • Boundary Constraints: The camera will not show areas outside the background.png image, regardless of zoom or pan actions.
    • Aspect Ratio: The program maintains the aspect ratio of the window. If the window is resized, the view adapts while preserving the aspect ratio.
    • Performance: SDL's hardware acceleration is used for rendering, ensuring smooth performance even with large images.

    Troubleshooting

    • SDL Initialization Errors: Ensure that SDL2 and SDL2_image are properly installed on your system.
    • Image Loading Errors: Verify that the path ./map/world/background.png is correct and that the image exists at that location.
    • Compilation Errors: Make sure to link against SDL2 and SDL2_image libraries using -lSDL2 -lSDL2_image.

    Feel free to customize and extend this program to suit your specific needs!