1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
| #include <iostream>
#include <fstream>
#include <vector>
#include <algorithm> // sort, max_element, random_shuffle, remove_if, lower_bound
#include <functional> // greater, bind2nd
#include <iomanip>
#include <stdio.h>
#include <math.h>
#include <cmath>
using namespace std;
/////////////////////////////Тут функции для расчета принадлежности точки многоугольнику///////////////////////////////////////
////////////////////////////Выдрана из америкосовского забугорья///////////////////////////////////////////////////////////////
//////////////////////////////ЭТУ ЧАСТЬ КОДА МОЖНО ПРОПУСТИТЬ ЕСЛИ ВАМ ЛЕНЬ РАЗБИРАТЬСЯ////////////////////////////////////////
// A C++ program to check if a given podouble lies inside a given polygon
// Refer [url]http://www.geeksforgeeks.org/check-if-two-given-line-segments-doubleersect/[/url]
// for explanation of functions onSegment(), orientation() and dodoubleersect()
// Define Infinite (Using double_MAX caused overflow problems)
#define INF 10000
struct Podouble
{
double x;
double y;
};
// Given three colinear podoubles p, q, r, the function checks if
// podouble q lies on line segment 'pr'
bool onSegment(Podouble p, Podouble q, Podouble r)
{
if (q.x <= max(p.x, r.x) && q.x >= min(p.x, r.x) &&
q.y <= max(p.y, r.y) && q.y >= min(p.y, r.y))
return true;
return false;
}
// To find orientation of ordered triplet (p, q, r).
// The function returns following values
// 0 --> p, q and r are colinear
// 1 --> Clockwise
// 2 --> Counterclockwise
double orientation(Podouble p, Podouble q, Podouble r)
{
double val = (q.y - p.y) * (r.x - q.x) -
(q.x - p.x) * (r.y - q.y);
if (val == 0) return 0; // colinear
return (val > 0)? 1: 2; // clock or counterclock wise
}
// The function that returns true if line segment 'p1q1'
// and 'p2q2' doubleersect.
bool dodoubleersect(Podouble p1, Podouble q1, Podouble p2, Podouble q2)
{
// Find the four orientations needed for general and
// special cases
double o1 = orientation(p1, q1, p2);
double o2 = orientation(p1, q1, q2);
double o3 = orientation(p2, q2, p1);
double o4 = orientation(p2, q2, q1);
// General case
if (o1 != o2 && o3 != o4)
return true;
// Special Cases
// p1, q1 and p2 are colinear and p2 lies on segment p1q1
if (o1 == 0 && onSegment(p1, p2, q1)) return true;
// p1, q1 and p2 are colinear and q2 lies on segment p1q1
if (o2 == 0 && onSegment(p1, q2, q1)) return true;
// p2, q2 and p1 are colinear and p1 lies on segment p2q2
if (o3 == 0 && onSegment(p2, p1, q2)) return true;
// p2, q2 and q1 are colinear and q1 lies on segment p2q2
if (o4 == 0 && onSegment(p2, q1, q2)) return true;
return false; // Doesn't fall in any of the above cases
}
// Returns true if the podouble p lies inside the polygon[] with n vertices
bool isInside(Podouble polygon[], int n, Podouble p)
{
// There must be at least 3 vertices in polygon[]
if (n < 3) return false;
// Create a podouble for line segment from p to infinite
Podouble extreme = {INF, p.y};
// Count doubleersections of the above line with sides of polygon
int count = 0, i = 0;
do
{
int next = (i+1)%n;
// Check if the line segment from 'p' to 'extreme' doubleersects
// with the line segment from 'polygon[i]' to 'polygon[next]'
if (dodoubleersect(polygon[i], polygon[next], p, extreme))
{
// If the podouble 'p' is colinear with line segment 'i-next',
// then check if it lies on segment. If it lies, return true,
// otherwise false
if (orientation(polygon[i], p, polygon[next]) == 0)
return onSegment(polygon[i], p, polygon[next]);
count++;
}
i = next;
} while (i != 0);
// Return true if count is odd, false otherwise
return count&1; // Same as (count%2 == 1)
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////Тут функции для расчета принадлежности точки многоугольнику заканчиваются/////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////Тут мое код пожалуйста посмотрите////////////////////////////////////////////////////
/*
Задача определить все точки с координатами X,Y входящие в полигон.
Полигон в данном случае - географические координаты. Область образуется несколькими точками,
в данном примере 4мя, но возможны и другие варианты в будущем.
В коде присутсвует 2 чек проверки, проверка 1 загоняет координаты еще до обьявления циклов, загоняет координаты
вручную, дублируя обозначенные выше, еще до того, как начинаются манимуляции с массивами
2 чек проверка, берет данные из обьявленных переменных.
3 проверка уже проходит в цикле, с переборами значений, тут кроется ошибка которую я не понимаю, посмотрите
пожалуйста мои комментарии в фаиле ниже.
*/
int main()
{
setlocale (LC_ALL, "Russian");
//Задаем координаты квадрата
double po1_x=49.789551;
double po1_y=73.111949;
double po2_x=49.789641;
double po2_y=73.111941;
double po3_x=49.789658;
double po3_y=73.112365;
double po4_x=49.789568;
double po4_y=73.112373;
//Шаг рассчета координат в области
double step= 0.000001;;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Контрольная проверка 1 принадлежности контрольной точки {49.789551, 73.111949} полигону//////////////////////////
Podouble polygon2[] = { {49.789551,73.111949}, {49.789641,73.111941}, {49.789658,73.112365}, {49.789568,73.112373}};
int n = sizeof(polygon2)/sizeof(polygon2[0]);
Podouble p = {49.789551, 73.111949};
//isInside(polygon2, n, p)? cout << "Yes \n": cout << "No \n";
if (isInside(polygon2,n,p) == true)
{cout <<setprecision(10) << "\n Control--YaYaYa--"<<49.789551<<"--"<<73.111949;}
else {cout <<setprecision(10)<< "\n Control--NoNoNo--"<<49.789551<<"--"<<73.111949;}
//Контрольная проверка 1 принадлежности контрольной точки {49.789551, 73.111949} полигону/////////////////////////
///////////ПРОВЕРКА ПРОХОДИТ НОРМАЛЬНО ПОКАЗЫВАЕТСЯ ЧТО ТОЧКА ВНУТРИ ПОЛИГОНА/////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Формируем массив точек Х
std::vector<double> myXpoints;
myXpoints.push_back(po1_x);
myXpoints.push_back(po2_x);
myXpoints.push_back(po3_x);
myXpoints.push_back(po4_x);
//Сохраняем количество элементов вектора
//int myXpoints_size = myXpoints.size();
//Массив точек У
std::vector<double> myYpoints;
myYpoints.push_back(po1_y);
myYpoints.push_back(po2_y);
myYpoints.push_back(po3_y);
myYpoints.push_back(po4_y);
//Сохраняем количество элементов вектора
//int myYpoints_size = myYpoints.size();
//Определяем максимальное и минимальное значение X
vector<double>::const_iterator largestX = max_element( myXpoints.begin(), myXpoints.end() );
cout<< setprecision(10) << "\nНаибольший элемент X" << *largestX << endl;
double max_x = *largestX;
vector<double>::const_iterator smalestX = min_element( myXpoints.begin(), myXpoints.end() );
cout<< setprecision(10) << "Наименьший элемент X" << *smalestX << endl;
double min_x = *smalestX;
//Максимальный и минимальное значение У
vector<double>::const_iterator largestY = max_element( myYpoints.begin(), myYpoints.end() );
cout<< setprecision(10) << "Наибольший элемент Y" << *largestY << endl;
double max_y = *largestY;
vector<double>::const_iterator smalestY = min_element( myYpoints.begin(), myYpoints.end() );
cout<< setprecision(10) << "Наименьший элемент Y" << *smalestY << endl;
double min_y = *smalestY;
//Формируем массивы, которые будут заполняться расчитанными значениями
vector<double> myvector_x;
vector<double> myvector_y;
//Заполняем массив всех возможных значений Х
myvector_x.push_back(min_x);
do {
min_x+=step;
myvector_x.push_back(min_x);
}
while ( (min_x+step) <= max_x);
// Сохраняем количество элементов вектора
int vector_size_x = myvector_x.size();
//Заполняем массив всех возможных значений У
myvector_y.push_back(min_y);
do {
min_y+=step;
myvector_y.push_back(min_y);
}
while ((min_y+step) <= max_y);
// Сохраняем количество элементов вектора
int vector_size_y = myvector_y.size();
//Создаем фаил для записи готовых значений
ofstream myfile;
myfile.open ("h:\\example.txt");
//////////////////////////////////////////////////////////////////////////////////////////
//Контрольная проверка №2 принадлежности контрольной точки {49.789551, 73.111949} полигону
double X_1 = 49.789551;
double Y_1 = 73.111949;
Podouble polygon1[] = {{po1_x,po1_y}, {po2_x,po2_y}, {po3_x,po3_y}, {po4_x,po4_y}};
n = sizeof(polygon1)/sizeof(polygon1[0]);
p = {X_1, Y_1};
if (isInside(polygon1,n,p) == true)
{cout << "\n Control-2--YaYaYa--"<<X_1<<"--"<<Y_1;}
else {cout << "\n Control-2--NoNoNo--"<<X_1<<"--"<<Y_1;}
//Контрольная проверка №2 принадлежности контрольной точки {49.789551, 73.111949} полигону
///////////ПРОВЕРКА ПРОХОДИТ НОРМАЛЬНО ПОКАЗЫВАЕТСЯ ЧТО ТОЧКА ВНУТРИ ПОЛИГОНА/////////////
//////////////////////////////////////////////////////////////////////////////////////////
//Уходим в цикл, и в дальнейшем
//для каждого значения из массива данных Х выполняется подбор всех возможных значений из массива Y
//далее выполняется проверка принадлежности найденной точки полигону
for (int i = 0; i < vector_size_x; i++)
{
double Lat1Dgr= myvector_x[i];
for (int i = 0; i < vector_size_y; i++)
{
//Тут определяем каждую точку Y для обозначенного выше X
double Long1Dgr = myvector_y[i];
/////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////ТУТ НАЧИНАЕТСЯ БРЕД//////////////////////////////////////////////////////////
////////1 - НЕ ПОНИМАЮ ПОЧЕМУ ПРОВЕРКА СООТВЕТСВИЯ ДЕЛАЕТСЯ НЕ ПРАВИЛЬНО ///////////////
////////ПОКАЗЫВАЕТСЯ ЧТО ТОЧКА НЕ ПРИНАДЛЕЖИТ///////////////////////////////////////////////////
////////2 - НЕ ПОНИМАЮ ПРАВИЛА ВЫПОЛНЕНИЯ if ВНУТРИ ЦИКЛА - ОБ ЭТОМ ПОДРОБНЕЕ НИЖЕ///////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//Запускаем проверку точки
Podouble polygon1[] = {{po1_x,po1_y}, {po2_x,po2_y}, {po3_x,po3_y}, {po4_x,po4_y}};
int n = sizeof(polygon1)/sizeof(polygon1[0]);
Podouble p = {Lat1Dgr, Long1Dgr};
//внутри этого if должна проводиться проверка на соответсвие
//логига у меня такая:
//Если значение Lat1Dgr строго равно 49.789551, тогда если Long1Dgr строго равно 73.111949
//то, только в этом случае выполняем вывод {Lat1Dgr, Long1Dgr} на экран, и делаем запись в фаил
//в противном случае, не делаем ничего, не выводим на экран и не записываем в фаил
//но почему-то, цикл работает не так как мне нужно
if (Lat1Dgr = 49.789551)
{
if (Long1Dgr = 73.111949)
{
if (isInside(polygon1,n,p) == true)
{cout << "\n YaYaYa--"<<Lat1Dgr<<"--"<<Long1Dgr;
myfile << setprecision(10) <<"/ X-Lat1Dgr/"<< Lat1Dgr << "/ Y-Long1Dgr/"<<Long1Dgr <<"/n -YaYaYa /n";
}
else
{cout << "\n NoNoNo--"<<Lat1Dgr<<"--"<<Long1Dgr;
myfile << setprecision(10) <<"/ X-Lat1Dgr/"<< Lat1Dgr << "/ Y-Long1Dgr/"<<Long1Dgr <<"/n -NoNoNo /n";
}
}
} //delete [] polygon1;//не могу удалить массив, программа зависает, компилятоh при этом не ругается
}
}
myfile.close();
} |