// Инициализация SDL_image
if (!(IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG)) {
printf("Ошибка инициализации SDL_image: %s\n", IMG_GetError());
SDL_Quit();
return 1;
}
// Создание окна с возможностью изменения размера
SDL_Window* window = SDL_CreateWindow("Отображение изображения",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
800, 600,
SDL_WINDOW_RESIZABLE);
if (!window) {
printf("Ошибка создания окна: %s\n", SDL_GetError());
IMG_Quit();
SDL_Quit();
return 1;
}
// Создание рендерера
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (!renderer) {
printf("Ошибка создания рендерера: %s\n", SDL_GetError());
SDL_DestroyWindow(window);
IMG_Quit();
SDL_Quit();
return 1;
}
// Загрузка изображения
SDL_Surface* imageSurface = IMG_Load("../Maps/world/provinces.png");
if (!imageSurface) {
printf("Ошибка загрузки изображения: %s\n", IMG_GetError());
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
IMG_Quit();
SDL_Quit();
return 1;
}
// Создание текстуры из поверхности изображения
SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, imageSurface);
SDL_FreeSurface(imageSurface); // Освобождение поверхности
if (!texture) {
printf("Ошибка создания текстуры: %s\n", SDL_GetError());
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
IMG_Quit();
SDL_Quit();
return 1;
}
// Получение размеров изображения
int imageWidth, imageHeight;
SDL_QueryTexture(texture, NULL, NULL, &imageWidth, &imageHeight);
// Размеры камеры (начальные)
float camX = 0, camY = 0;
float camW = imageWidth - 1;
float camH = imageHeight - 1;
// Основной цикл приложения
int running = 1;
while (running) {
SDL_Event event;
// Обработка событий
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
running = 0;
} else if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED) {
// При изменении размера окна можно обновить камеру, если необходимо
}
}
// Получение размеров окна
int windowWidth, windowHeight;
SDL_GetWindowSize(window, &windowWidth, &windowHeight);
// Вычисление размеров камеры с сохранением пропорций и ограничением по размерам изображения
float windowAspect = (float)windowWidth / (float)windowHeight;
// Камера должна быть меньше изображения по любой из сторон
float maxCamW = imageWidth - 1;
float maxCamH = imageHeight - 1;
float camAspect = windowAspect;
// Попытка установить камеру на основе ширины
camW = maxCamW;
camH = camW / camAspect;
if (camH >= maxCamH) {
// Если высота камеры выходит за пределы, то корректируем на основе высоты
camH = maxCamH;
camW = camH * camAspect;
}
// Проверяем, чтобы камера была меньше размеров изображения
if (camW >= maxCamW) {
camW = maxCamW;
}
if (camH >= maxCamH) {
camH = maxCamH;
}
// Центрируем камеру на изображении
camX = (imageWidth - camW) / 2;
camY = (imageHeight - camH) / 2;
SDL_Rect srcRect = { (int)camX, (int)camY, (int)camW, (int)camH };
SDL_Rect destRect = { 0, 0, windowWidth, windowHeight };
// Очистка рендерера
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); // Черный фон
SDL_RenderClear(renderer);
// Отрисовка текстуры с масштабированием
SDL_RenderCopy(renderer, texture, &srcRect, &destRect);
// Обновление экрана
SDL_RenderPresent(renderer);
}
// Освобождение ресурсов
SDL_DestroyTexture(texture);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
IMG_Quit();
SDL_Quit();
return 0;
}
Напиши для этого кода код зума в файлах EditorCamera.c и .h. Зум должен быть плавным, уровень зума должен быть с типом float, чтобы камера не подстраивалась размером под пиксели карты(изображения). При прокрутке колесика мыши вверх камера приближается, при прокрутке вниз отдаляется. Камера при зуме не должна выходить за границы изображение(карты)
Certainly! Below is the implementation of the zoom functionality for your code, split into two files: EditorCamera.h and EditorCamera.c. The zoom level is represented by a float, allowing for smooth zooming without snapping to pixel sizes. Scrolling the mouse wheel up zooms in, and scrolling down zooms out. The camera will not go outside the image boundaries during zoom.
EditorCamera.h
c
#ifndef EDITOR_CAMERA_H
#define EDITOR_CAMERA_H
#include <SDL.h>
typedef struct {
float x, y; // Position of the camera in image coordinates
float w, h; // Width and height of the camera view
float zoom; // Current zoom level
float minZoom, maxZoom; // Minimum and maximum allowed zoom levels
int imageWidth; // Width of the image
int imageHeight; // Height of the image
int windowWidth; // Width of the window
int windowHeight; // Height of the window
} EditorCamera;
// Initialize the camera with image and window dimensions
void EditorCamera_Init(EditorCamera* camera, int imageWidth, int imageHeight, int windowWidth, int windowHeight);
// Update the window size in the camera (e.g., when the window is resized)
void EditorCamera_SetWindowSize(EditorCamera* camera, int windowWidth, int windowHeight);
// Zoom the camera in or out based on zoomAmount, keeping the mouse position stable
void EditorCamera_Zoom(EditorCamera* camera, float zoomAmount, int mouseX, int mouseY);
// Get the source rectangle representing the portion of the image to display
void EditorCamera_GetSourceRect(EditorCamera* camera, SDL_Rect* srcRect);
// Center the camera on the image
void EditorCamera_Center(EditorCamera* camera);
#endif // EDITOR_CAMERA_H
EditorCamera.c
c
Integration into Your Main Code
Now, let's integrate the camera with your main code. We'll include EditorCamera.h, initialize the camera, and modify the event loop to handle zooming with the mouse wheel.
c
Explanation of the Integration
Including EditorCamera: We include EditorCamera.h in the main code to use the camera functions.
Initializing the Camera: After loading the image and obtaining its dimensions, we initialize the camera with EditorCamera_Init. We also center the camera on the image using EditorCamera_Center.
Handling Window Resizing: When the window is resized (SDL_WINDOWEVENT_SIZE_CHANGED), we update the camera's windowWidth and windowHeight using EditorCamera_SetWindowSize.
Handling Mouse Wheel Events for Zooming:
Mouse Wheel Up (event.wheel.y > 0): We increase the zoom level by a small amount (e.g., 0.1f). Scrolling up zooms in.
Mouse Wheel Down (event.wheel.y < 0): We decrease the zoom level by a small amount (e.g., -0.1f). Scrolling down zooms out.
We retrieve the current mouse position with SDL_GetMouseState.
We call EditorCamera_Zoom to update the camera's zoom level, passing in the zoom amount and mouse position.
Rendering the Image:
We get the source rectangle from the camera using EditorCamera_GetSourceRect.
The destination rectangle covers the entire window (destRect).
We render the texture using SDL_RenderCopy, which scales the source rectangle (srcRect) to fit the destination rectangle (destRect).
Key Points About the Zoom Functionality
Smooth Zooming: The zoom level is a float, allowing for smooth zoom transitions without snapping to integer pixel sizes.
Mouse-Centered Zoom: The zoom function keeps the image point under the mouse cursor stationary during zoom. This means that when you zoom in or out, the image will zoom relative to the mouse pointer, providing a more intuitive user experience.
Bounded Camera Movement: The camera's position (x, y) is clamped so that it never goes outside the boundaries of the image. This ensures that there are no black borders or empty spaces outside the image when zooming or panning.
Adjustable Zoom Limits: The minimum and maximum zoom levels (minZoom, maxZoom) can be adjusted to suit your needs. This prevents the user from zooming in too close or zooming out too far.
Possible Extensions
Panning: You may want to add the ability to pan the image by clicking and dragging. This would involve updating the camera's x and y based on mouse movements.
Zoom Speed: Adjust the zoom increment (0.1f in the example) to change how quickly the image zooms in or out in response to the mouse wheel.
Zoom Under Cursor: The current implementation zooms around the mouse position. If you prefer to zoom towards the center of the screen regardless of mouse position, you can modify the EditorCamera_Zoom function accordingly.
Feel free to adjust the code to better fit your project's specific needs. The provided implementation should serve as a solid foundation for adding smooth zoom functionality to your SDL application.
#include "EditorCamera.h"
// Initialize the camera with image and window dimensions
void EditorCamera_Init(EditorCamera* camera, int imageWidth, int imageHeight, int windowWidth, int windowHeight) {
camera->imageWidth = imageWidth;
camera->imageHeight = imageHeight;
camera->windowWidth = windowWidth;
camera->windowHeight = windowHeight;
camera->zoom = 1.0f; // Start with no zoom
camera->minZoom = 0.1f; // Minimum zoom (10% of original size)
camera->maxZoom = 10.0f; // Maximum zoom (1000% of original size)
camera->w = imageWidth;
camera->h = imageHeight;
camera->x = 0;
camera->y = 0;
}
// Update the window size in the camera (e.g., when the window is resized)
void EditorCamera_SetWindowSize(EditorCamera* camera, int windowWidth, int windowHeight) {
camera->windowWidth = windowWidth;
camera->windowHeight = windowHeight;
}
// Zoom the camera in or out based on zoomAmount, keeping the mouse position stable
void EditorCamera_Zoom(EditorCamera* camera, float zoomAmount, int mouseX, int mouseY) {
// Save the old zoom level
float oldZoom = camera->zoom;
// Update the zoom level
camera->zoom += zoomAmount;
if (camera->zoom < camera->minZoom) camera->zoom = camera->minZoom;
if (camera->zoom > camera->maxZoom) camera->zoom = camera->maxZoom;
// Calculate the change in zoom
float zoomFactor = camera->zoom / oldZoom;
// Calculate the position of the mouse in image coordinates before zoom
float mouseImageX = camera->x + (float)mouseX / camera->windowWidth * camera->w;
float mouseImageY = camera->y + (float)mouseY / camera->windowHeight * camera->h;
// Update the camera's width and height based on the new zoom level
camera->w = camera->imageWidth / camera->zoom;
camera->h = camera->imageHeight / camera->zoom;
// Adjust the camera's position to keep the zoom centered around the mouse position
camera->x = mouseImageX - (float)mouseX / camera->windowWidth * camera->w;
camera->y = mouseImageY - (float)mouseY / camera->windowHeight * camera->h;
// Clamp the camera's position to prevent it from going outside the image boundaries
if (camera->x < 0) camera->x = 0;
if (camera->y < 0) camera->y = 0;
if (camera->x + camera->w > camera->imageWidth) camera->x = camera->imageWidth - camera->w;
if (camera->y + camera->h > camera->imageHeight) camera->y = camera->imageHeight - camera->h;
}
// Get the source rectangle representing the portion of the image to display
void EditorCamera_GetSourceRect(EditorCamera* camera, SDL_Rect* srcRect) {
srcRect->x = (int)camera->x;
srcRect->y = (int)camera->y;
srcRect->w = (int)camera->w;
srcRect->h = (int)camera->h;
}
// Center the camera on the image
void EditorCamera_Center(EditorCamera* camera) {
camera->x = (camera->imageWidth - camera->w) / 2.0f;
camera->y = (camera->imageHeight - camera->h) / 2.0f;
// Clamp the camera's position just to be safe
if (camera->x < 0) camera->x = 0;
if (camera->y < 0) camera->y = 0;
if (camera->x + camera->w > camera->imageWidth) camera->x = camera->imageWidth - camera->w;
if (camera->y + camera->h > camera->imageHeight) camera->y = camera->imageHeight - camera->h;
}
#include <SDL.h>
#include <SDL_image.h>
#include <stdio.h>
#include "EditorCamera.h" // Include the camera header
int main(int argc, char* argv[]) {
// Initialize SDL
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
printf("Ошибка инициализации SDL: %s\n", SDL_GetError());
return 1;
}
// Initialize SDL_image
if (!(IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG)) {
printf("Ошибка инициализации SDL_image: %s\n", IMG_GetError());
SDL_Quit();
return 1;
}
// Create a resizable window
SDL_Window* window = SDL_CreateWindow("Отображение изображения",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
800, 600,
SDL_WINDOW_RESIZABLE);
if (!window) {
printf("Ошибка создания окна: %s\n", SDL_GetError());
IMG_Quit();
SDL_Quit();
return 1;
}
// Create a renderer
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (!renderer) {
printf("Ошибка создания рендерера: %s\n", SDL_GetError());
SDL_DestroyWindow(window);
IMG_Quit();
SDL_Quit();
return 1;
}
// Load the image
SDL_Surface* imageSurface = IMG_Load("../Maps/world/provinces.png");
if (!imageSurface) {
printf("Ошибка загрузки изображения: %s\n", IMG_GetError());
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
IMG_Quit();
SDL_Quit();
return 1;
}
// Create a texture from the image surface
SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, imageSurface);
SDL_FreeSurface(imageSurface); // Free the surface
if (!texture) {
printf("Ошибка создания текстуры: %s\n", SDL_GetError());
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
IMG_Quit();
SDL_Quit();
return 1;
}
// Get the image dimensions
int imageWidth, imageHeight;
SDL_QueryTexture(texture, NULL, NULL, &imageWidth, &imageHeight);
// Create and initialize the camera
EditorCamera camera;
int windowWidth = 800, windowHeight = 600; // Initial window size
EditorCamera_Init(&camera, imageWidth, imageHeight, windowWidth, windowHeight);
EditorCamera_Center(&camera); // Center the camera at start
// Enable mouse wheel events
SDL_EventState(SDL_MOUSEWHEEL, SDL_ENABLE);
// Main application loop
int running = 1;
while (running) {
SDL_Event event;
// Event handling
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
running = 0;
} else if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED) {
// Update the window size in the camera
SDL_GetWindowSize(window, &windowWidth, &windowHeight);
EditorCamera_SetWindowSize(&camera, windowWidth, windowHeight);
} else if (event.type == SDL_MOUSEWHEEL) {
// Zoom in or out
float zoomAmount = 0.0f;
// Determine the zoom amount based on mouse wheel direction
if (event.wheel.y > 0) {
zoomAmount = 0.1f; // Zoom in
} else if (event.wheel.y < 0) {
zoomAmount = -0.1f; // Zoom out
}
// Get the current mouse position
int mouseX, mouseY;
SDL_GetMouseState(&mouseX, &mouseY);
// Update the camera's zoom level
EditorCamera_Zoom(&camera, zoomAmount, mouseX, mouseY);
}
}
// Get the source rectangle from the camera
SDL_Rect srcRect;
EditorCamera_GetSourceRect(&camera, &srcRect);
// Destination rectangle covers the entire window
SDL_Rect destRect = { 0, 0, windowWidth, windowHeight };
// Clear the renderer
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); // Black background
SDL_RenderClear(renderer);
// Render the texture with scaling
SDL_RenderCopy(renderer, texture, &srcRect, &destRect);
// Update the screen
SDL_RenderPresent(renderer);
}
// Clean up resources
SDL_DestroyTexture(texture);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
IMG_Quit();
SDL_Quit();
return 0;
}