Write the Province class in C++ and raylib.
There should be functions:
drawProvince with the following arguments: Raylib color(Fill color), float stroke thickness, stroke type(dotted line, solid by default, float stroke thickness. This function loads and displays polygons from a file provinces.txt . This function reads the province id (the first line) through the for loop and then reads the coordinates from the next two lines, where the first line is the coordinates of the points in X, and the second is the coordinates of the points in Y. Both coordinates must be of type int. After that, the province is displayed in the raylib window. Implement polygon selection using the standard C++ library and raylib on Linux.
drawPoints, which allows you to draw new points of the province when the mouse is clicked from raylib until Enter is pressed. After pressing Enter, the dots are drawn for the new province. Polygon points should be drawn using raylib world coordinates.
deletePoints, this function deletes the extreme point of the province being drawn during the execution of drawPoints, this function can be performed several times until all the points are deleted.
savePointsToFile, which should also be called using the keyboard button press event from Raylib, by default it will be Enter. When called, this function will save the polygon province to a new file named provinces in txt format. 3 lines are allocated for each province: the first one is the coordinates of the points of the province in x, which are listed through the symbol ';', the second line is the coordinates of the points of the province in Y, which are listed through the symbol ';'.
deleteProvince - This function deletes the entire province by clicking the left mouse button on the fill of a certain province. It removes it from both memory and display, as well as from provinces.txt if she is registered there.
My future code with the main function will interact with this class.
Assistant
User
Assistant
User
The DrawPolyEx ID is still not defined in Province.cpp does it need to be added to hpp?
Assistant
User
не существует подходящего определяемого пользователем преобразования из "std::vector<Province::Point, std::allocatorProvince::Point>" в "const std::vector<Vector2, std::allocator>" error in Provinces.cpp
Assistant
The error message you've encountered indicates that there is no suitable user-defined conversion from std::vector<Province::Point, std::allocator<Province::Point>> to const std::vector<Vector2, std::allocator<Vector2>>. This occurs because the Province class uses its own Point structure, but the DrawPolyEx function you are trying to use expects a vector of raylib's Vector2 structures.
To solve this problem, you'll need to convert your std::vector<Province::Point> to a before calling . Here's how you can do this:
User
Identifier strokeType isn't declared, fix it
Assistant
User
Province.cpp:58:29: ошибка: no matching function for call to «std::vector::push_back(Province::Point)»
58 | points.push_back(Point{x, y});
Assistant
The error you're encountering indicates that you're trying to push a Province::Point object into a std::vector<Vector2>, which is incorrect because the vector expects objects of type Vector2, not Province::Point.
This occurs in the context where you are handling mouse click events to add new points to a representation of a province. The mistake lies in not converting instances to before pushing them into the vector expected by Raylib functions.
User
отсутствуют экземпляры перегруженная функция "std::vector<_Tp, _Alloc>::push_back [с _Tp=Province::Point, _Alloc=std::allocatorProvince::Point]", соответствующие списку аргументов
Assistant
User
Assistant
User
Assistant
User
Assistant
User
Assistant
User
Как получить случайный цвет fillColor для drawProvince с помощью raylib. Цвет должен быть случайны для каждой новой провинции. Добавь это в функцию drawProvince
Assistant
Для генерации случайного цвета в библиотеке raylib, вы можете использовать функцию GetRandomValue для получения случайного значения для каждого из каналов цвета (красный, зеленый, синий). Далее, с использованием этих значений, вы можете создать новый цвет с помощью функции Color из raylib.
Давайте внесем изменения в метод drawProvince класса Province, чтобы для каждой отрисовываемой провинции был задействован случайный цвет:
void Province::drawProvince() const {
// Генерация случайного цвета для этой провинции
Color fillColor = (Color){ GetRandomValue(0, 255), GetRandomValue(0, 255),
GetRandomValue(0, 255), 255 }; // 255 в конце — это значение альфа-канала (непрозрачность)
if (points.size() >= 3) { // Минимально требуемое количество точек для рисования многоугольника
int pointsCount = static_cast<int>(points.size());
Vector2 pointsVec[pointsCount];
for (int i = 0; i < pointsCount; i++) {
pointsVec[i] = {points[i].x, points[i].y};
}
// Рисуем многоугольник с помощью полученного случайного цвета
DrawPolyEx(pointsVec, pointsCount, fillColor);
// Если требуется рисовать контур, добавьте здесь соответствующий код...
}
}
User
Assistant
Основываясь на предоставленном коде, есть несколько моментов, которые могут влиять на отображение провинций на экране:
Проверка Имплементации Province::drawProvince: Убедитесь, что в методе drawProvince действительно выполняется отрисовка. Проверьте, корректно ли вы работаете с координатами точек и правильно ли используете функции raylib для отрисовки. Убедитесь, что содержит достаточно точек для визуализации.
User
Что не так с функцией drawProvince?:
void Province::drawProvince(Color fillColor, bool drawStroke, Color strokeColor, float strokeThickness) {
for (const auto& province : provinces) {
std::vector raylibPoints; // Преобразование точек Province::Point в Vector2 для Raylib
for (const auto& point : province) {
raylibPoints.push_back({static_cast<float>(point.x), static_cast<float>(point.y)});
}
// Заполнение полигона
DrawPolyEx(raylibPoints, fillColor, strokeColor, drawStroke);
// Если требуется рисовать контур
if(drawStroke) {
for(size_t i = 0; i < raylibPoints.size(); i++) {
Vector2 start = raylibPoints[i];
Vector2 end = raylibPoints[(i + 1) % raylibPoints.size()]; // Замыкание контура
DrawLineEx(start, end, strokeThickness, strokeColor);
}
}
}
}
Assistant
Функция drawProvince в вашем вопросе кажется корректной с точки зрения логики отрисовки с использованием библиотеки raylib. Однако, есть несколько потенциальных вопросов и предложений:
1. Неопределенная функция DrawPolyEx
Функция DrawPolyEx не является частью стандартного API Raylib. Возможно, это функция, определенная в или другой пользовательской библиотеке. Убедитесь, что данная функция корректно определена и работает как ожидается. Если должна обрабатывать массив точек и цвет заливки, возможно, вам потребуется реализовать её самостоятельно или использовать стандартные функции Raylib для рисования геометрических фигур, например, .
User
Вот код функции DrawPolyEx, который я переписал в Provinces.cpp:
void DrawPolyEx(const std::vector& points, Color fillColor, Color strokeColor, bool drawStroke) {
if (points.size() < 3) return;
// Drawing polygon fill
for (size_t i = 0; i < points.size() - 1; i++) {
for (size_t j = i + 1; j < points.size(); j++) {
DrawTriangle(points[0], points[i], points[j], fillColor);
}
}
// Drawing polygon stroke
if (drawStroke) {
for (size_t i = 0; i < points.size() - 1; i++) {
DrawLineEx(points[i], points[i + 1], 2.0f, strokeColor);
}
DrawLineEx(points.back(), points[0], 2.0f, strokeColor);
}
}
Assistant
По данному коду функции , есть несколько моментов для улучшения и исправления:
User
main.cpp:43:46: предупреждение: narrowing conversion of «GetRandomValue(0, 255)» from «int» to «unsigned char» [-Wnarrowing]
43 | Color fillColor = (Color){ GetRandomValue(0, 255), GetRandomValue(0, 255), GetRandomValue(0, 255), 255 };
| ~~~~~~~~~~~~~~^~~~~~~~
main.cpp:43:70: предупреждение: narrowing conversion of «GetRandomValue(0, 255)» from «int» to «unsigned char» [-Wnarrowing]
43 | Color fillColor = (Color){ GetRandomValue(0, 255), GetRandomValue(0, 255), GetRandomValue(0, 255), 255 };
| ~~~~~~~~~~~~~~^~~~~~~~
main.cpp:43:94: предупреждение: narrowing conversion of «GetRandomValue(0, 255)» from «int» to «unsigned char» [-Wnarrowing]
43 | Color fillColor = (Color){ GetRandomValue(0, 255), GetRandomValue(0, 255), GetRandomValue(0, 255), 255 };
Возможно из-за случайного цвета я не вижу заливку, как это исправить?
Assistant
В предупреждении компилятора указывается на узкое преобразование (narrowing conversion) из типа int в unsigned char при создании структуры Color. В библиотеке raylib структура Color определена таким образом, что ожидает значения компонентов цветов (красный, зелёный, синий и альфа-канал) в виде unsigned char, который может содержать значения от 0 до 255.
Чтобы убрать это предупреждение и гарантировать корректное преобразование значений, вы можете использовать явное приведение типа к unsigned char при передаче результатов вызова функции в конструктор структуры . Это явное приведение типа гарантирует, что значения, возвращаемые функцией , будут корректно интерпретироваться как , не вызывая предупреждения компилятора о узком преобразовании.
Теперь код отрисовки в main.cpp выглядит так, но полигон не отрисовывается при кликах левой кнопки мыши, нужно ли обновлять видимость полигонов после клика?
Assistant
Похоже, что проблема кроется в порядке вызовов функций внутри вашего главного отрисовочного цикла. Вызов ClearBackground(RAYWHITE); повторяется дважды, и второй вызов происходит после BeginMode2D, что фактически очищает всё, что было нарисовано до этого момента внутри блока BeginMode2D/EndMode2D. К тому же, такой порядок вызовов может привести к неожиданным эффектам в отрисовке, ведь обычно очистка фона выполняется в самом начале блока BeginDrawing.
Вот как должен выглядеть улучшенный и исправленный код отрисовки в вашем , где фон очищается один раз перед всеми операциями отрисовки:
Incorporating all requested functionalities into a Province class using C++ and raylib, here's a guideline on how to create such a class. Note, due to complexity and broadness of the question, some simplifications are made, and assumptions are stated, where necessary. This guide assumes you have basic knowledge of raylib and C++.
Header file: Province.hpp
#ifndef PROVINCE_HPP
#define PROVINCE_HPP
#include "raylib.h"
#include <vector>
#include <string>
class Province {
public:
Province();
~Province();
void drawProvince(Color fillColor, float strokeThickness, int strokeType);
void drawPoints();
void deletePoints();
void savePointsToFile(std::string filename);
bool deleteProvince(Vector2 mousePoint);
void loadProvincesFromFile(std::string filename);
private:
struct Point {
int x, y;
};
std::vector<Point> points; // Points of the province being drawn or manipulated
std::vector<std::vector<Point>> provinces; // List of provinces loaded from file
void parseLineToPoints(const std::string& lineX, const std::string& lineY);
};
#endif // PROVINCE_HPP
Implementation: Province.cpp
This implementation provides the skeleton of functions. Specific logic, especially for complex interaction like deleting a province based on mouse clicks, is simplified.
#include "Province.hpp"
#include <fstream>
#include <sstream>
Province::Province() {}
Province::~Province() {}
void Province::drawProvince(Color fillColor, float strokeThickness, int strokeType) {
for (const auto& province : provinces) {
int pointsCount = static_cast<int>(province.size());
if(pointsCount < 3) continue; // Ensure it's at least a triangle
Vector2 pointsVec[pointsCount];
for (int i = 0; i < pointsCount; i++) {
pointsVec[i] = {static_cast<float>(province[i].x), static_cast<float>(province[i].y)};
}
// Fill Polygon
DrawPolyEx(pointsVec, pointsCount, fillColor);
// Stroke Polygon
for (int i = 0; i < pointsCount; i++) {
Vector2 start = pointsVec[i];
Vector2 end = pointsVec[(i + 1) % pointsCount]; // Ensure closing the polygon
if(strokeType == 0) { // Solid
DrawLineEx(start, end, strokeThickness, BLACK);
} else if(strokeType == 1) { // Dotted
// Dotted line drawing might require custom implementation
}
}
}
}
void Province::drawPoints() {
// Placeholders for coordinates
int x, y;
while (!IsKeyPressed(KEY_ENTER)) {
if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT)) {
Vector2 mousePos = GetMousePosition();
x = static_cast<int>(mousePos.x);
y = static_cast<int>(mousePos.y);
points.push_back(Point{x, y});
}
}
// Assuming you save after finishing
provinces.push_back(points); // Add currently drawn points as a province
points.clear(); // Clear current province points for next drawing
}
void Province::deletePoints() {
if (!points.empty()) {
points.pop_back();
}
}
void Province::savePointsToFile(std::string filename) {
std::ofstream outFile(filename, std::ios::app); // Appends to file
if (outFile.is_open()) {
for (const auto& province : provinces) {
for (const auto& point : province) {
outFile << point.x << ';';
}
outFile << "\n";
for (const auto& point : province) {
outFile << point.y << ';';
}
outFile << "\n";
}
}
outFile.close();
}
bool Province::deleteProvince(Vector2 mousePoint) {
// Simplified; should include logic to determine if point is inside a province's polygon and remove it.
// This function just demonstrates a possible interface.
return false;
}
void Province::loadProvincesFromFile(std::string filename) {
std::ifstream inFile(filename);
std::string lineX, lineY;
while (std::getline(inFile, lineX) && std::getline(inFile, lineY)) {
parseLineToPoints(lineX, lineY);
}
}
void Province::parseLineToPoints(const std::string& lineX, const std::string& lineY) {
std::vector<Point> newProvince;
std::stringstream ssX(lineX), ssY(lineY);
std::string itemX, itemY;
while (getline(ssX, itemX, ';') && getline(ssY, itemY, ';')) {
if (!itemX.empty() && !itemY.empty()) {
Point newPoint{std::stoi(itemX), std::stoi(itemY)};
newProvince.push_back(newPoint);
}
}
provinces.push_back(newProvince);
}
Key Simplifications & Assumptions:
Real-time drawing is assumed to end when ENTER is pressed; user interaction is highly dependent on raylib functions like IsKeyPressed and IsMouseButtonPressed.
The function drawProvince allows for basic rendering with options for filled color and stroke styles. The stroke style customization, especially for dotted lines, is left abstract since raylib doesn't natively support dotted lines; it requires a custom implementation.
deleteProvince function notionally shows interface design - actual geometric computation (point-in-polygon test) is needed to determine if a mouse click is inside a province's area.
File operations do not handle all edge cases; file formatting and error checking are minimal for clarity.
This guide prioritizes demonstrating function interfaces and basic mechanics; it omits full error handling and complex geometry calculations for simplicity.
For a complete solution, especially for the more complex polygon-based interactions, further comprehensive geometrical algorithms and raylib-specific handling are required.
How to use the DrawPolyEx function from a file main.cpp in the file Province.cpp main.cpp I will provide below:
void DrawPolyEx(const std::vector& points, Color fillColor, Color strokeColor, bool drawStroke) {
if (points.size() < 3) return;
// Drawing polygon fill
for (size_t i = 0; i < points.size() - 1; i++) {
for (size_t j = i + 1; j < points.size(); j++) {
DrawTriangle(points[0], points[i], points[j], fillColor);
}
}
// Drawing polygon stroke
if (drawStroke) {
for (size_t i = 0; i < points.size() - 1; i++) {
DrawLineEx(points[i], points[i + 1], 2.0f, strokeColor);
}
DrawLineEx(points.back(), points[0], 2.0f, strokeColor);
}
}
int main() {
const int screenWidth = 800;
const int screenHeight = 450;
SetConfigFlags(FLAG_WINDOW_RESIZABLE | FLAG_VSYNC_HINT);
InitWindow(screenWidth, screenHeight, "OpenAge map editor");
SetTargetFPS(60);
Camera2D camera = { 0 };
camera.offset = { screenWidth / 2.0f, screenHeight / 2.0f };
camera.target = { screenWidth / 2.0f, screenHeight / 2.0f };
camera.rotation = 0.0f;
float smoothTime = 30.0f;
float camSmoothTime = 30.0f; // The time it should take to reach the target
Texture2D background = LoadTexture("background.png");
Vector2 mousePosition = GetScreenToWorld2D(GetMousePosition(), camera);
while (!WindowShouldClose()) {
mousePosition.x = roundf(mousePosition.x);
mousePosition.y = roundf(mousePosition.y);
Vector2 mousePosition = GetMousePosition();
Vector2 worldMousePos = GetScreenToWorld2D(mousePosition, camera);
// Получаем изменение положения колесика мыши
float wheelMove = GetMouseWheelMove();
if (wheelMove != 0) {
float previousZoom = camera.zoom;
// Определение и обновление уровня зума камеры
camera.zoom += wheelMove * 0.05f; // Изменяем зум
camera.zoom = fmaxf(camera.zoom, 0.20f); // Ограничиваем минимальный зум
camera.zoom = fminf(camera.zoom, 40.0f); // Ограничиваем максимальный зум
// Рассчитываем изменение зума
float zoomDiff = camera.zoom / previousZoom;
// Получаем вектор смещения от текущего таргета к курсору и корректируем положение таргета камеры
// В зависимости от масштабирования
if (wheelMove > 0) { // Если приближаем
camera.target.x -= (worldMousePos.x - camera.target.x) * (1.0f - zoomDiff);
camera.target.y -= (worldMousePos.y - camera.target.y) * (1.0f - zoomDiff);
} else { // Если отдаляем
camera.target.x += (worldMousePos.x - camera.target.x) * (zoomDiff - 1.0f);
camera.target.y += (worldMousePos.y - camera.target.y) * (zoomDiff - 1.0f);
}
}
// Smooth camera movement
if (IsMouseButtonDown(MOUSE_BUTTON_RIGHT))
{
Vector2 delta = GetMouseDelta();
Vector2 target = (Vector2){ camera.target.x - delta.x / camera.zoom, camera.target.y - delta.y / camera.zoom };
// Interpolate the current target towards the new target
camera.target.x += (target.x - camera.target.x) * smoothTime * GetFrameTime();
camera.target.y += (target.y - camera.target.y) * smoothTime * GetFrameTime();
float minX = -camera.offset.x;
float minY = -camera.offset.y;
float maxX = background.width + camera.offset.x;
float maxY = background.height + camera.offset.y;
// Ensure the target position is within the allowed range
camera.target.x = (target.x < minX) ? minX : (target.x > maxX) ? maxX : target.x;
camera.target.y = (target.y < minY) ? minY : (target.y > maxY) ? maxY : target.y;
// Interpolate the current target towards the new target
camera.target.x += (camera.target.x - camera.target.x) * smoothTime * GetFrameTime();
camera.target.y += (camera.target.y - camera.target.y) * smoothTime * GetFrameTime();
}
BeginDrawing();
ClearBackground(RAYWHITE);
BeginMode2D(camera);
DrawTextureEx(background, {0, 0}, 0.0f, 1.0f, WHITE);
EndMode2D();
EndDrawing();
}
UnloadTexture(background);
CloseWindow();
return 0;
}
Given the provided main.cpp file, I'll demonstrate how you could integrate the custom DrawPolyEx function for polygon drawing with a Province class example as discussed. To integrate, it is apparent that the DrawPolyEx function you provided uses std::vector<Vector2> for polygon points, which needs to be adopted in the Province class for consistency.
I'll adjust the given example slightly to fit within the raylib framework you're working with and show how the Province class could be integrated into your main.cpp.
Adjusting the Province Class
Given the DrawPolyEx from main.cpp, we see it takes a std::vector<Vector2> for points, a Color for the fill, a Color for the stroke, and a boolean to indicate if the stroke should be drawn. To use this in Province.cpp, we'll modify its implementation to fit with your custom drawing function.
Here's how the adjusted Province class can be modified to use std::vector<Vector2> and the custom DrawPolyEx. Firstly, the signature of the drawing function in Province should adapt to utilize the same vector structure:
Province.hpp
Adjust the header file, if necessary. Most noteworthy changes would be the method signatures and perhaps point storage:
#ifndef PROVINCE_HPP
#define PROVINCE_HPP
#include "raylib.h"
#include <vector>
class Province {
public:
Province();
~Province();
void drawProvince(Color fillColor, Color strokeColor, bool drawStroke);
void drawPoints(Camera2D camera); // Example method accepting a camera for conversion
// Other methods here...
private:
std::vector<Vector2> points; // Adjusted to use Vector2 for compatibility
// Other members...
};
#endif // PROVINCE_HPP
Adjustments in Province.cpp
Since the primary focus is on utilizing the DrawPolyEx function, the drawProvince method would look something like this:
#include "Province.hpp"
// Include other necessary headers...
void Province::drawProvince(Color fillColor, Color strokeColor, bool drawStroke) {
// Use the provided custom DrawPolyEx method from `main.cpp`
DrawPolyEx(points, fillColor, strokeColor, drawStroke);
}
// Implement other methods...
Integrating in Main.cpp
After integrating the Province class, you could create, manipulate, and render Province instances within main.cpp. Notice the DrawPolyEx function is already defined in your main.cpp, so make sure to instantiate and use your Province objects correctly. Here's a snippet on how you might integrate it:
#include "raylib.h"
#include "/home/danya/raylib/src/raylib.h"
// Include Province class
#include "Province.hpp"
int main() {
// Initialization code...
std::vector<Vector2> points = {{100, 100}, {200, 100}, {150, 150}}; // Example points
Province myProvince;
// Assume there's a way to set points or myProvince was constructed with points
while (!WindowShouldClose()) {
// Other drawing code...
// Draw example province
myProvince.drawProvince(GREEN, BLACK, true);
// Finish drawing
EndDrawing();
}
// De-initialization code...
return 0;
}
Essentially, by adjusting the class structure and data types, you enable the Province class to utilize your custom polygon drawing method seamlessly.
Please, merge and adjust the snippets above accordingly, as direct full integration would require modifying and potentially refactoring parts of your existing Province class not shown in the question. Remember, this approach assumes the Province class will manage or store its own points in a format compatible with your custom DrawPolyEx function as part of the class design.
Given the nature of the DrawPolyEx function as it's custom-defined in your main.cpp, and considering the split between your Province.cpp/Province.hpp and main.cpp, there are a couple of methods to make DrawPolyEx accessible in your Province.cpp.
Method 1: Move DrawPolyEx into a Common Header File
You could create a common header file that declares and defines DrawPolyEx, which would then be included in both main.cpp and Province.cpp.
Steps:
Create a Header File:CommonDrawFunctions.hpp
Here, you'll declare and define DrawPolyEx. Since DrawPolyEx involves template code (due to the usage of std::vector<Vector2>), it's practical to include both the declaration and the definition in the header.
CommonDrawFunctions.hpp:
#ifndef COMMON_DRAW_FUNCTIONS_HPP
#define COMMON_DRAW_FUNCTIONS_HPP
#include "raylib.h"
#include <vector>
// Declare and define DrawPolyEx right in the header to avoid linker issues with templates
inline void DrawPolyEx(const std::vector<Vector2>& points, Color fillColor, Color strokeColor, bool drawStroke) {
if (points.size() < 3) return;
// Drawing polygon fill (elided for brevity)
// Drawing polygon stroke (elided for brevity)
}
#endif // COMMON_DRAW_FUNCTIONS_HPP
Include This Header in Both main.cpp and Province.cpp:
At the top of both main.cpp and Province.cpp, include this new header:
#include "CommonDrawFunctions.hpp"
Method 2: Define DrawPolyEx Inline in Province.hpp
If DrawPolyEx is specifically useful for the Province class, and you want to avoid global scope pollution or simply prefer containing related functionalities, you could define DrawPolyEx directly within Province.hpp if it's used within Province primarily.
Steps:
Add DrawPolyEx to Province.hpp:
This makes DrawPolyEx part of Province's interface, directly accessible to classes or functions including Province.hpp.
#ifndef PROVINCE_HPP
#define PROVINCE_HPP
#include "raylib.h"
#include <vector>
// Declare and define DrawPolyEx inside the Province header
inline void DrawPolyEx(const std::vector<Vector2>& points, Color fillColor, Color strokeColor, bool drawStroke) {
// Implementation...
}
class Province {
public:
Province();
~Province();
void drawProvince(Color fillColor, Color strokeColor, bool drawStroke);
// Other methods...
private:
std::vector<Vector2> points;
// Other members...
};
#endif // PROVINCE_HPP
No Other Changes Required:
Since Province.cpp includes Province.hpp, it automatically has access to DrawPolyEx.
Conclusion
Both methods are valid. The best approach depends on your project's structure and whether you think other parts of your project might benefit from having access to DrawPolyEx without necessarily dealing with Province objects. If DrawPolyEx is broadly useful beyond Province functionality, Method 1 is cleaner as it keeps utility functions separate, promoting good organization and reuse. Otherwise, Method 2 is a simple and quick way to ensure DrawPolyEx is accessible where needed without altering much of your project's structure.
std::vector<Vector2>
DrawPolyEx
Assuming your Province::Point structure looks something like this:
struct Point {
int x, y;
};
And you have a std::vector<Point> points; in your Province class that you want to convert to std::vector<Vector2> to use with DrawPolyEx, here is a modified version of the drawProvince method that performs the necessary conversion:
void Province::drawProvince(Color fillColor, Color strokeColor, bool drawStroke) {
std::vector<Vector2> raylibPoints;
for (const auto& point : points) {
// Convert each Province::Point to Vector2 and add it to the new vector
raylibPoints.push_back({static_cast<float>(point.x), static_cast<float>(point.y)});
}
// Now you can call DrawPolyEx with raylibPoints
DrawPolyEx(raylibPoints, fillColor, strokeColor, drawStroke);
}
This code iterates through your std::vector<Province::Point> and converts each Province::Point to a Vector2 before pushing it back to a new std::vector<Vector2>, which is then passed to the DrawPolyEx function.
This approach ensures type compatibility between your Province class' internal representation of points and the Vector2 type expected by DrawPolyEx. Remember, when dealing with graphics libraries or any external API, type compatibility is crucial for successful function calls and data handling.
The issue you pointed out refers to the strokeType identifier that was earlier described in a conceptual draft for drawing provinces, where it was intended to indicate whether the stroke should be solid or dotted. However, it seems I mistakenly included strokeType in a context where it wasn't clearly defined or implemented, particularly concerning raylib functions and the custom DrawPolyEx function provided. Let's address this oversight by adjusting the implementation to exclude strokeType, focusing instead on providing a solid or dotted stroke based on a boolean flag or simulating it with the tools raylib offers.
Given raylib does not natively support dotted lines directly through its API, let's refactor the prototype by removing strokeType and instead show how you can render strokes with the available raylib functions. We'll use a solid line for simplicity, as a dotted line would require custom logic to implement.
Adjusted Function Signature in Province Class
Assuming we have a Province class with methods to draw filled polygons with optional strokes, we simplify by removing strokeType:
// Province::drawProvince now simplified without strokeType
void drawProvince(Color fillColor, bool drawStroke, Color strokeColor, float strokeThickness);
Adjusted Example Implementation:
void Province::drawProvince(Color fillColor, bool drawStroke, Color strokeColor, float strokeThickness) {
std::vector<Vector2> raylibPoints;
// Assuming 'points' stores the vertices of the province
for (const auto& point : points) {
raylibPoints.push_back({static_cast<float>(point.x), static_cast<float>(point.y)});
}
// Now you can call DrawPolyEx with raylibPoints for the fill
DrawPolyEx(raylibPoints, fillColor, strokeColor, drawStroke);
// If a stroke is desired, add logic for drawing the stroke
if(drawStroke) {
for(size_t i = 0; i < raylibPoints.size(); i++) {
// Draw lines between consecutive points. Loops back to the start for closure
Vector2 start = raylibPoints[i];
Vector2 end = raylibPoints[(i + 1) % raylibPoints.size()];
DrawLineEx(start, end, strokeThickness, strokeColor);
}
}
}
Notes on Implementing Dotted Lines:
Implementing dotted lines without native support involves manually calculating the points along the line and drawing small segments or points with gaps in between. This can be achieved with raylib's DrawLineEx or DrawPointEx functions, calculating the positions along the path where dots should appear. However, due to the complexity and variance on desired appearance, this implementation detail is omitted here in favor of focusing on the corrected strokeType misunderstanding.
By simplifying to focus on solid strokes and how to implement this with raylib, the confusion regarding strokeType is resolved. For dotted lines or more complex stroke types, consider implementing a function that iterates over line segments and draws segmented lines or dots based on custom logic for the desired pattern.
Province::Point
Vector2
Given a structure or class Province::Point with integer members x and y, and knowing that Raylib's Vector2 type also contains floating-point x and y fields, you must convert your custom point type to Raylib's expected type.
Given that your loop for adding points might look something like this (according to the initial error and context):
void Province::drawPoints() {
int x, y;
while (!IsKeyPressed(KEY_ENTER)) {
if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT)) {
Vector2 mousePos = GetMousePosition();
x = static_cast<int>(mousePos.x);
y = static_cast<int>(mousePos.y);
// Convert and add the point
Vector2 raylibPoint = {static_cast<float>(x), static_cast<float>(y)};
points.push_back(raylibPoint);
}
}
// Continue with the implementation...
}
This modification ensures that when you are adding a new point from mouse click events into your Province points vector (presumed for drawing with Raylib), you're pushing Vector2 instances which are compatible with Raylib's function expectations, such as your DrawPolyEx or any drawing function provided by Raylib.
Make sure your points vector is indeed declared as std::vector<Vector2> to match Raylib's expected types for functions involving point collections. This adjustment aligns your custom province drawing logic with the types and conventions used by Raylib, eliminating type mismatch issues such as the one you encountered.
This error message indicates that there's an attempt to use the push_back method with an argument type that does not match the expected type of the vector. Specifically, it shows the scenario where you might have a std::vector that is expected to store objects of type Province::Point, but there's an attempt to insert an object of a different type, causing a mismatch error.
Given the previous context, it seems you're attempting to use Vector2 types directly with a vector designed to hold Province::Point objects, or vice versa. To address the issue, ensure you're consistently using the correct type throughout your operations with the vector.
Let's clarify the solution focusing on ensuring proper usage of types:
Assuming the Definition of Province::Point
Let's assume Province::Point is defined within the Province class as follows:
class Province {
public:
struct Point {
int x, y;
};
// Other members and methods...
};
Handling the Addition of New Points
If you intend to collect points in response to mouse clicks and store them in a std::vector<Province::Point>, the addition of new points should correctly instantiate and push Province::Point objects into the vector.
Correctly Adding a Province::Point:
void Province::addPoint(int x, int y) {
points.push_back({x, y}); // Correctly adding a Province::Point to std::vector<Province::Point>
}
If Working with Vector2:
If there's a need to convert or use Vector2 types (for example, when interfacing with Raylib functions), ensure that conversions between Province::Point and Raylib::Vector2 are correctly performed at the boundaries where Raylib functions are called.
For instance, converting std::vector<Province::Point> to std::vector<Vector2> before using DrawPolyEx:
std::vector<Vector2> convertPointsToVector2(const std::vector<Province::Point>& points) {
std::vector<Vector2> vector2Points;
for (const auto& point : points) {
vector2Points.push_back({static_cast<float>(point.x), static_cast<float>(point.y)});
}
return vector2Points;
}
Then, when needing to use Raylib drawing functions, do the conversion:
auto vector2Points = convertPointsToVector2(provincePoints); // provincePoints is std::vector<Province::Point>
DrawPolyEx(vector2Points, fillColor, strokeColor, drawStroke);
Summary:
Ensure you're using the correct types consistent with your std::vector declarations when adding elements.
Perform conversions between Province::Point and Vector2 when necessary, especially at the interfaces between your application logic and Raylib functions.
This approach maintains type safety and clarity in your code, avoiding the type mismatch errors you've encountered.
void Province::addPoint(int x, int y) {
points.push_back({x, y}); // Correctly adding a Province::Point to std::vectorProvince::Point
}
void Province::drawProvince(Color fillColor, bool drawStroke, Color strokeColor, float strokeThickness) {
std::vector raylibPoints;
for (const auto& point : points) {
raylibPoints.push_back({static_cast(point.x), static_cast(point.y)});
}
for (const auto& province : provinces) {
int pointsCount = static_cast(province.size());
if(pointsCount < 3) continue; // Ensure it’s at least a triangle
Vector2 pointsVec[pointsCount];
for (int i = 0; i < pointsCount; i++) {
pointsVec[i] = {static_cast<float>(province[i].x), static_cast<float>(province[i].y)};
}
std::vector<Vector2> convertPointsToVector2(const std::vector<Province::Point>& points) {
std::vector<Vector2> vector2Points;
for (const auto& point : points) {
vector2Points.push_back({static_cast<float>(point.x), static_cast<float>(point.y)});
};
auto vector2Points = convertPointsToVector2(provincePoints); // provincePoints is std::vector<Province::Point>
DrawPolyEx(vector2Points, fillColor, strokeColor, drawStroke);
return vector2Points;
}
// Fill Polygon
DrawPolyEx(raylibPoints, fillColor, strokeColor, drawStroke);
if(drawStroke) {
for(size_t i = 0; i < raylibPoints.size(); i++) {
// Draw lines between consecutive points. Loops back to the start for closure
Vector2 start = raylibPoints[i];
Vector2 end = raylibPoints[(i + 1) % raylibPoints.size()];
DrawLineEx(start, end, strokeThickness, strokeColor);
if(drawStroke) {
for(size_t i = 0; i < raylibPoints.size(); i++) {
// Draw lines between consecutive points. Loops back to the start for closure
Vector2 start = raylibPoints[i];
Vector2 end = raylibPoints[(i + 1) % raylibPoints.size()];
DrawLineEx(start, end, strokeThickness, strokeColor);
}
}
}
}
}
}
void Province::drawPoints() {
int x, y;
while (!IsKeyPressed(KEY_ENTER)) {
if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT)) {
Vector2 mousePos = GetMousePosition();
x = static_cast(mousePos.x);
y = static_cast(mousePos.y);
// Convert and add the point
Vector2 raylibPoint = {static_cast<float>(x), static_cast<float>(y)};
points.push_back(raylibPoint);
}
}
// Assuming you save after finishing
provinces.push_back(points); // Add currently drawn points as a province
points.clear(); // Clear current province points for next drawing
}
void Province::deletePoints() {
if (!points.empty()) {
points.pop_back();
}
}
void Province::savePointsToFile(std::string filename) {
std::ofstream outFile(filename, std::ios::app); // Appends to file
if (outFile.is_open()) {
for (const auto& province : provinces) {
for (const auto& point : province) {
outFile << point.x << ';';
}
outFile << "\n";
for (const auto& point : province) {
outFile << point.y << ';';
}
outFile << "\n";
}
}
outFile.close();
}
bool Province::deleteProvince(Vector2 mousePoint) {
// Simplified; should include logic to determine if point is inside a province’s polygon and remove it.
// This function just demonstrates a possible interface.
return false;
}
while (getline(ssX, itemX, ';') && getline(ssY, itemY, ';')) {
if (!itemX.empty() && !itemY.empty()) {
Point newPoint{std::stoi(itemX), std::stoi(itemY)};
newProvince.push_back(newPoint);
}
}
provinces.push_back(newProvince);
}
Частично перепиши этот код так, чтобы у points была возможность выполнения push_back
Based on your detailed code and the error message you've encountered, it seems there's a misunderstanding in managing Point structures vs. Vector2 instances within the Province class and its methods. Let's clarify and correct the code for consistent handling of point types and ensure push_back can be called appropriately on your points vector.
Firstly, I'll consolidate your Point definition within the Province class and ensure it's used consistently. Then, I'll adjust the method implementations for compatibility.
Adjusted Province.hpp (Simplified)
Let's ensure the Province class correctly defines a Point structure if it's not already defined elsewhere correctly.
#ifndef PROVINCE_HPP
#define PROVINCE_HPP
#include "raylib.h"
#include <vector>
#include <string>
class Province {
public:
Province();
~Province();
struct Point {
int x, y;
};
void addPoint(int x, int y);
void drawProvince(Color fillColor, bool drawStroke, Color strokeColor, float strokeThickness);
void drawPoints();
void deletePoints();
void savePointsToFile(std::string filename);
bool deleteProvince(Vector2 mousePoint);
void loadProvincesFromFile(std::string filename);
private:
std::vector<std::vector<Point>> provinces; // Stores multiple provinces, each as a vector of Points
std::vector<Point> points; // Temporary storage for current drawing points
void parseLineToPoints(const std::string& lineX, const std::string& lineY);
};
#endif // PROVINCE_HPP
Adjusted Province.cpp (Corrected for push_back)
We'll simplify and correct your Province.cpp to ensure it uses Point objects correctly within Province, particularly for push_back.
Corrections:
Removed redundant conversion code and corrected the drawProvince method.
Adjusted addPoint and drawPoints for consistency.
#include "Province.hpp"
#include <fstream>
#include <sstream>
#include "CommonDrawFunctions.hpp" // Make sure this includes DrawPolyEx prototype
Province::Province() {}
Province::~Province() {}
void Province::addPoint(int x, int y) {
points.push_back({x, y}); // Correctly adding a Province::Point
}
void Province::drawProvince(Color fillColor, bool drawStroke, Color strokeColor, float strokeThickness) {
// Assuming you've filled 'provinces' with meaningful data
for (const auto& province : provinces) {
std::vector<Vector2> raylibPoints; // Convert Province::Point to Vector2 for Raylib
for (const auto& point : province) {
raylibPoints.push_back({static_cast<float>(point.x), static_cast<float>(point.y)});
}
// Use your custom DrawPolyEx or Raylib's drawing functions as needed
DrawPolyEx(raylibPoints, fillColor, strokeColor, drawStroke); // Adjust signature as needed
// Further drawing logic...
}
}
// Other methods...
void Province::drawPoints() {
// Method body...
// Use 'points' directly since it should already be std::vector<Point>
}
// Additional methods unchanged...
Main Points
Ensure Point structure is used within Province class consistently.
Use Vector2 for interfacing with Raylib drawing functions, converting Province::Point to Vector2 as needed.
Avoid nested functions (like convertPointsToVector2 within drawProvince) as this was likely unintended and syntactically incorrect.
This correction focuses on ensuring consistent usage of your Point structure for internal logic within Province and converting to Vector2 when interfacing with Raylib. push_back is used correctly with std::vector<Point> providing type-consistent usage within your class methods.
void Province::addPoint(int x, int y) {
points.push_back({x, y}); // Correctly adding a Province::Point
}
void Province::drawProvince(Color fillColor, bool drawStroke, Color strokeColor, float strokeThickness) {
// Assuming you’ve filled ‘provinces’ with meaningful data
for (const auto& province : provinces) {
std::vector raylibPoints; // Convert Province::Point to Vector2 for Raylib
for (const auto& point : province) {
raylibPoints.push_back({static_cast(point.x), static_cast(point.y)});
}
for (const auto& province : provinces) {
int pointsCount = static_cast(province.size());
if(pointsCount < 3) continue; // Ensure it’s at least a triangle
Vector2 pointsVec[pointsCount];
for (int i = 0; i < pointsCount; i++) {
pointsVec[i] = {static_cast<float>(province[i].x), static_cast<float>(province[i].y)};
}
std::vector<Vector2> convertPointsToVector2(const std::vector<Province::Point>& points) {
std::vector<Vector2> vector2Points;
for (const auto& point : points) {
vector2Points.push_back({static_cast<float>(point.x), static_cast<float>(point.y)});
};
auto vector2Points = convertPointsToVector2(provincePoints); // provincePoints is std::vector<Province::Point>
DrawPolyEx(vector2Points, fillColor, strokeColor, drawStroke);
return vector2Points;
}
// Fill Polygon
DrawPolyEx(raylibPoints, fillColor, strokeColor, drawStroke);
if(drawStroke) {
for(size_t i = 0; i < raylibPoints.size(); i++) {
// Draw lines between consecutive points. Loops back to the start for closure
Vector2 start = raylibPoints[i];
Vector2 end = raylibPoints[(i + 1) % raylibPoints.size()];
DrawLineEx(start, end, strokeThickness, strokeColor);
if(drawStroke) {
for(size_t i = 0; i < raylibPoints.size(); i++) {
// Draw lines between consecutive points. Loops back to the start for closure
Vector2 start = raylibPoints[i];
Vector2 end = raylibPoints[(i + 1) % raylibPoints.size()];
DrawLineEx(start, end, strokeThickness, strokeColor);
}
}
}
}
}
}
void drawPoints() {
int x, y;
while (!IsKeyPressed(KEY_ENTER)) {
if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT)) {
Vector2 mousePos = GetMousePosition();
x = static_cast(mousePos.x);
y = static_cast(mousePos.y);
// Convert and add the point
Vector2 raylibPoint = {static_cast<float>(x), static_cast<float>(y)};
points.push_back(raylibPoint);
}
}
// Assuming you save after finishing
provinces.push_back(points); // Add currently drawn points as a province
points.clear(); // Clear current province points for next drawing
}
void Province::deletePoints() {
if (!points.empty()) {
points.pop_back();
}
}
void Province::savePointsToFile(std::string filename) {
std::ofstream outFile(filename, std::ios::app); // Appends to file
if (outFile.is_open()) {
for (const auto& province : provinces) {
for (const auto& point : province) {
outFile << point.x << ';';
}
outFile << "\n";
for (const auto& point : province) {
outFile << point.y << ';';
}
outFile << "\n";
}
}
outFile.close();
}
bool Province::deleteProvince(Vector2 mousePoint) {
// Simplified; should include logic to determine if point is inside a province’s polygon and remove it.
// This function just demonstrates a possible interface.
return false;
}
while (getline(ssX, itemX, ';') && getline(ssY, itemY, ';')) {
if (!itemX.empty() && !itemY.empty()) {
Point newPoint{std::stoi(itemX), std::stoi(itemY)};
newProvince.push_back(newPoint);
}
}
provinces.push_back(newProvince);
}
Скорректируй в этом коде точки с запятой и фигурные скобки, а также укажи на возможные фатальные ошибки
Ваш код содержит несколько синтаксических и логических ошибок, включая неправильное использование точек с запятой и фигурных скобок, а также повторения определённых частей кода. Перейдем к исправлению:
Удаление Неправильного Объявления Функции внутри Метода:
В коде представлено некорректное объявление функции convertPointsToVector2 непосредственно внутри метода. В C++ нельзя объявлять функции внутри других функций таким образом. Если требуется такое преобразование, его нужно либо вынести в отдельный метод класса, либо выполнить непосредственно в коде, где это необходимо.
Исправление Дублирования Кода:
Удаление повторяющегося кода, который не только усложняет чтение, но и может привести к ошибкам при будущих изменениях кода.
Исправление Синтаксических Ошибок:
Правильное использование фигурных скобок и точек с запятой для обеспечения корректного синтаксиса C++.
Исправленный код:
Province.cpp
#include "Province.hpp"
#include <fstream>
#include <sstream>
#include "/home/danya/raylib/src/raylib.h"
#include "CommonDrawFunctions.hpp"
Province::Province() {}
Province::~Province() {}
void Province::addPoint(int x, int y) {
points.push_back({x, y}); // Добавление точки к временному хранению точек
}
void Province::drawProvince(Color fillColor, bool drawStroke, Color strokeColor, float strokeThickness) {
for (const auto& province : provinces) {
std::vector<Vector2> raylibPoints; // Преобразование точек Province::Point в Vector2 для Raylib
for (const auto& point : province) {
raylibPoints.push_back({static_cast<float>(point.x), static_cast<float>(point.y)});
}
// Заполнение полигона
DrawPolyEx(raylibPoints, fillColor, strokeColor, drawStroke);
// Если требуется рисовать контур
if(drawStroke) {
for(size_t i = 0; i < raylibPoints.size(); i++) {
Vector2 start = raylibPoints[i];
Vector2 end = raylibPoints[(i + 1) % raylibPoints.size()]; // Замыкание контура
DrawLineEx(start, end, strokeThickness, strokeColor);
}
}
}
}
void Province::drawPoints() {
int x, y;
while (!IsKeyPressed(KEY_ENTER)) {
if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT)) {
Vector2 mousePos = GetMousePosition();
x = static_cast<int>(mousePos.x);
y = static_cast<int>(mousePos.y);
// Добавление точки к вектору points
Point newPoint = {x, y};
points.push_back(newPoint);
}
}
// Предполагается сохранение после завершения
provinces.push_back(points); // Добавить текущие нарисованные точки как новую провинцию
points.clear(); // Очистить текущие точки провинции для следующего рисования
}
void Province::deletePoints() {
if (!points.empty()) {
points.pop_back();
}
}
void Province::savePointsToFile(std::string filename) {
std::ofstream outFile(filename, std::ios::app); // Дозапись в файл
if (outFile.is_open()) {
for (const auto& province : provinces) {
for (const auto& point : province) {
outFile << point.x << ';' << point.y << '\n';
}
outFile << "\n"; // Дополнительная пустая строка между провинциями
}
}
outFile.close();
}
bool Province::deleteProvince(Vector2 mousePoint) {
// Реализация удаления провинции, если точка mousePoint находится внутри неё (опущено для упрощения)
return false;
}
void Province::loadProvincesFromFile(std::string filename) {
std::ifstream inFile(filename);
std::string lineX, lineY;
while (std::getline(inFile, lineX) && std::getline(inFile, lineY)) {
parseLineToPoints(lineX, lineY);
}
}
void Province::parseLineToPoints(const std::string& lineX, const std::string& lineY) {
std::vector<Point> newProvince;
std::stringstream ssX(lineX), ssY(lineY);
std::string itemX, itemY;
while (getline(ssX, itemX, ';') && getline(ssY, itemY, ';')) {
if (!itemX.empty() && !itemY.empty()) {
Point newPoint {std::stoi(itemX), std::stoi(itemY)};
newProvince.push_back(newPoint);
}
}
provinces.push_back(newProvince);
}
Ключевые изменения:
Удален неправильно объявленный метод внутри другого метода.
Исправлена логика работы с точками и их добавлением.
Удалено дублирование кода.
Корректировки по форматированию и структуре кода для лучшей читаемости и поддержки.
int main() {
const int screenWidth = 800;
const int screenHeight = 450;
SetConfigFlags(FLAG_WINDOW_RESIZABLE | FLAG_VSYNC_HINT);
InitWindow(screenWidth, screenHeight, "OpenAge map editor");
SetTargetFPS(60);
Camera2D camera = { 0 };
camera.offset = { screenWidth / 2.0f, screenHeight / 2.0f };
camera.target = { screenWidth / 2.0f, screenHeight / 2.0f };
camera.rotation = 0.0f;
float smoothTime = 30.0f;
float camSmoothTime = 30.0f; // The time it should take to reach the target
Texture2D background = LoadTexture("background.png");
Vector2 mousePosition = GetScreenToWorld2D(GetMousePosition(), camera);
while (!WindowShouldClose()) {
mousePosition.x = roundf(mousePosition.x);
mousePosition.y = roundf(mousePosition.y);
Vector2 mousePosition = GetMousePosition();
Vector2 worldMousePos = GetScreenToWorld2D(mousePosition, camera);
// Получаем изменение положения колесика мыши
float wheelMove = GetMouseWheelMove();
if (wheelMove != 0) {
float previousZoom = camera.zoom;
// Определение и обновление уровня зума камеры
camera.zoom += wheelMove * 0.05f; // Изменяем зум
camera.zoom = fmaxf(camera.zoom, 0.20f); // Ограничиваем минимальный зум
camera.zoom = fminf(camera.zoom, 40.0f); // Ограничиваем максимальный зум
// Рассчитываем изменение зума
float zoomDiff = camera.zoom / previousZoom;
// Получаем вектор смещения от текущего таргета к курсору и корректируем положение таргета камеры
// В зависимости от масштабирования
if (wheelMove > 0) { // Если приближаем
camera.target.x -= (worldMousePos.x - camera.target.x) * (1.0f - zoomDiff);
camera.target.y -= (worldMousePos.y - camera.target.y) * (1.0f - zoomDiff);
} else { // Если отдаляем
camera.target.x += (worldMousePos.x - camera.target.x) * (zoomDiff - 1.0f);
camera.target.y += (worldMousePos.y - camera.target.y) * (zoomDiff - 1.0f);
}
}
// Smooth camera movement
if (IsMouseButtonDown(MOUSE_BUTTON_RIGHT))
{
Vector2 delta = GetMouseDelta();
Vector2 target = (Vector2){ camera.target.x - delta.x / camera.zoom, camera.target.y - delta.y / camera.zoom };
// Interpolate the current target towards the new target
camera.target.x += (target.x - camera.target.x) * smoothTime * GetFrameTime();
camera.target.y += (target.y - camera.target.y) * smoothTime * GetFrameTime();
float minX = -camera.offset.x;
float minY = -camera.offset.y;
float maxX = background.width + camera.offset.x;
float maxY = background.height + camera.offset.y;
// Ensure the target position is within the allowed range
camera.target.x = (target.x < minX) ? minX : (target.x > maxX) ? maxX : target.x;
camera.target.y = (target.y < minY) ? minY : (target.y > maxY) ? maxY : target.y;
// Interpolate the current target towards the new target
camera.target.x += (camera.target.x - camera.target.x) * smoothTime * GetFrameTime();
camera.target.y += (camera.target.y - camera.target.y) * smoothTime * GetFrameTime();
}
BeginDrawing();
ClearBackground(RAYWHITE);
BeginMode2D(camera);
DrawTextureEx(background, {0, 0}, 0.0f, 1.0f, WHITE);
EndMode2D();
EndDrawing();
}
UnloadTexture(background);
CloseWindow();
return 0;
}
Исправь в этом коде местоположение камеры при запуске. Она появляется неизвестно где, а должна появляться по центру загружаемого изображения
Чтобы камера при запуске приложения появлялась в центре загружаемого изображения, необходимо установить начальные значения camera.target с учётом размеров изображения. Для этого можно использовать ширину и высоту загруженной текстуры background. После загрузки текстуры, но до входа в основной цикл, следует установить camera.target в центр изображения.
Пример исправленного кода:
#include "/home/danya/raylib/src/raylib.h"
#include <cmath>
#include <vector>
#include <cstdlib>
#include "CommonDrawFunctions.hpp"
Vector2 Vector2Lerp(Vector2 v1, Vector2 v2, float amount) {
Vector2 result;
amount = 0.5f; // Это переопределение 'amount', возможно его стоит убрать или устанавливать заранее
result.x = v1.x + amount * (v2.x - v1.x);
result.y = v1.y + amount * (v2.y - v1.y);
return result;
}
int main() {
const int screenWidth = 800;
const int screenHeight = 450;
SetConfigFlags(FLAG_WINDOW_RESIZABLE | FLAG_VSYNC_HINT);
InitWindow(screenWidth, screenHeight, "OpenAge map editor");
SetTargetFPS(60);
Camera2D camera = { 0 };
// Инициализация камеры будет перенесена ниже после загрузки текстуры
Texture2D background = LoadTexture("background.png");
// Теперь устанавливаем цель камеры в центр загруженного изображения
camera.offset = { screenWidth / 2.0f, screenHeight / 2.0f };
camera.target = { background.width / 2.0f, background.height / 2.0f };
camera.rotation = 0.0f;
camera.zoom = 1.0f; // Начальный масштаб камеры
Vector2 mousePosition = GetScreenToWorld2D(GetMousePosition(), camera);
while (!WindowShouldClose()) {
mousePosition = GetScreenToWorld2D(GetMousePosition(), camera); // Исправление повторного объявления переменной
// Получаем изменение положения колесика мыши
float wheelMove = GetMouseWheelMove();
// Код обработки масштабирования и движения камеры...
BeginDrawing();
ClearBackground(RAYWHITE);
BeginMode2D(camera);
DrawTextureEx(background, {0, 0}, 0.0f, 1.0f, WHITE);
EndMode2D();
EndDrawing();
}
UnloadTexture(background);
CloseWindow();
return 0;
}
В этом исправлении:
camera.target устанавливается в центр изображения сразу после загрузки текстуры background, что гарантирует, что камера будет смотреть на центр изображения при запуске приложения.
Исправлена ошибка с повторным объявлением mousePosition в главном цикле, переменная должна обновляться без повторного объявления.
В коде присутствует строка, которая заранее переопределяет amount в функции Vector2Lerp, что может быть нецелесообразно, если предполагается использование параметра amount. Убедитесь, что логика использования amount соответствует вашим требованиям.
Vector2 Vector2Lerp(Vector2 v1, Vector2 v2, float amount) {
Vector2 result;
amount = 0.5f; // Это переопределение ‘amount’, возможно его стоит убрать или устанавливать заранее
result.x = v1.x + amount * (v2.x - v1.x);
result.y = v1.y + amount * (v2.y - v1.y);
return result;
}
int main() {
const int screenWidth = 800;
const int screenHeight = 450;
SetConfigFlags(FLAG_WINDOW_RESIZABLE | FLAG_VSYNC_HINT);
InitWindow(screenWidth, screenHeight, "OpenAge map editor");
SetTargetFPS(60);
Camera2D camera = { 0 };
camera.offset = { screenWidth / 2.0f, screenHeight / 2.0f };
camera.target = { screenWidth / 2.0f, screenHeight / 2.0f };
camera.rotation = 0.0f;
float smoothTime = 30.0f;
float camSmoothTime = 30.0f; // The time it should take to reach the target
Texture2D background = LoadTexture("background.png");
// Теперь устанавливаем цель камеры в центр загруженного изображения
camera.offset = { screenWidth / 2.0f, screenHeight / 2.0f };
camera.target = { background.width / 2.0f, background.height / 2.0f };
camera.rotation = 0.0f;
camera.zoom = 1.0f; // Начальный масштаб камеры
Vector2 mousePosition = GetScreenToWorld2D(GetMousePosition(), camera);
while (!WindowShouldClose()) {
mousePosition = GetScreenToWorld2D(GetMousePosition(), camera);
Vector2 mousePosition = GetMousePosition();
Vector2 worldMousePos = GetScreenToWorld2D(mousePosition, camera);
// Получаем изменение положения колесика мыши
float wheelMove = GetMouseWheelMove();
if (wheelMove != 0) {
float previousZoom = camera.zoom;
// Определение и обновление уровня зума камеры
camera.zoom += wheelMove * 0.05f; // Изменяем зум
camera.zoom = fmaxf(camera.zoom, 0.20f); // Ограничиваем минимальный зум
camera.zoom = fminf(camera.zoom, 40.0f); // Ограничиваем максимальный зум
// Рассчитываем изменение зума
float zoomDiff = camera.zoom / previousZoom;
// Получаем вектор смещения от текущего таргета к курсору и корректируем положение таргета камеры
// В зависимости от масштабирования
if (wheelMove > 0) { // Если приближаем
camera.target.x -= (worldMousePos.x - camera.target.x) * (1.0f - zoomDiff);
camera.target.y -= (worldMousePos.y - camera.target.y) * (1.0f - zoomDiff);
} else { // Если отдаляем
camera.target.x += (worldMousePos.x - camera.target.x) * (zoomDiff - 1.0f);
camera.target.y += (worldMousePos.y - camera.target.y) * (zoomDiff - 1.0f);
}
}
// Smooth camera movement
if (IsMouseButtonDown(MOUSE_BUTTON_RIGHT))
{
Vector2 delta = GetMouseDelta();
Vector2 target = (Vector2){ camera.target.x - delta.x / camera.zoom, camera.target.y - delta.y / camera.zoom };
// Interpolate the current target towards the new target
camera.target.x += (target.x - camera.target.x) * smoothTime * GetFrameTime();
camera.target.y += (target.y - camera.target.y) * smoothTime * GetFrameTime();
float minX = -camera.offset.x;
float minY = -camera.offset.y;
float maxX = background.width + camera.offset.x;
float maxY = background.height + camera.offset.y;
// Ensure the target position is within the allowed range
camera.target.x = (target.x < minX) ? minX : (target.x > maxX) ? maxX : target.x;
camera.target.y = (target.y < minY) ? minY : (target.y > maxY) ? maxY : target.y;
// Interpolate the current target towards the new target
camera.target.x += (camera.target.x - camera.target.x) * smoothTime * GetFrameTime();
camera.target.y += (camera.target.y - camera.target.y) * smoothTime * GetFrameTime();
}
BeginDrawing();
ClearBackground(RAYWHITE);
BeginMode2D(camera);
DrawTextureEx(background, {0, 0}, 0.0f, 1.0f, WHITE);
EndMode2D();
EndDrawing();
}
UnloadTexture(background);
CloseWindow();
return 0;
}
Встрой в этот код функцию drawProvince из класса Province, которая постоянно отображает провинции, drawPoints, которая рисует новую точку при нажатии левой кнопки мыши, а drawProvince её отображает и потом отображает всю провинцию и добавь функцию deletePoints вызываемую клавишей Backspace
Для внедрения функций drawProvince и drawPoints, а также добавления функциональности удаления точек по нажатию на клавишу Backspace в ваш код, нужен небольшой рефакторинг. Поскольку Province ещё не описан полностью в вашем контексте, я предложу упрощённый вариант класса Province и демонстрацию его использования в главной программе.
Начнём с определения класса Province:
// Province.hpp
#include "raylib.h"
#include <vector>
class Province {
public:
std::vector<Vector2> points; // Упрощённо используем Vector2 напрямую для удобства
void addPoint(Vector2 newPoint) {
points.push_back(newPoint);
}
void drawProvince() const {
for (size_t i = 0; i < points.size(); ++i) {
if (i > 0) {
// Рисуем линию между текущей точкой и предыдущей
DrawLineV(points[i-1], points[i], BLACK);
}
}
}
void deleteLastPoint() {
if (!points.empty()) {
points.pop_back();
}
}
};
Теперь интегрируем использование класса Province в вашу основную программу:
#include "/home/danya/raylib/src/raylib.h"
#include <cmath>
#include <vector>
#include <cstdlib>
#include "CommonDrawFunctions.hpp"
#include "Province.hpp" // Подключаем только что созданный класс
int main() {
// Инициализация окна и камеры (Пропущено для краткости)
Texture2D background = LoadTexture("background.png");
// Устанавливаем цель камеры в центр загруженного изображения
camera.offset = { screenWidth / 2.0f, screenHeight / 2.0f };
camera.target = { background.width / 2.0f, background.height / 2.0f };
Province province; // Экземпляр класса Province для работы с провинциями
while (!WindowShouldClose()) {
Vector2 worldMousePos = GetScreenToWorld2D(GetMousePosition(), camera);
// Реализация добавления новой точки по левому клику мыши
if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT)) {
province.addPoint(worldMousePos); // Добавляем точку к текущей провинции
}
// Реализация удаления последней точки по нажатию Backspace
if (IsKeyPressed(KEY_BACKSPACE)) {
province.deleteLastPoint();
}
BeginDrawing();
ClearBackground(RAYWHITE);
BeginMode2D(camera);
DrawTextureEx(background, {0, 0}, 0.0f, 1.0f, WHITE); // Отрисовка фона
province.drawProvince(); // Отрисовка провинции
EndMode2D();
EndDrawing();
}
// Очистка ресурсов и закрытие программы (Пропущено для краткости)
}
Этот подход предоставляет базовую реализацию для работы с провинциями: добавление новой точки по клику, удаление последней точки по нажатию клавиши и отрисовку текущей провинции. Вы можете дополнить и адаптировать этот пример под свои требования, расширяя функциональность класса Province и детализируя рендеринг.
Учтите, что функция GetRandomValue требует инициализации генератора случайных чисел вызовом SetRandomSeed, который лучше всего поместить в начало функции main. Это гарантирует, что каждый раз при запуске вашей программы будут генерироваться новые случайные значения.
Пример инициализации генератора случайных чисел в начале main:
int main() {
// Инициализация библиотеки
InitWindow(screenWidth, screenHeight, "Пример с случайными цветами");
SetRandomSeed(time(NULL)); // Инициализация генератора случайных чисел
// Основной цикл приложения
return 0;
}
Таким образом, для каждой новой провинции при её отрисовке будет генерироваться новый случайный цвет.
Vector2 Vector2Lerp(Vector2 v1, Vector2 v2, float amount) {
Vector2 result;
amount = 0.5f; // Это переопределение ‘amount’, возможно его стоит убрать или устанавливать заранее
result.x = v1.x + amount * (v2.x - v1.x);
result.y = v1.y + amount * (v2.y - v1.y);
return result;
}
int main() {
const int screenWidth = 800;
const int screenHeight = 450;
SetConfigFlags(FLAG_WINDOW_RESIZABLE | FLAG_VSYNC_HINT);
InitWindow(screenWidth, screenHeight, "OpenAge map editor");
SetRandomSeed(time(NULL));
SetTargetFPS(60);
Camera2D camera = { 0 };
camera.offset = { screenWidth / 2.0f, screenHeight / 2.0f };
camera.target = { screenWidth / 2.0f, screenHeight / 2.0f };
camera.rotation = 0.0f;
float smoothTime = 30.0f;
float camSmoothTime = 30.0f; // The time it should take to reach the target
Texture2D background = LoadTexture("background.png");
// Теперь устанавливаем цель камеры в центр загруженного изображения
camera.offset = { screenWidth / 2.0f, screenHeight / 2.0f };
camera.target = { background.width / 2.0f, background.height / 2.0f };
camera.rotation = 0.0f;
camera.zoom = 1.0f; // Начальный масштаб камеры
Vector2 mousePosition = GetScreenToWorld2D(GetMousePosition(), camera);
Province province;
Color fillColor = (Color){ GetRandomValue(0, 255), GetRandomValue(0, 255), GetRandomValue(0, 255), 255 };
while (!WindowShouldClose()) {
mousePosition = GetScreenToWorld2D(GetMousePosition(), camera);
Vector2 mousePosition = GetMousePosition();
Vector2 worldMousePos = GetScreenToWorld2D(mousePosition, camera);
// Получаем изменение положения колесика мыши
float wheelMove = GetMouseWheelMove();
if (wheelMove != 0) {
float previousZoom = camera.zoom;
// Определение и обновление уровня зума камеры
camera.zoom += wheelMove * 0.05f; // Изменяем зум
camera.zoom = fmaxf(camera.zoom, 0.20f); // Ограничиваем минимальный зум
camera.zoom = fminf(camera.zoom, 40.0f); // Ограничиваем максимальный зум
// Рассчитываем изменение зума
float zoomDiff = camera.zoom / previousZoom;
// Получаем вектор смещения от текущего таргета к курсору и корректируем положение таргета камеры
// В зависимости от масштабирования
if (wheelMove > 0) { // Если приближаем
camera.target.x -= (worldMousePos.x - camera.target.x) * (1.0f - zoomDiff);
camera.target.y -= (worldMousePos.y - camera.target.y) * (1.0f - zoomDiff);
} else { // Если отдаляем
camera.target.x += (worldMousePos.x - camera.target.x) * (zoomDiff - 1.0f);
camera.target.y += (worldMousePos.y - camera.target.y) * (zoomDiff - 1.0f);
}
}
// Smooth camera movement
if (IsMouseButtonDown(MOUSE_BUTTON_RIGHT))
{
Vector2 delta = GetMouseDelta();
Vector2 target = (Vector2){ camera.target.x - delta.x / camera.zoom, camera.target.y - delta.y / camera.zoom };
// Interpolate the current target towards the new target
camera.target.x += (target.x - camera.target.x) * smoothTime * GetFrameTime();
camera.target.y += (target.y - camera.target.y) * smoothTime * GetFrameTime();
float minX = -camera.offset.x;
float minY = -camera.offset.y;
float maxX = background.width + camera.offset.x;
float maxY = background.height + camera.offset.y;
// Ensure the target position is within the allowed range
camera.target.x = (target.x < minX) ? minX : (target.x > maxX) ? maxX : target.x;
camera.target.y = (target.y < minY) ? minY : (target.y > maxY) ? maxY : target.y;
// Interpolate the current target towards the new target
camera.target.x += (camera.target.x - camera.target.x) * smoothTime * GetFrameTime();
camera.target.y += (camera.target.y - camera.target.y) * smoothTime * GetFrameTime();
}
if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT)) {
province.addPoint(worldMousePos.x, worldMousePos.y); // Добавляем точку к текущей провинции
}
if (IsKeyPressed(KEY_BACKSPACE)) {
province.deletePoints();
}
BeginDrawing();
ClearBackground(RAYWHITE);
BeginMode2D(camera);
DrawTextureEx(background, {0, 0}, 0.0f, 1.0f, WHITE);
province.drawProvince(fillColor, true, BLACK, 0.25f);
EndMode2D();
EndDrawing();
}
UnloadTexture(background);
CloseWindow();
return 0;
}
Код в main.cpp не отображает провинции, хотя ошибок нет, в чем может быть проблема?
points
Передача Цвета: Вы передаёте переменную fillColor в drawProvince каждый раз при вызове. Если drawProvince не предполагает изменение цвета заливки каждый кадр, возможно, следует задавать цвет заливки менее динамически. Также убедитесь, что true, BLACK и 0.25f правильно обрабатываются в вашем методе, особенно значение толщины линии 0.25f — достаточно ли это значение видимо при текущем размере и масштабировании.
Масштабирование и Позиционирование в Camera2D: Камера может быть сфокусирована не там, где находятся ваша рисуемая геометрия. Дебаг-печать координат точек или временное отключение камеры (использование BeginMode2D без параметров или BeginMode2D с камерой, но без перемещения и масштабирования) помогут установить, видны ли объекты вообще.
Проверка Логики addPoint и deletePoints: Убедитесь, что addPoint корректно добавляет точки в Province::points, а deletePoints (возможно, в вашем случае должен быть deleteLastPoint) корректно удаляет. Для отладки можно временно добавить вывод в консоль размера points.size() после добавления и удаления точек.
Проверка Главного Цикла Обработки Событий: Убедитесь, что события клика мышью и нажатие клавиши Backspace обрабатываются корректно. Размещение принтов или отладочных сообщений внутри условных операторов поможет убедиться, что события считываются правильно.
Если после проверки этих пунктов проблема всё ещё не решена, рекомендуется упростить код до минимального варианта, который только рисует статический набор точек на экране, чтобы проверить, корректно ли работает отрисовка в принципе. Это поможет локализовать проблему.
"CommonDrawFunctions.hpp"
DrawPolyEx
DrawPoly
2. Ошибка в использовании DrawPolyEx
Если DrawPolyEx является вашей собственной функцией и предназначена для отрисовки сложных полигонов, убедитесь, что она принимает правильные аргументы. В стандартном API Raylib есть функция DrawPoly, которая работает немного иначе. Подробно рассмотрите, правильно ли использованы аргументы, и соответствуют ли они определению функции DrawPolyEx.
3. Цикл отрисовки контура
Логика цикла для отрисовки контура кажется корректной. Однако, учитывая, что вы используете (i + 1) % raylibPoints.size() для замыкания контура, это должно работать правильно и соединить последнюю точку с первой. Убедитесь, что strokeThickness и strokeColor заданы таким образом, чтобы контур был видимым на экране (например, strokeThickness не должен быть слишком мал).
4. Верификация данных
Удостоверьтесь, что в provinces действительно есть данные до вызова функции drawProvince и что точки в province заданы корректно. Если массив provinces пуст или содержит некорректные данные, отрисовка не будет выполнена, как ожидается.
Базовая проверка перед отрисовкой
Добавьте проверку на наличие достаточного количества точек для отрисовки:
if (raylibPoints.size() < 3) continue; // Пропускаем отрисовку, если точек меньше 3
Заключение
Если проблема не в одном из вышеперечисленных пунктов, то стоит проверить и другие части программы, которые могут влиять на отрисовку: инициализацию графической системы, состояние камеры и так далее.
DrawPolyEx
Ошибка При Рисовании Заливки Многоугольника
Исходный подход к рисованию заливки многоугольника через последовательное соединение вершин с первой точкой не всегда приведёт к правильному отображению заливки сложных многоугольников, особенно если многоугольник самопересекающийся или его вершины не следуют в порядке обхода по или против часовой стрелки.
Чтобы решить эту проблему правильно, можно воспользоваться функцией DrawTriangleFan, если такая имеется в вашей версии raylib, или же применить другой алгоритм, более подходящий для рисования многоугольников с заливкой.
Ошибка При Рисовании Контура Многоугольника
Ваш подход корректно рисует контур многоугольника, однако, стоит обратить внимание на то, что толщина линии контура (2.0f) задана жёстко. Вы могли бы использовать передаваемое в функцию значение strokeThickness для более гибкого управления этим параметром:
if (drawStroke) {
for (size_t i = 0; i < points.size() - 1; i++) {
DrawLineEx(points[i], points[i + 1], strokeThickness, strokeColor);
}
DrawLineEx(points.back(), points[0], strokeThickness, strokeColor);
}
Учитывая, что у вас уже имеется реализованный код, оставляю его почти без изменений, лишь предлагая использовать толщину линии из параметров.
Проверка размера массива точек
В самом начале функции вы правильно делаете проверку на минимальное количество точек для рисования многоугольника:
if (points.size() < 3) return;
Это отличная практика, предотвращающая попытки рисования несуществующих или некорректных геометрических фигур.
Итог
Улучшенный код функции DrawPolyEx, который использует strokeThickness для управления толщиной контурной линии:
void DrawPolyEx(const std::vector<Vector2>& points, Color fillColor, Color strokeColor, bool drawStroke) {
if (points.size() < 3) return; // Необходимо минимум 3 точки для многоугольника
// Drawing polygon fill
// Доработать алгоритм заливки, если необходимо
for (size_t i = 1; i < points.size() - 1; i++) {
DrawTriangle(points[0], points[i], points[i + 1], fillColor);
}
// Drawing polygon stroke
if (drawStroke) {
for (size_t i = 0; i < points.size() - 1; i++) {
DrawLineEx(points[i], points[i + 1], strokeThickness, strokeColor);
}
DrawLineEx(points.back(), points[0], strokeThickness, strokeColor);
}
}
Этот код должен корректно обрабатывать отрисовку как заливку многоугольника (при условии, что он выпуклый), так и его контур.
GetRandomValue
Color
GetRandomValue
unsigned char
Исправленная строка с использованием явного преобразования типа будет выглядеть следующим образом:
Color fillColor = (Color){
static_cast<unsigned char>(GetRandomValue(0, 255)),
static_cast<unsigned char>(GetRandomValue(0, 255)),
static_cast<unsigned char>(GetRandomValue(0, 255)),
255 // для альфа-канала явное преобразование не нужно, так как значение 255 вписывается в допустимый диапазон unsigned char
};
Добавление static_cast<unsigned char>() для каждого вызова GetRandomValue(0, 255) гарантирует, что каждое значение будет корректно преобразовано из int в unsigned char, предотвращая предупреждения компилятора.
Однако, если вы не видите заливку, проблема может быть не связана прямо с данным предупреждением. Убедитесь, что:
координаты точек корректны и они образуют заметную фигуру на экране;
значения, генерируемые GetRandomValue(0, 255), не делают цвет фона слишком близким к цвету фигуры, делая её незаметной;
проверьте масштаб и положение камеры в вашем приложении, возможно фигура рисуется за пределами видимой области.
Vector2 Vector2Lerp(Vector2 v1, Vector2 v2, float amount) {
Vector2 result;
amount = 0.5f; // Это переопределение ‘amount’, возможно его стоит убрать или устанавливать заранее
result.x = v1.x + amount * (v2.x - v1.x);
result.y = v1.y + amount * (v2.y - v1.y);
return result;
}
int main() {
const int screenWidth = 800;
const int screenHeight = 450;
SetConfigFlags(FLAG_WINDOW_RESIZABLE | FLAG_VSYNC_HINT);
InitWindow(screenWidth, screenHeight, "OpenAge map editor");
SetRandomSeed(time(NULL));
SetTargetFPS(60);
Camera2D camera = { 0 };
camera.offset = { screenWidth / 2.0f, screenHeight / 2.0f };
camera.target = { screenWidth / 2.0f, screenHeight / 2.0f };
camera.rotation = 0.0f;
float smoothTime = 30.0f;
float camSmoothTime = 30.0f; // The time it should take to reach the target
Texture2D background = LoadTexture("background.png");
// Теперь устанавливаем цель камеры в центр загруженного изображения
camera.offset = { screenWidth / 2.0f, screenHeight / 2.0f };
camera.target = { background.width / 2.0f, background.height / 2.0f };
camera.rotation = 0.0f;
camera.zoom = 1.0f; // Начальный масштаб камеры
Vector2 mousePosition = GetScreenToWorld2D(GetMousePosition(), camera);
Province province;
Color fillColor = (Color){
static_cast<unsigned char>(GetRandomValue(0, 255)),
static_cast<unsigned char>(GetRandomValue(0, 255)),
static_cast<unsigned char>(GetRandomValue(0, 255)),
255 // для альфа-канала явное преобразование не нужно, так как значение 255 вписывается в допустимый диапазон unsigned char
};
while (!WindowShouldClose()) {
mousePosition = GetScreenToWorld2D(GetMousePosition(), camera);
Vector2 mousePosition = GetMousePosition();
Vector2 worldMousePos = GetScreenToWorld2D(mousePosition, camera);
// Получаем изменение положения колесика мыши
float wheelMove = GetMouseWheelMove();
if (wheelMove != 0) {
float previousZoom = camera.zoom;
// Определение и обновление уровня зума камеры
camera.zoom += wheelMove * 0.05f; // Изменяем зум
camera.zoom = fmaxf(camera.zoom, 0.20f); // Ограничиваем минимальный зум
camera.zoom = fminf(camera.zoom, 40.0f); // Ограничиваем максимальный зум
// Рассчитываем изменение зума
float zoomDiff = camera.zoom / previousZoom;
// Получаем вектор смещения от текущего таргета к курсору и корректируем положение таргета камеры
// В зависимости от масштабирования
if (wheelMove > 0) { // Если приближаем
camera.target.x -= (worldMousePos.x - camera.target.x) * (1.0f - zoomDiff);
camera.target.y -= (worldMousePos.y - camera.target.y) * (1.0f - zoomDiff);
} else { // Если отдаляем
camera.target.x += (worldMousePos.x - camera.target.x) * (zoomDiff - 1.0f);
camera.target.y += (worldMousePos.y - camera.target.y) * (zoomDiff - 1.0f);
}
}
// Smooth camera movement
if (IsMouseButtonDown(MOUSE_BUTTON_RIGHT))
{
Vector2 delta = GetMouseDelta();
Vector2 target = (Vector2){ camera.target.x - delta.x / camera.zoom, camera.target.y - delta.y / camera.zoom };
// Interpolate the current target towards the new target
camera.target.x += (target.x - camera.target.x) * smoothTime * GetFrameTime();
camera.target.y += (target.y - camera.target.y) * smoothTime * GetFrameTime();
float minX = -camera.offset.x;
float minY = -camera.offset.y;
float maxX = background.width + camera.offset.x;
float maxY = background.height + camera.offset.y;
// Ensure the target position is within the allowed range
camera.target.x = (target.x < minX) ? minX : (target.x > maxX) ? maxX : target.x;
camera.target.y = (target.y < minY) ? minY : (target.y > maxY) ? maxY : target.y;
// Interpolate the current target towards the new target
camera.target.x += (camera.target.x - camera.target.x) * smoothTime * GetFrameTime();
camera.target.y += (camera.target.y - camera.target.y) * smoothTime * GetFrameTime();
}
BeginDrawing();
ClearBackground(RAYWHITE);
BeginMode2D(camera);
DrawTextureEx(background, {0, 0}, 0.0f, 1.0f, WHITE);
province.drawProvince(fillColor, true, BLACK, 0.25f);
if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT)) {
province.addPoint(worldMousePos.x, worldMousePos.y); // Добавляем точку к текущей провинции
}
if (IsKeyPressed(KEY_BACKSPACE)) {
province.deletePoints();
}
EndMode2D();
EndDrawing();
}
UnloadTexture(background);
CloseWindow();
return 0;
}
Так сейчас выглядит код main.cpp. Из за чего там может не рисоваться провинция на координатах пикселей загруженного изображения?
Из приведенного вами кода видно, что вы используете систему камеры Camera2D для отрисовки сцены. Однако, есть один важный момент, который может мешать корректному отображению провинций на фоне загруженного изображения, — это использование worldMousePos для добавления точек провинции.
Когда вы добавляете новую точку в провинцию с помощью province.addPoint(worldMousePos.x, worldMousePos.y);, вы используете координаты в "мире" (то есть, те, которые преобразованы с использованием камеры). В то время как для функции DrawPolyEx, которую вы, скорее всего, используете в методе drawProvince(), нужны координаты, адаптированные к камере для корректного отображения.
Камера может изменить позиционирование и масштаб объектов на сцене, не изменяя их реальные координаты. Таким образом, если вы добавляете точки, используя координаты в мировом пространстве worldMousePos, и при этом отрисовка ведется в экранных координатах, это может приводить к расхождению реального и ожидаемого положения отрисованных точек и провинций.
Как это исправить:
Используйте Экранные Координаты Для Добавления Точек: При использовании камеры для отрисовки может быть более правильным добавлять точки, используя их экранные координаты после преобразования. Однако, ваш текущий подход c worldMousePos кажется корректным если вы ожидаете работать с преобразованными координатами.
Убедитесь в Правильности Метода drawProvince(): Проверьте, что метод drawProvince() корректно обрабатывает координаты точек относительно камеры. Если в вашей программе используется преобразование через камеру, вам нужно убедиться, что перед рисованием провинции ваши точки тоже преобразуются с учетом позиции и масштаба камеры.
Проверьте Видимость Объектов на Сцене: Возможно, объект рисуется, но вне видимой области. Попробуйте добавить точки вблизи центра экрана и проверьте, не смещена ли камера таким образом, что добавленные объекты рисуются вне видимой области.
Проверьте значения fillColor и strokeColor: Убедитесь, что цвета выбраны так, чтобы объект был видим на фоне.
Debug вывод: Попробуйте добавить отладочный вывод (например, с помощью DrawText) для отображения координат точек непосредственно перед их добавлением и в функции рисования, чтобы убедиться, что они лежат в ожидаемом диапазоне и не выходят за пределы видимой области.
Если вы всё ещё сталкиваетесь с проблемами, рекомендую начать с упрощенного сценария, где вы только инициализируете камеру без каких-либо преобразований и пытаетесь нарисовать базовые фигуры в фиксированных местах экрана. Это поможет исключить проблемы, связанные с использованием камеры.
Перепиши код Main.cpp и код Province.cpp так, чтобы все фигуры и точки рисовались на мировых координатах, а не на экранных(точки могут появляться в левом верхнем углу мировых координат, в области равной по размеру размерам экрана) Вот код Province.cpp:
void DrawPolyEx(const std::vector& points, Color fillColor, Color strokeColor, bool drawStroke) {
if (points.size() < 3) return;
for (size_t i = 1; i < points.size() - 1; i++) {
DrawTriangle(points[0], points[i], points[i + 1], fillColor);
}
if (drawStroke) {
for (size_t i = 0; i < points.size() - 1; i++) {
DrawLineEx(points[i], points[i + 1], 2, strokeColor);
}
DrawLineEx(points.back(), points[0], 2, strokeColor);
}
}
Province::Province() {
std::vector points;
}
Province::~Province() {}
void Province::addPoint(int x, int y) {
points.push_back({x, y}); // Добавление точки к временному хранению точек
}
void Province::drawProvince(Color fillColor, bool drawStroke, Color strokeColor, float strokeThickness) {
for (const auto& province : provinces) {
std::vector raylibPoints; // Преобразование точек Province::Point в Vector2 для Raylib
for (const auto& point : province) {
raylibPoints.push_back({static_cast<float>(point.x), static_cast<float>(point.y)});
}
// Заполнение полигона
DrawPolyEx(raylibPoints, fillColor, strokeColor, drawStroke);
// Если требуется рисовать контур
if(drawStroke) {
for(size_t i = 0; i < raylibPoints.size(); i++) {
Vector2 start = raylibPoints[i];
Vector2 end = raylibPoints[(i + 1) % raylibPoints.size()]; // Замыкание контура
DrawLineEx(start, end, strokeThickness, strokeColor);
}
}
}
}
void Province::drawPoints() {
int x, y;
while (!IsKeyPressed(KEY_ENTER)) {
if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT)) {
Vector2 mousePos = GetMousePosition();
x = static_cast(mousePos.x);
y = static_cast(mousePos.y);
// Добавление точки к вектору points
Point newPoint = {x, y};
points.push_back(newPoint);
}
}
// Предполагается сохранение после завершения
provinces.push_back(points); // Добавить текущие нарисованные точки как новую провинцию
points.clear(); // Очистить текущие точки провинции для следующего рисования
}
void Province::deletePoints() {
if (!points.empty()) {
points.pop_back();
}
}
void Province::savePointsToFile(std::string filename) {
std::ofstream outFile(filename, std::ios::app); // Дозапись в файл
if (outFile.is_open()) {
for (const auto& province : provinces) {
for (const auto& point : province) {
outFile << point.x << ";" << point.y << '\n';
}
outFile << '\n'; // Дополнительная пустая строка между провинциями
}
}
outFile.close();
}
bool Province::deleteProvince(Vector2 mousePoint) {
// Реализация удаления провинции, если точка mousePoint находится внутри неё (опущено для упрощения)
return false;
}
while (getline(ssX, itemX, ';') && getline(ssY, itemY, ';')) {
if (!itemX.empty() && !itemY.empty()) {
Point newPoint {std::stoi(itemX), std::stoi(itemY)};
newProvince.push_back(newPoint);
}
}
provinces.push_back(newProvince);
}
Чтобы гарантировать, что все фигуры и точки рисуются на мировых координатах, а не на экранных, и точки могут появляться в левом верхнем углу мировых координат, важно правильно установить камеру и координаты, используемые для рисования.
В коде Province.cpp вам нужно будет обновить метод addPoint так, чтобы он добавлял точки, используя мировые координаты напрямую, без преобразования из экранных координат. Однако, кажется, ваш код уже использует мировые координаты напрямую через mousePos, полученный с помощью вызова GetScreenToWorld2D(GetMousePosition(), camera). Это правильный подход.
Ваш код Province.cpp выглядит согласованным с отрисовкой на мировых координатах, учитывая описанный процесс. Убедимся, что в main.cpp у вас есть соответствующая настройка:
#include "raylib.h"
#include "Province.hpp"
#include <vector>
#include <cstdlib>
#include <ctime>
int main() {
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "OpenAge map editor");
SetTargetFPS(60);
Camera2D camera = {0};
camera.target = (Vector2){0, 0}; // Центр в мировых координатах
camera.offset = (Vector2){screenWidth / 2.0f, screenHeight / 2.0f}; // Центрирование камеры на экране
camera.rotation = 0.0f;
camera.zoom = 1.0f;
SetRandomSeed(time(NULL));
Province province;
while (!WindowShouldClose()) {
// Преобразование координат мыши из экранных в мировые
Vector2 mousePosition = GetScreenToWorld2D(GetMousePosition(), camera);
if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT)) {
province.addPoint(mousePosition.x, mousePosition.y);
}
if (IsKeyPressed(KEY_BACKSPACE)) {
province.deletePoints();
}
BeginDrawing();
ClearBackground(RAYWHITE);
BeginMode2D(camera);
// Отрисовка фона и провинций
EndMode2D();
EndDrawing();
}
CloseWindow();
return 0;
}
Обратите внимание:
Мы исправили инициализацию камеры, чтобы убедиться, что она правильно установлена для взаимодействия с мировыми координатами.
Координаты мыши теперь преобразуются из экранных в мировые при помощи GetScreenToWorld2D перед добавлением точек в province.
Удалена неиспользуемая инициализация Province::Province() { std::vector<Vector2> points; }, так как переменная points уже является членом класса Province.
Если вы заметили, что точки не отрисовываются, убедитесь в том, что:
Вы осуществляете отрисовку внутри BeginMode2D и EndMode2D.
Проверьте логику и правильность координат при вызове метода drawProvince() в классе Province, чтобы убедиться, что координаты точек находятся в пределах видимости камеры.
main.cpp
BeginDrawing();
ClearBackground(RAYWHITE); // Очистить фон перед началом отрисовки
BeginMode2D(camera);
DrawTextureEx(background, {0, 0}, 0.0f, 1.0f, WHITE); // Отрисовать фон
// Проверка на нажатие кнопки мыши внутри Mode2D не является лучшей практикой,
// так как Mode2D не влияет на обработку ввода. Но это не проблема для отображения:
if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT)) {
province.addPoint(mousePosition.x, mousePosition.y);
}
province.drawProvince(fillColor, true, BLACK, 0.25f); // Отрисовать провинцию
EndMode2D();
// Проверка нажатия клавиши лучше разместить вне блока Mode2D для ясности кода
if (IsKeyPressed(KEY_BACKSPACE)) {
province.deletePoints();
}
EndDrawing();
Также важно отметить, что обновление и/или отрисовка фигур должна происходить в каждом кадре цикла рендеринга из-за особенностей работы в реальном времени. Здесь не нужно "обновлять видимость полигонов после клика", потому что в каждом кадре происходит полная переотрисовка всей сцены, и если вы правильно создаете и храните данные о провинциях, то любое изменение (например, добавление новой точки) автоматически будет отображено в следующем кадре.
Убедитесь, что методы addPoint и drawProvince реализованы корректно для работы с вашей логикой отрисовки и хранения данных о провинциях в классе Province.