Исправь следующую проблему в этом коде: 1. При зуме с максимального отдаления srcRect…
- User
Исправь следующую проблему в этом коде:
- При зуме с максимального отдаления srcRect сначала сдвигается в сторону курсора, пока не достигнет края, и только после этого начинает корректный зум.
- Добавь рисование полигонов поверх карты(бэкграунда) как в коде polygon_drawer.c. Точки полигона должны устанавливаться ровно на пиксели изображения. Полигоны должны быть полупрозрачными. Цвет полигона должен задаваться случайно. напиши код рисования полигонов в файлах EProvince.c и .EProvince.h. Свяжи эти файлы с mainEditor.c
#include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <stdio.h> #include "zoom.h"
#define WINDOW_WIDTH 800 #define WINDOW_HEIGHT 600
int main(int argc, char *argv[]) { SDL_Window *window = NULL; SDL_Renderer *renderer = NULL; SDL_Texture *texture = NULL; SDL_Event event; int quit = 0;
int image_width, image_height; // Initialize SDL if (SDL_Init(SDL_INIT_VIDEO) < 0) { printf("SDL could not initialize! SDL_Error: %s\n", SDL_GetError()); return -1; } // Initialize SDL_image if (!(IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG)) { printf("SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError()); SDL_Quit(); return -1; } // Create window window = SDL_CreateWindow("OpenAge Map Editor", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_RESIZABLE); if (window == NULL) { printf("Window could not be created! SDL_Error: %s\n", SDL_GetError()); IMG_Quit(); SDL_Quit(); return -1; } // Create renderer renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); if (renderer == NULL) { printf("Renderer could not be created! SDL_Error: %s\n", SDL_GetError()); SDL_DestroyWindow(window); IMG_Quit(); SDL_Quit(); return -1; } // Load image SDL_Surface *loadedSurface = IMG_Load("./map/world/background.png"); if (loadedSurface == NULL) { printf("Unable to load image %s! SDL_image Error: %s\n", "./map/world/background.png", IMG_GetError()); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); IMG_Quit(); SDL_Quit(); return -1; } // Create texture from surface texture = SDL_CreateTextureFromSurface(renderer, loadedSurface); if (texture == NULL) { printf("Unable to create texture from %s! SDL Error: %s\n", "./map/world/background.png", SDL_GetError()); SDL_FreeSurface(loadedSurface); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); IMG_Quit(); SDL_Quit(); return -1; } image_width = loadedSurface->w; image_height = loadedSurface->h; SDL_FreeSurface(loadedSurface); // Get initial window size int window_width, window_height; SDL_GetWindowSize(window, &window_width, &window_height); // Initialize zoom and camera init_zoom(image_width, image_height, window_width, window_height); // Main loop while (!quit) { // Event handling while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: quit = 1; break; case SDL_WINDOWEVENT: if (event.window.event == SDL_WINDOWEVENT_RESIZED) { // Update window size SDL_GetWindowSize(window, &window_width, &window_height); set_window_size(window_width, window_height); } break; case SDL_MOUSEBUTTONDOWN: if (event.button.button == SDL_BUTTON_LEFT) { // Start dragging start_camera_drag(event.button.x, event.button.y); } break; case SDL_MOUSEBUTTONUP: if (event.button.button == SDL_BUTTON_LEFT) { // Stop dragging stop_camera_drag(); } break; case SDL_MOUSEMOTION: // Update camera dragging update_camera_drag(event.motion.x, event.motion.y); break; case SDL_MOUSEWHEEL: { // Get mouse position int mouse_x, mouse_y; SDL_GetMouseState(&mouse_x, &mouse_y); // Zoom in and out if (event.wheel.y > 0) { zoom_in(mouse_x, mouse_y); } else if (event.wheel.y < 0) { zoom_out(mouse_x, mouse_y); } break; } default: break; } } // Update zoom level update_zoom(); // Get the source rectangle for rendering SDL_Rect src_rect = get_source_rect(); // Set the destination rectangle (where to render the image in the window) SDL_Rect dst_rect; dst_rect.x = 0; dst_rect.y = 0; dst_rect.w = window_width; dst_rect.h = window_height; // Clear renderer SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); // Black background SDL_RenderClear(renderer); // Render the texture SDL_RenderCopy(renderer, texture, &src_rect, &dst_rect); // Update screen SDL_RenderPresent(renderer); // Delay to control frame rate SDL_Delay(16); // Approximately 60 frames per second } // Clean up SDL_DestroyTexture(texture); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); IMG_Quit(); SDL_Quit(); return 0;}
//zoom.c #include "zoom.h" #include <math.h> // Для функции fabs()
static float zoom_level = 1.0f; static float zoom_target = 1.0f; static float zoom_speed = 0.1f; static const float initial_zoom_speed = 0.5f; // Стартовая скорость зума static const float min_zoom_speed = 0.1f; // Минимальная скорость зума static const float zoom_factor = 1.1f; // Zoom increment factor
// Image and window dimensions static int image_width = 0; static int image_height = 0; static int window_width = 0; static int window_height = 0;
// Camera properties static float camera_x = 0.0f; static float camera_y = 0.0f;
static int dragging = 0; static int prev_mouse_x = 0; static int prev_mouse_y = 0;
// Variables for zooming around cursor static int is_zooming = 0; static float cursor_world_x = 0.0f; static float cursor_world_y = 0.0f; static int cursor_screen_x = 0; static int cursor_screen_y = 0;
// Initialize zoom and camera settings void init_zoom(int img_width, int img_height, int win_width, int win_height) { zoom_level = 1.0f; zoom_target = 1.0f; image_width = img_width; image_height = img_height; window_width = win_width; window_height = win_height; camera_x = 0.0f; camera_y = 0.0f; }
// Zoom functions void zoom_in(int mouse_x, int mouse_y) { // Store the world coordinates under the cursor cursor_world_x = camera_x + (float)mouse_x / zoom_level; cursor_world_y = camera_y + (float)mouse_y / zoom_level; cursor_screen_x = mouse_x; cursor_screen_y = mouse_y;
zoom_target *= zoom_factor; is_zooming = 1; zoom_speed = initial_zoom_speed;}
void zoom_out(int mouse_x, int mouse_y) { // Store the world coordinates under the cursor cursor_world_x = camera_x + (float)mouse_x / zoom_level; cursor_world_y = camera_y + (float)mouse_y / zoom_level; cursor_screen_x = mouse_x; cursor_screen_y = mouse_y;
zoom_target /= zoom_factor; is_zooming = 1; zoom_speed = initial_zoom_speed;}
void update_zoom() { // Smoothly interpolate towards the target zoom level float prev_zoom_level = zoom_level; zoom_level += (zoom_target - zoom_level) * zoom_speed;
// Decrease zoom_speed gradually if (is_zooming) { zoom_speed *= 0.9f; // Decrease zoom_speed if (zoom_speed < min_zoom_speed) { zoom_speed = min_zoom_speed; is_zooming = 0; // Stop decreasing zoom_speed } // Adjust camera position to keep the cursor world position under the cursor camera_x = cursor_world_x - (float)cursor_screen_x / zoom_level; camera_y = cursor_world_y - (float)cursor_screen_y / zoom_level; } // Clamp zoom level if (zoom_level < 0.1f) { zoom_level = 0.1f; zoom_target = 0.1f; } if (zoom_level > 10.0f) { zoom_level = 10.0f; zoom_target = 10.0f; }}
// Camera drag functions void start_camera_drag(int mouse_x, int mouse_y) { dragging = 1; prev_mouse_x = mouse_x; prev_mouse_y = mouse_y; }
void stop_camera_drag() { dragging = 0; }
void update_camera_drag(int mouse_x, int mouse_y) { if (dragging) { // Calculate the difference in mouse movement int delta_x = mouse_x - prev_mouse_x; int delta_y = mouse_y - prev_mouse_y;
// Update the camera position inversely to the mouse movement camera_x -= delta_x / zoom_level; camera_y -= delta_y / zoom_level; // Update previous mouse position prev_mouse_x = mouse_x; prev_mouse_y = mouse_y; }}
// Window resize handling void set_window_size(int win_width, int win_height) { window_width = win_width; window_height = win_height; }
// Getters float get_zoom_level() { return zoom_level; }
SDL_Rect get_source_rect() { SDL_Rect src_rect;
// Calculate the aspect ratio of the window float window_aspect_ratio = (float)window_width / (float)window_height; // Calculate the visible width and height based on zoom level float visible_width = window_width / zoom_level; float visible_height = window_height / zoom_level; // Adjust visible area to maintain aspect ratio float adjusted_width = visible_width; float adjusted_height = visible_height; float current_aspect_ratio = visible_width / visible_height; if (current_aspect_ratio > window_aspect_ratio) { // Width is too big compared to height, adjust width adjusted_width = visible_height * window_aspect_ratio; } else if (current_aspect_ratio < window_aspect_ratio) { // Height is too big compared to width, adjust height adjusted_height = visible_width / window_aspect_ratio; } visible_width = adjusted_width; visible_height = adjusted_height; // Ensure visible dimensions do not exceed image dimensions if (visible_width > image_width) { visible_width = (float)image_width; visible_height = visible_width / window_aspect_ratio; } if (visible_height > image_height) { visible_height = (float)image_height; visible_width = visible_height * window_aspect_ratio; } // Adjust camera position to ensure src_rect is within image boundaries float max_camera_x = image_width - visible_width; float max_camera_y = image_height - visible_height; if (camera_x < 0) camera_x = 0; if (camera_x > max_camera_x) camera_x = max_camera_x; if (camera_y < 0) camera_y = 0; if (camera_y > max_camera_y) camera_y = max_camera_y; src_rect.x = (int)camera_x; src_rect.y = (int)camera_y; src_rect.w = (int)visible_width; src_rect.h = (int)visible_height; return src_rect;}
//zoom.h #ifndef ZOOM_H #define ZOOM_H
#include <SDL2/SDL.h>
// Initialize zoom and camera settings void init_zoom(int image_width, int image_height, int window_width, int window_height);
// Zoom controls void zoom_in(int mouse_x, int mouse_y); void zoom_out(int mouse_x, int mouse_y); void update_zoom();
// Camera controls void start_camera_drag(int mouse_x, int mouse_y); void stop_camera_drag(); void update_camera_drag(int mouse_x, int mouse_y);
// Window resize handling void set_window_size(int window_width, int window_height);
// Getters float get_zoom_level(); SDL_Rect get_source_rect();
#endif // ZOOM_H
//polygon_drawer.c #include <SDL2/SDL.h> #include <SDL2/SDL2_gfxPrimitives.h>
#define MAX_POINTS 1000
int main(int argc, char *argv[]) { SDL_Window *window; SDL_Renderer *renderer; SDL_Event event; int quit = 0; int numPoints = 0; Sint16 vx[MAX_POINTS]; Sint16 vy[MAX_POINTS];
// Initialize SDL if (SDL_Init(SDL_INIT_VIDEO) < 0) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_Init failed: %s\n", SDL_GetError()); return 1; } // Create window and renderer if (SDL_CreateWindowAndRenderer(800, 600, SDL_WINDOW_SHOWN, &window, &renderer) < 0) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_CreateWindowAndRenderer failed: %s\n", SDL_GetError()); SDL_Quit(); return 1; } SDL_SetWindowTitle(window, "Interactive Polygon Drawer"); // Main loop while (!quit) { // Event handling while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: quit = 1; break; case SDL_MOUSEBUTTONDOWN: if (event.button.button == SDL_BUTTON_LEFT) { // Add point if (numPoints < MAX_POINTS) { vx[numPoints] = event.button.x; vy[numPoints] = event.button.y; numPoints++; } } break; default: break; } } // Clear renderer SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); // Black background SDL_RenderClear(renderer); // Draw filled polygon if we have at least 3 points if (numPoints >= 3) { filledPolygonRGBA(renderer, vx, vy, numPoints, 255, 0, 0, 255); // Red filled polygon } // Draw points for (int i = 0; i < numPoints; i++) { filledCircleRGBA(renderer, vx[i], vy[i], 3, 0, 255, 0, 255); // Green points } // Present renderer SDL_RenderPresent(renderer); // Delay to limit frame rate SDL_Delay(16); // Approximately 60 frames per second } // Clean up SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); return 0;}
- Assistant
Исправление и дополнение кода
Давайте последовательно решим обе поставленные задачи:
-
Исправление проблемы с зумом:
- Проблема заключается в некорректном обновлении позиции камеры при изменении уровня зума. Необходимо обеспечить, чтобы точка под курсором оставалась постоянной при зуме, избегая нежелательных сдвигов.
-
Добавление рисования полигонов поверх карты:
- Реализуем модули
EProvince.cиEProvince.hдля управления полигонами. - Полигон будет иметь случайный цвет с прозрачностью.
- Убедимся, что точки полигона выровнены по пикселям.
- Интегрируем рисование полигонов в основной цикл рендеринга.
- Реализуем модули
1. Исправление проблемы с зумом
В файле
zoom.cнеобходимо скорректировать функции зума, чтобы избежать сдвигаsrcRectпри зуме. Изменения направлены на сохранение позиции точки под курсором во время зума.Обновленный
zoom.c:// zoom.c #include "zoom.h" #include <math.h> // Для функции fabs() static float zoom_level = 1.0f; static float zoom_target = 1.0f; static float zoom_speed = 0.1f; static const float initial_zoom_speed = 0.5f; // Стартовая скорость зума static const float min_zoom_speed = 0.1f; // Минимальная скорость зума static const float zoom_factor = 1.1f; // Zoom increment factor // Image and window dimensions static int image_width = 0; static int image_height = 0; static int window_width = 0; static int window_height = 0; // Camera properties static float camera_x = 0.0f; static float camera_y = 0.0f; static int dragging = 0; static int prev_mouse_x = 0; static int prev_mouse_y = 0; // Variables for zooming around cursor static float cursor_world_x = 0.0f; static float cursor_world_y = 0.0f; static int cursor_screen_x = 0; static int cursor_screen_y = 0; // Initialize zoom and camera settings void init_zoom(int img_width, int img_height, int win_width, int win_height) { zoom_level = 1.0f; zoom_target = 1.0f; image_width = img_width; image_height = img_height; window_width = win_width; window_height = win_height; camera_x = 0.0f; camera_y = 0.0f; } // Zoom functions void zoom_in(int mouse_x, int mouse_y) { // Вычисляем координаты мира под курсором до зума cursor_world_x = camera_x + (float)mouse_x / zoom_level; cursor_world_y = camera_y + (float)mouse_y / zoom_level; zoom_target *= zoom_factor; is_zooming = 1; zoom_speed = initial_zoom_speed; } void zoom_out(int mouse_x, int mouse_y) { // Вычисляем координаты мира под курсором до зума cursor_world_x = camera_x + (float)mouse_x / zoom_level; cursor_world_y = camera_y + (float)mouse_y / zoom_level; zoom_target /= zoom_factor; is_zooming = 1; zoom_speed = initial_zoom_speed; } void update_zoom() { // Плавно интерполируем уровень зума к целевому float prev_zoom_level = zoom_level; zoom_level += (zoom_target - zoom_level) * zoom_speed; // Вычисляем масштаб после обновления зума float new_zoom_level = zoom_level; // Корректируем позицию камеры, чтобы точка под курсором оставалась неизменной camera_x = cursor_world_x - ((float)cursor_screen_x / new_zoom_level); camera_y = cursor_world_y - ((float)cursor_screen_y / new_zoom_level); // Ограничиваем уровень зума if (zoom_level < 0.1f) { zoom_level = 0.1f; zoom_target = 0.1f; } if (zoom_level > 10.0f) { zoom_level = 10.0f; zoom_target = 10.0f; } // Ограничиваем позицию камеры, чтобы src_rect не выходил за границы изображения float visible_width = window_width / zoom_level; float visible_height = window_height / zoom_level; float max_camera_x = image_width - visible_width; float max_camera_y = image_height - visible_height; if (camera_x < 0) camera_x = 0; if (camera_x > max_camera_x) camera_x = max_camera_x; if (camera_y < 0) camera_y = 0; if (camera_y > max_camera_y) camera_y = max_camera_y; } // Camera drag functions void start_camera_drag(int mouse_x, int mouse_y) { dragging = 1; prev_mouse_x = mouse_x; prev_mouse_y = mouse_y; } void stop_camera_drag() { dragging = 0; } void update_camera_drag(int mouse_x, int mouse_y) { if (dragging) { // Вычисляем разницу в движении мыши int delta_x = mouse_x - prev_mouse_x; int delta_y = mouse_y - prev_mouse_y; // Обновляем позицию камеры инверсно движению мыши camera_x -= delta_x / zoom_level; camera_y -= delta_y / zoom_level; // Обновляем предыдущую позицию мыши prev_mouse_x = mouse_x; prev_mouse_y = mouse_y; // Ограничиваем позицию камеры float visible_width = window_width / zoom_level; float visible_height = window_height / zoom_level; float max_camera_x = image_width - visible_width; float max_camera_y = image_height - visible_height; if (camera_x < 0) camera_x = 0; if (camera_x > max_camera_x) camera_x = max_camera_x; if (camera_y < 0) camera_y = 0; if (camera_y > max_camera_y) camera_y = max_camera_y; } } // Window resize handling void set_window_size(int win_width, int win_height) { window_width = win_width; window_height = win_height; } // Getters float get_zoom_level() { return zoom_level; } SDL_Rect get_source_rect() { SDL_Rect src_rect; // Вычисляем видимую область на основе уровня зума float visible_width = window_width / zoom_level; float visible_height = window_height / zoom_level; // Ограничиваем видимую область границами изображения if (visible_width > image_width) { visible_width = (float)image_width; } if (visible_height > image_height) { visible_height = (float)image_height; } // Ограничиваем позицию камеры float max_camera_x = image_width - visible_width; float max_camera_y = image_height - visible_height; if (camera_x < 0) camera_x = 0; if (camera_x > max_camera_x) camera_x = max_camera_x; if (camera_y < 0) camera_y = 0; if (camera_y > max_camera_y) camera_y = max_camera_y; src_rect.x = (int)floor(camera_x); src_rect.y = (int)floor(camera_y); src_rect.w = (int)ceil(visible_width); src_rect.h = (int)ceil(visible_height); return src_rect; }Изменения:
- В функции
update_zoomмы теперь корректируем позицию камеры после обновления уровня зума, чтобы точка под курсором оставалась стабильной. - Убраны ненужные переменные и упрощена логика ограничений камеры.
- Убедились, что
camera_xиcamera_yне выходят за границы изображения.
2. Добавление рисования полигонов поверх карты
Создадим два новых файла:
EProvince.hиEProvince.c, отвечающие за управление и рисование полигонов.EProvince.h// EProvince.h #ifndef EPROVINCE_H #define EPROVINCE_H #include <SDL2/SDL.h> #include <stdbool.h> // Максимальное количество вершин в полигоне #define MAX_POLYGON_POINTS 1000 // Структура для хранения полигона typedef struct { int num_points; SDL_Point points[MAX_POLYGON_POINTS]; Uint8 r, g, b, a; // Цвет с прозрачностью } Province; // Инициализация системы провинций void province_init(); // Добавление нового полигона bool province_add(const SDL_Point *points, int num_points); // Рисование всех полигонов void province_draw(SDL_Renderer *renderer); #endif // EPROVINCE_HEProvince.c// EProvince.c #include "EProvince.h" #include <stdlib.h> #include <time.h> // Массив провинций #define MAX_PROVINCES 100 static Province provinces[MAX_POLYGON_POINTS]; static int province_count = 0; // Инициализация генерации случайных цветов void province_init() { srand((unsigned int)time(NULL)); } // Генерация случайного цвета с фиксированной прозрачностью static void generate_random_color(Uint8 *r, Uint8 *g, Uint8 *b, Uint8 *a) { *r = rand() % 256; *g = rand() % 256; *b = rand() % 256; *a = 128; // Полупрозрачность (50%) } // Добавление нового полигона bool province_add(const SDL_Point *points, int num_points) { if (province_count >= MAX_POLYGONS || num_points < 3 || num_points > MAX_POLYGON_POINTS) return false; provinces[province_count].num_points = num_points; for (int i = 0; i < num_points; i++) { // Убедимся, что точки выровнены по пикселям (целочисленные координаты) provinces[province_count].points[i].x = points[i].x; provinces[province_count].points[i].y = points[i].y; } generate_random_color(&provinces[province_count].r, &provinces[province_count].g, &provinces[province_count].b, &provinces[province_count].a); province_count++; return true; } // Рисование всех полигонов void province_draw(SDL_Renderer *renderer) { for (int i = 0; i < province_count; i++) { Province *prov = &provinces[i]; // Устанавливаем цвет с прозрачностью SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND); SDL_SetRenderDrawColor(renderer, prov->r, prov->g, prov->b, prov->a); // Рисуем заполненный полигон // Используем SDL2_gfx для рисования заполненных полигонов // Необходимо убедиться, что библиотека SDL2_gfx подключена и добавлена в проект filledPolygonRGBA(renderer, (Sint16*)prov->points[0].x, (Sint16*)prov->points[0].y, prov->num_points, prov->r, prov->g, prov->b, prov->a); } }Примечания:
- Мы используем библиотеку
SDL2_gfxдля рисования заполненных полигонов. Убедитесь, что она установлена и подключена к вашему проекту. - Полигон ограничен 1000 точками и всего 100 полигонов. Эти значения можно изменить по необходимости.
- Цвет полигона генерируется случайным образом при добавлении.
3. Интеграция в основной код (
mainEditor.c)Теперь интегрируем систему провинций в основной цикл рендеринга. Также добавим возможность добавления полигонов с помощью мыши (например, по нажатию определенной клавиши или кнопки).
Обновленный
main.c(предполагается, что этоmainEditor.c):#include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <SDL2/SDL2_gfxPrimitives.h> #include <stdio.h> #include "zoom.h" #include "EProvince.h" #define WINDOW_WIDTH 800 #define WINDOW_HEIGHT 600 // Функция для генерации случайного цвета void generate_random_color(Uint8 *r, Uint8 *g, Uint8 *b, Uint8 *a) { *r = rand() % 256; *g = rand() % 256; *b = rand() % 256; *a = 128; // Полупрозрачность (50%) } int main(int argc, char *argv[]) { SDL_Window *window = NULL; SDL_Renderer *renderer = NULL; SDL_Texture *texture = NULL; SDL_Event event; int quit = 0; int image_width, image_height; // Инициализация SDL if (SDL_Init(SDL_INIT_VIDEO) < 0) { printf("SDL could not initialize! SDL_Error: %s\n", SDL_GetError()); return -1; } // Инициализация SDL_image if (!(IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG)) { printf("SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError()); SDL_Quit(); return -1; } // Создание окна window = SDL_CreateWindow("OpenAge Map Editor", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_RESIZABLE); if (window == NULL) { printf("Window could not be created! SDL_Error: %s\n", SDL_GetError()); IMG_Quit(); SDL_Quit(); return -1; } // Создание рендерера renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (renderer == NULL) { printf("Renderer could not be created! SDL_Error: %s\n", SDL_GetError()); SDL_DestroyWindow(window); IMG_Quit(); SDL_Quit(); return -1; } // Загрузка изображения SDL_Surface *loadedSurface = IMG_Load("./map/world/background.png"); if (loadedSurface == NULL) { printf("Unable to load image %s! SDL_image Error: %s\n", "./map/world/background.png", IMG_GetError()); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); IMG_Quit(); SDL_Quit(); return -1; } // Создание текстуры из поверхности texture = SDL_CreateTextureFromSurface(renderer, loadedSurface); if (texture == NULL) { printf("Unable to create texture from %s! SDL Error: %s\n", "./map/world/background.png", SDL_GetError()); SDL_FreeSurface(loadedSurface); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); IMG_Quit(); SDL_Quit(); return -1; } image_width = loadedSurface->w; image_height = loadedSurface->h; SDL_FreeSurface(loadedSurface); // Получение начального размера окна int window_width, window_height; SDL_GetWindowSize(window, &window_width, &window_height); // Инициализация зума и камеры init_zoom(image_width, image_height, window_width, window_height); // Инициализация системы провинций province_init(); // Переменные для рисования полигона #define MAX_POLYGON_POINTS 1000 SDL_Point current_polygon_points[MAX_POLYGON_POINTS]; int current_polygon_count = 0; bool drawing_polygon = false; // Основной цикл while (!quit) { // Обработка событий while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: quit = 1; break; case SDL_WINDOWEVENT: if (event.window.event == SDL_WINDOWEVENT_RESIZED) { // Обновление размера окна SDL_GetWindowSize(window, &window_width, &window_height); set_window_size(window_width, window_height); } break; case SDL_MOUSEBUTTONDOWN: if (event.button.button == SDL_BUTTON_LEFT) { if (SDL_GetModState() & KMOD_CTRL) { // Начало или продолжение рисования полигона if (current_polygon_count < MAX_POLYGON_POINTS) { current_polygon_points[current_polygon_count].x = event.button.x; current_polygon_points[current_polygon_count].y = event.button.y; current_polygon_count++; drawing_polygon = true; } } else { // Начало перетаскивания камеры start_camera_drag(event.button.x, event.button.y); } } break; case SDL_MOUSEBUTTONUP: if (event.button.button == SDL_BUTTON_LEFT) { if (!(SDL_GetModState() & KMOD_CTRL)) { // Окончание перетаскивания камеры stop_camera_drag(); } } break; case SDL_MOUSEMOTION: // Обновление перетаскивания камеры update_camera_drag(event.motion.x, event.motion.y); break; case SDL_MOUSEWHEEL: { // Получение позиции курсора int mouse_x, mouse_y; SDL_GetMouseState(&mouse_x, &mouse_y); // Зумирование if (event.wheel.y > 0) { zoom_in(mouse_x, mouse_y); } else if (event.wheel.y < 0) { zoom_out(mouse_x, mouse_y); } break; } case SDL_KEYDOWN: if (event.key.keysym.sym == SDLK_RETURN && drawing_polygon && current_polygon_count >= 3) { // Завершение рисования полигона province_add(current_polygon_points, current_polygon_count); current_polygon_count = 0; drawing_polygon = false; } break; default: break; } } // Обновление зума update_zoom(); // Получение исходного прямоугольника для рендеринга SDL_Rect src_rect = get_source_rect(); // Установка прямоугольника назначения (рендеринг растягивается на размер окна) SDL_Rect dst_rect; dst_rect.x = 0; dst_rect.y = 0; dst_rect.w = window_width; dst_rect.h = window_height; // Очистка рендерера SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); // Черный фон SDL_RenderClear(renderer); // Рендеринг текстуры карты SDL_RenderCopy(renderer, texture, &src_rect, &dst_rect); // Рисование провинций поверх карты province_draw(renderer); // Рисование текущего рисуемого полигона (если есть) if (drawing_polygon && current_polygon_count > 0) { // Устанавливаем цвет для временного полигона (белый) SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); // Рисуем линии между точками полигона for (int i = 0; i < current_polygon_count - 1; i++) { SDL_RenderDrawLine(renderer, current_polygon_points[i].x, current_polygon_points[i].y, current_polygon_points[i + 1].x, current_polygon_points[i + 1].y); } // Соединяем последнюю точку с первой if (current_polygon_count > 1) { SDL_RenderDrawLine(renderer, current_polygon_points[current_polygon_count - 1].x, current_polygon_points[current_polygon_count - 1].y, current_polygon_points[0].x, current_polygon_points[0].y); } } // Обновление экрана SDL_RenderPresent(renderer); // Задержка для контроля частоты кадров SDL_Delay(16); // Приблизительно 60 кадров в секунду } // Очистка SDL_DestroyTexture(texture); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); IMG_Quit(); SDL_Quit(); return 0; }Объяснение изменений:
-
Инициализация системы провинций:
- Вызов
province_init()после инициализации зума.
- Вызов
-
Добавление полигонов:
- При нажатии левой кнопки мыши вместе с удерживанием
Ctrl(можно изменить комбинацию) точки добавляются в текущий полигон. - При нажатии клавиши
Enter, если текущий полигон содержит как минимум 3 точки, он добавляется в систему провинций и отображается поверх карты.
- При нажатии левой кнопки мыши вместе с удерживанием
-
Рендеринг полигонов:
- После рендеринга текстуры карты вызывается
province_draw(renderer), которая рисует все добавленные провинции. - Также рисуется текущий рисуемый пользователем полигон в белом цвете для визуализации процесса рисования.
- После рендеринга текстуры карты вызывается
-
Сохранение целостности точки под курсором при зуме:
- Используя исправленный
zoom.c, позиция камеры корректируется таким образом, чтобы точка под курсором оставалась неизменной при изменении уровня зума.
- Используя исправленный
-
Использование SDL2_gfx:
- Убедитесь, что библиотека
SDL2_gfxподключена к вашему проекту. Для этого может потребоваться установка библиотеки и добавление флага-lSDL2_gfxпри компиляции.
- Убедитесь, что библиотека
Пример компиляции
Если вы используете
gcc, пример команды для компиляции может выглядеть следующим образом:gcc main.c zoom.c EProvince.c -o mainEditor -lSDL2 -lSDL2_image -lSDL2_gfxДополнительные улучшения
-
Сохранение и загрузка полигонов:
- Можно добавить функциональность для сохранения созданных полигонов в файл и загрузки их при запуске редактора.
-
Редактирование полигонов:
- Добавить возможность редактировать или удалять существующие полигоны.
-
Управление слоями:
- Если планируется добавление других элементов поверх карты, полезно организовать систему слоев для управления порядком отображения.
Заключение
Теперь ваш редактор карты поддерживает корректное зумирование без нежелательных сдвигов и позволяет пользователю рисовать полигоны поверх карты с полупрозрачными случайными цветами. Убедитесь, что все библиотеки (
SDL2,SDL2_image,SDL2_gfx) правильно установлены и подключены к вашему проекту. -