-
Notifications
You must be signed in to change notification settings - Fork 0
/
geocrop.cpp
1065 lines (891 loc) · 34.4 KB
/
geocrop.cpp
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include <memory>
#include <cassert>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <gdal_priv.h>
#include <ogr_spatialref.h>
#include <proj.h>
#include "version.h"
using namespace std;
static const char * const s_options = "f:s:Sw:ngp:Vh";
struct GeoTransformMatrix
{
std::array<double, 6> matrix;
double* get()
{
return matrix.data();
}
double pixelWidth() const
{
return matrix[1];
}
double pixelHeight() const
{
return matrix[5];
}
double left() const
{
return matrix[0];
}
double top() const
{
return matrix[3];
}
// TODO
double rtnX() const
{
return matrix[2];
}
// TODO
double rtnY() const
{
return matrix[4];
}
void pixelToCoordinate(int rasterX, int rasterY,
double &geoX, double &geoY)
{
geoX = left() + rasterX * pixelWidth() + rasterY * rtnY();
geoY = top() + rasterY * pixelHeight() + rasterX * rtnX();
}
void coordinateToPixel(double geoX, double geoY,
int &rasterX, int &rasterY)
{
// TODO: optimize
rasterX = (geoX - left() - rtnY()/pixelHeight()*geoY + top()*rtnY()/pixelHeight()) / (pixelWidth() - rtnX()*rtnY()/pixelHeight());
rasterY = (geoY - top() - rasterX * rtnX()) / pixelHeight();
}
};
void version()
{
cout << "version: " << GEOCROP_VERSION << '\n';
}
void usage(char *name)
{
cout << "Tool for automatic crop raster maps\n";
cout << "(C) Alexander 'hatred' Drozdov, 2012-2017. Distributed under GPLv2 terms\n";
version();
cout << "\nUse: " << name << " [args] <in geodata> [<croped geodata>] [-- [optional gdalwarp arguments]]\n"
<< " Input geotiff MUST be in RGB pallete, so, use pct2rgb.py to convert from indexed\n"
" Output geotiff croped and nodata areas is transparency\n"
"\n"
" Args:\n"
" -s SCALE\n"
" Scale must be:\n"
" 500k for 1:500 000 plates\n"
" 200k for 1:200 000 plates\n"
" 100k(*) for 1:100 000 plates, used by default\n"
" 50k for 1:50 000 plates\n"
" 25k for 1:25 000 plates\n"
" 1M (1:1 000 000) used by default\n"
" Any other scales currently not support\n"
" -S turn off auto-detection for doubled plates (60-76 degrees) and quadruple\n"
" plates (over 76 degree)\n"
" -f OUTPUT_FORMAT\n"
" Any format supported by GDAL. GTiff is default one\n"
" -n\n"
" Disable '-crop_to_cutline' option. Border will be only filled with transparent color\n"
" -w GDALWARP\n"
" Allow to override `gdalwarp` name and path, by default simple `gdalwarp` and search under PATH\n"
" -g\n"
" Only generate CVS description for the `cutline` on `stdout` without `gdalwarp` execution.\n"
" Output files with this option will be ignored and can be omited as arguments.\n"
" -p srs_def\n"
" Override projection for dataset\n"
" -V\n"
" Output version and exit.\n"
" -h\n"
" This screen.\n"
;
}
string generate_temp_file_name()
{
char name[] = "/tmp/geocrop.XXXXXX";
close(mkstemp(name));
string result(name);
return result;
}
//
// [RU]
// Определяем подлист листа с указанным обрамлением. Для листов делящихся последовательно на 4
// Наприме, лист километровки делится на 4 листа полукилометровок, если нам нужно получить
// обрамление листа полукилометровки, расчитываем оное для километровки, передаём в качестве входных
// параметров сюда а так же пробную точку, по которой определяем подлист.
//
// Далее, так же последовательно можно сделать расчёт для двухсотпятидесятиметровки
//
char get_subplate(double lon,
double lat,
double &subPlateTop,
double &subPlateLeft,
double &subPlateBottom,
double &subPlateRight)
{
double centerLon = subPlateLeft + (subPlateRight - subPlateLeft) / 2;
double centerLat = subPlateBottom + (subPlateTop - subPlateBottom) / 2;
char subPlateCh = 0;
if (lon >= subPlateLeft && lon < centerLon)
{
// 1-3 четверти
subPlateRight = centerLon;
if (lat >= subPlateBottom && lat < centerLat)
{
subPlateCh = 'C'; // 3 четверть
subPlateTop = centerLat;
}
else if (lat >= centerLat && lat <= subPlateTop)
{
subPlateCh = 'A'; // 1 четверть
subPlateBottom = centerLat;
}
}
else if (lon >= centerLon && lon <= subPlateRight)
{
// 2-4 четверти
subPlateLeft = centerLon;
if (lat >= subPlateBottom && lat < centerLat)
{
subPlateCh = 'D'; // 3 четверть
subPlateTop = centerLat;
}
else if (lat >= centerLat && lat <= subPlateTop)
{
subPlateCh = 'B'; // 1 четверть
subPlateBottom = centerLat;
}
}
return subPlateCh;
}
bool load_projection(const char* projfilename, GDALDataset *dataset)
{
ifstream ifs(projfilename);
if (ifs)
{
string wktprojection;
string line;
while (getline(ifs, line))
{
wktprojection += line;
}
return dataset->SetProjection(wktprojection.c_str()) == CE_None;
}
return false;
}
template<typename T>
struct Point
{
Point() : x(0.0), y(0.0) {}
Point(T x, T y) : x(x), y(y) {}
T x;
T y;
};
typedef Point<double> PointReal;
typedef Point<int> PointInt;
/** Adds a " +type=crs" suffix to a PROJ string (if it is a PROJ string) */
static std::string pj_add_type_crs_if_needed(std::string_view str)
{
std::string ret(str);
if( (str.starts_with("proj=") ||
str.starts_with("+proj=") ||
str.starts_with("+init=") ||
str.starts_with("+title=")) &&
str.find("type=crs") == std::string::npos )
{
ret += " +type=crs";
}
return ret;
}
class CrsInstance
{
public:
CrsInstance();
explicit CrsInstance(std::string_view definition);
bool isLatLong() const;
bool isLatFirst() const;
double toRadians() const;
std::string_view definition() const;
operator bool() const;
PJ* get() const;
void reset();
PJ* release();
CrsInstance getGeographicCrs() const;
private:
static void deleter(PJ *ptr)
{
if (ptr)
proj_destroy(ptr);
}
using pj_ptr_t = std::unique_ptr<PJ, decltype(&deleter)>;
static pj_ptr_t wrap(PJ *pj);
pj_ptr_t m_crs;
std::string m_definition;
bool m_isLongLat = false;
bool m_isLatFirst = false;
double m_toRadians = 0.0;
};
//
// http://www.gdal.org/gdal_tutorial_ru.html
//
int main(int argc, char **argv)
{
GDALDataset *dataset = nullptr;
bool autodetectDoubles = true;
int mapsCountMult = 1;
string scale = "100k";
string inFileName;
string ouFileName;
string prjFileName;
string ouDriver = "GTiff";
GeoTransformMatrix geoTransform;
int rasterXSize = 0;
int rasterYSize = 0;
int rasterXCenter = 0;
int rasterYCenter = 0;
string gdalwarpPath = "gdalwarp";
vector<char*> gdalwarpOpts; // Additional options for gdalwarp
bool cropToCutline = true;
bool generateOnly = false;
while (true)
{
int opt = getopt(argc, argv, s_options);
if (opt == -1)
break;
switch (opt)
{
case 'f':
ouDriver = optarg;
break;
case 's':
scale = optarg;
break;
case 'S':
autodetectDoubles = false;
break;
case 'w':
gdalwarpPath = optarg;
break;
case 'n':
cropToCutline = false;
break;
case 'g':
generateOnly = true;
break;
case 'p':
prjFileName = optarg;
break;
case 'V':
version();
return 0;
default:
usage(argv[0]);
return opt == 'h' ? 0 : 1;
}
}
if (optind > argc - (generateOnly ? 1 : 2))
{
usage(argv[0]);
return 1;
}
inFileName = argv[optind++];
if (!generateOnly)
ouFileName = argv[optind++];
if (optind < argc)
{
gdalwarpOpts.reserve(argc - optind);
while (optind++ < argc)
{
gdalwarpOpts.push_back(argv[optind - 1]);
}
}
GDALAllRegister();
dataset = (GDALDataset*)GDALOpen(inFileName.c_str(), GA_ReadOnly);
if (dataset == 0)
{
cerr << "Can't open file: " << inFileName << endl;
return 1;
}
clog << "InDriver: " << dataset->GetDriver()->GetDescription() << "/"
<< dataset->GetDriver()->GetMetadata(GDAL_DMD_LONGNAME) << endl;
clog << "InSize: " << dataset->GetRasterXSize() << "x" << dataset->GetRasterYSize() << "x"
<< dataset->GetRasterCount() << endl;
// Override or detect projection
if (!prjFileName.empty())
{
clog << "Override projection with: '" << prjFileName << "'\n";
if (!load_projection(prjFileName.c_str(), dataset))
{
cerr << "Can't load projection\n";
return 1;
}
gdalwarpOpts.push_back(::strdup("-s_srs"));
gdalwarpOpts.push_back(::strdup(prjFileName.c_str()));
}
else if (dataset->GetProjectionRef() == nullptr || *dataset->GetProjectionRef() == '\0')
{
clog << "Empty projection...\n";
for (auto ext : {"prj", "prf"})
{
auto projfilename = CPLResetExtension(inFileName.c_str(), ext);
clog << " Try load from the '" << projfilename << "'\n";
if (load_projection(projfilename, dataset))
{
gdalwarpOpts.push_back(::strdup("-s_srs"));
gdalwarpOpts.push_back(::strdup(projfilename));
break;
}
}
}
if (dataset->GetProjectionRef() != nullptr)
{
clog << "Projection: " << dataset->GetProjectionRef() << endl;
}
if (dataset->GetGeoTransform(geoTransform.get()) == CE_None)
{
fprintf(stderr,
"Coordinate zero (%.6f,%.6f)\n",
geoTransform.left(), geoTransform.top() );
fprintf(stderr,
"Pixel size (%.6f,%.6f)\n",
geoTransform.pixelWidth(), geoTransform.pixelHeight() );
rasterXSize = dataset->GetRasterXSize();
rasterYSize = dataset->GetRasterYSize();
rasterXCenter = rasterXSize / 2;
rasterYCenter = rasterYSize / 2;
vector<PointReal> shapeBorderCoordinates(4);
vector<PointInt> shapeBorderPixels(4);
double geoXCenter;
double geoYCenter;
geoTransform.pixelToCoordinate(rasterXCenter, rasterYCenter, geoXCenter, geoYCenter);
fprintf(stderr, "Shape center: (%5d, %5d)\n", rasterXCenter, rasterYCenter);
fprintf(stderr, "Shape center coordinates: (%.6f, %.6f)\n", geoXCenter, geoYCenter);
// Back conversion check
//geoToPixelCoordinate(geoTransform, geoXCenter, geoYCenter, rasterXCenter, rasterYCenter);
//printf("Центр листа: (%5d, %5d)\n", rasterXCenter, rasterYCenter);
// Convert WKT projection representation to the PRIJ4 form
OGRSpatialReference inSrs;
inSrs.importFromWkt(dataset->GetProjectionRef());
char *proj4Ref;
inSrs.exportToProj4(&proj4Ref);
string inProj = proj4Ref;
clog << "PROJ4: " << inProj << endl;
// Recalc metric coordinates to the LonLat for shape detection
CrsInstance pjSrc{inProj};
PJ *transform = nullptr;
double geoLonCenter = geoXCenter;
double geoLatCenter = geoYCenter;
if (!pjSrc.isLatLong())
{
auto pjTar = pjSrc.getGeographicCrs();
clog << "PROJ: " << pjTar.definition() << endl;
if (!pjSrc|| !pjTar)
{
cerr << "Can't setup projection'\n";
return 1;
}
transform = proj_create_crs_to_crs_from_pj(PJ_DEFAULT_CTX,
pjSrc.get(), pjTar.get(),
nullptr, nullptr);
if (!transform) {
clog << "Can't create PROJ transformation\n";
return 1;
}
PJ_COORD coord{};
coord.xy.x = geoXCenter;
coord.xy.y = geoYCenter;
coord = proj_trans(transform, PJ_FWD, coord);
geoLonCenter = coord.uv.u;
geoLatCenter = coord.uv.v;
fprintf(stderr, "Shape center coordinates (lat/lon): (%.6f, %.6f)\n",
geoLatCenter, geoLonCenter);
}
//
// Detect 1M shape
//
// Detect shape letter (in other word: shape latitude)
int letterNumber = (int)ceil(geoLatCenter / 4);
// Degree border of the corresponding 1M map
double top1m = letterNumber * 4;
double bottom1m = top1m - 4;
// Detect double/quad maps
if (autodetectDoubles) {
// geoLatCenter, geoLonCenter
// To detect doublding/quad maps we should use only geoLatCenter
// it allows us correctly detect shape
// TODO: add support for sourth
if (bottom1m >= 60.0) {
mapsCountMult = 2; // doubled maps
}
if (bottom1m >= 76.0) {
mapsCountMult = 4; // quad maps
}
}
fprintf(stderr, "Shape bottom: %f, assume %d maps in Lon direction\n", bottom1m, mapsCountMult);
// Zone depends on shapes count
int Nz = (int)ceil(geoLonCenter / (6 * mapsCountMult));
double right1m = Nz * (6 * mapsCountMult);
double left1m = right1m - (6 * mapsCountMult);
shapeBorderCoordinates[0] = PointReal(top1m, left1m);
shapeBorderCoordinates[1] = PointReal(top1m, right1m);
shapeBorderCoordinates[2] = PointReal(bottom1m, left1m);
shapeBorderCoordinates[3] = PointReal(bottom1m, right1m);
for (int i = 0; i < 4; ++i)
{
if (transform)
{
// At the LatLon representation, first is a latitude that is a Y. Second -
// longitude that is X. Before pass it to the pj_transform() we must put to
// correct places:
// first - X (lon), second - Y (lat)
PJ_COORD coord{};
coord.uv.u = shapeBorderCoordinates[i].y;
coord.uv.v = shapeBorderCoordinates[i].x;
coord = proj_trans(transform, PJ_INV, coord);
shapeBorderCoordinates[i].x = coord.xy.x;
shapeBorderCoordinates[i].y = coord.xy.y;
}
// Recalc coordinates to the pixels
geoTransform.coordinateToPixel(shapeBorderCoordinates[i].x, shapeBorderCoordinates[i].y, shapeBorderPixels[i].x, shapeBorderPixels[i].y);
}
char plateCh = 'A' + letterNumber - 1; // Shape letter
int plateNum = Nz*mapsCountMult + 30; // Shape number
stringstream plateNameStream;
plateNameStream << plateCh << "-" << plateNum;
string plateName = plateNameStream.str();
#if 0
plateName.push_back(plateCh);
switch (mapsCountMult) {
case 1:
plateName = plateNameStream.str();
break;
case 2:
case 4:
{
int first = plateNum > 1 ? plateNum / mapsCountMult * mapsCountMult - 1 : 1;
plateName.append("-");
for (int i = 0; i < mapsCountMult; ++i) {
plateName.append(to_string(first + i));
if (i != mapsCountMult - 1)
plateName.append(",");
}
break;
}
}
#endif
clog << "Shape of the 1M map: " << plateName << endl;
fprintf(stderr,
"Shape border coordinates (lat/lon) %s:\n"
" (%.6f, %.6f) (%.6f, %.6f)\n"
" (%.6f, %.6f) (%.6f, %.6f)\n",
plateName.c_str(),
top1m, left1m, top1m, right1m,
bottom1m, left1m, bottom1m, right1m);
int tmpx = 1; // shape row number at the 1M base map, from 0 left-to-right
int tmpy = 1; // shape column number at the 1M base map, from 0 top-to-bottm
int plateSubNum = 1; // linear shape number at the 1M base map, valid for 500k, 200k and 100k subsets
// more huge scales bases on 100k settings
// for 500k subbser, linear number is a letter 'А'-'Г' on Russian or
// 'A'-'D', like O-50-A
double plateWidthMin = 360 * mapsCountMult; // Shape width in minutes, 360 - for 1M map
double plateHeightMin = 240; // Shape height in minutes, 240 - for 1M map
int plateWidthInSubplates = 1; // 1M shape width in subset scales,
// for example, 1M map width of 500k maps is a 2
double subPlateTop = top1m; // Shape top in LonLat coordinates
double subPlateBottom = bottom1m; // Shape bottom in LonLat coordinates
double subPlateLeft = left1m; // Shape left in LonLat coordinates
double subPlateRight = right1m; // Shape right in LonLat coordinates
bool knownScale = false; // true if we known specified scale. Otherwise assume that
// we deals with 1M map
if (scale == "100k" || scale == "50k" || scale == "25k")
{
// 100k subsets (50k, 25k) calculates based on superset (100k) settings
plateWidthInSubplates = 12;
plateWidthMin = 30 * mapsCountMult;
plateHeightMin = 20;
knownScale = true;
}
else if (scale == "200k")
{
plateWidthInSubplates = 6;
plateWidthMin = 60 * mapsCountMult;
plateHeightMin = 40;
knownScale = true;
}
else if (scale == "500k")
{
plateWidthInSubplates = 2;
plateWidthMin = 180 * mapsCountMult;
plateHeightMin = 120;
knownScale = true;
}
if (knownScale)
{
// Detect shape number
tmpx = (int)((geoLonCenter - left1m) * 60) / plateWidthMin;
tmpy = (int)((geoLatCenter - bottom1m) * 60) / plateHeightMin;
tmpy = plateWidthInSubplates - 1 - tmpy; // инвертируем, т.к. растем сверху вниз
clog << "tmpx = " << tmpx << ", tmpy = " << tmpy << endl;
// Shape number
plateSubNum = tmpy * plateWidthInSubplates + tmpx + 1;
plateNameStream << "-";
// Forming shape name
if (scale == "100k" || scale == "50k" || scale == "25k")
{
if (plateSubNum < 10)
{
plateNameStream << "00";
}
else if (plateSubNum > 9 && plateSubNum < 100)
{
plateNameStream << "0";
}
}
else if (scale == "200k")
{
if (plateSubNum < 10)
{
plateNameStream << "0";
}
}
if (scale == "500k")
{
// 500k maps marks with A-D letters
char plate500kCh = 'A' + plateSubNum - 1;
plateNameStream << plate500kCh;
}
else
plateNameStream << plateSubNum;
// Shape borders in LonLat coordinates
subPlateTop = top1m - tmpy * plateHeightMin/60.0;
subPlateBottom = subPlateTop - plateHeightMin/60.0;
subPlateLeft = left1m + tmpx * plateWidthMin/60.0;
subPlateRight = subPlateLeft + plateWidthMin/60.0;
// Be more patient for the huge scales
if (scale == "50k" || scale == "25k")
{
char plate50kCh = get_subplate(geoLonCenter,
geoLatCenter,
subPlateTop,
subPlateLeft,
subPlateBottom,
subPlateRight);
if (!plate50kCh)
{
cerr << "Incorrect page of 1:50000\n";
return 1;
}
plateNameStream << '-' << plate50kCh;
if (scale == "25k")
{
char plate25kCh = get_subplate(geoLonCenter,
geoLatCenter,
subPlateTop,
subPlateLeft,
subPlateBottom,
subPlateRight);
if (!plate25kCh)
{
cerr << "Incorrect page of 1:25000\n";
return 1;
}
plate25kCh -= ('A' - 'a'); // change register :-)
plateNameStream << '-' << plate25kCh;
}
}
clog << "Shape number: " << plateNameStream.str() << endl;
fprintf(stderr,
"Shape border coordinates (lat/lon) %s:\n"
" (%.6f, %.6f) (%.6f, %.6f)\n"
" (%.6f, %.6f) (%.6f, %.6f)\n",
plateNameStream.str().c_str(),
subPlateTop, subPlateLeft, subPlateTop, subPlateRight,
subPlateBottom, subPlateLeft, subPlateBottom, subPlateRight);
// Recalc coordinates to the source SRS
shapeBorderCoordinates[0] = PointReal(subPlateTop, subPlateLeft);
shapeBorderCoordinates[1] = PointReal(subPlateTop, subPlateRight);
shapeBorderCoordinates[2] = PointReal(subPlateBottom, subPlateLeft);
shapeBorderCoordinates[3] = PointReal(subPlateBottom, subPlateRight);
for (int i = 0; i < 4; ++i)
{
if (transform)
{
// At the LatLon representation, first is a latitude that is a Y. Second -
// longitude that is X. Before pass it to the pj_transform() we must put to
// correct places:
// first - X (lon), second - Y (lat)
PJ_COORD coord{};
coord.uv.u = shapeBorderCoordinates[i].y;
coord.uv.v = shapeBorderCoordinates[i].x;
coord = proj_trans(transform, PJ_INV, coord);
shapeBorderCoordinates[i].x = coord.xy.x;
shapeBorderCoordinates[i].y = coord.xy.y;
}
// Recalculate coordinates to the raster pixels
//geo_to_pixel_coordinate(geoTransform,
// shapeBorderCoordinates[i].x, shapeBorderCoordinates[i].y, shapeBorderPixels[i].x, shapeBorderPixels[i].y);
geoTransform.coordinateToPixel(shapeBorderCoordinates[i].x, shapeBorderCoordinates[i].y, shapeBorderPixels[i].x, shapeBorderPixels[i].y);
// TODO: add processing for partial shapes: there is a lot of scanned maps with breaks
// one shape to the seleveral ones. Some notes:
// - if coordinates negate, set it to the zero
// - if coordinates greater real shape size, limit it with shape size
}
}
fprintf(stderr,
"Shape border coordinates %s:\n"
" (%.6f, %.6f) (%.6f, %.6f)\n"
" (%.6f, %.6f) (%.6f, %.6f)\n",
plateNameStream.str().c_str(),
shapeBorderCoordinates[0].x, shapeBorderCoordinates[0].y,
shapeBorderCoordinates[1].x, shapeBorderCoordinates[1].y,
shapeBorderCoordinates[2].x, shapeBorderCoordinates[2].y,
shapeBorderCoordinates[3].x, shapeBorderCoordinates[3].y);
fprintf(stderr,
"Shape border in pixels %s:\n"
" (%5d, %5d) (%5d, %5d)\n"
" (%5d, %5d) (%5d, %5d)\n",
plateNameStream.str().c_str(),
shapeBorderPixels[0].x, shapeBorderPixels[0].y,
shapeBorderPixels[1].x, shapeBorderPixels[1].y,
shapeBorderPixels[2].x, shapeBorderPixels[2].y,
shapeBorderPixels[3].x, shapeBorderPixels[3].y);
// Prepare "cutline" file. Use CSV with WKT:
// http://www.gdal.org/drv_csv.html
// https://en.wikipedia.org/wiki/Well-known_text
struct CutlineStreamFree
{
void operator()(ostream *ost)
{
if (ost != &cout &&
ost != &cerr &&
ost != &clog)
{
delete ost;
}
}
};
unique_ptr<ostream, CutlineStreamFree> cutline(&cout);
string cutlineFile = "<stdout>";
if (!generateOnly)
{
cutlineFile = generate_temp_file_name() + ".csv";
cutline.reset(new ofstream(cutlineFile.c_str()));
}
*cutline << "WKT,dummy\n" << "\"";
stringstream cutlinePolygon;
cutlinePolygon << "POLYGON((";
if (knownScale)
{
cutlinePolygon << shapeBorderCoordinates[0].x << " " << shapeBorderCoordinates[0].y << ",";
cutlinePolygon << shapeBorderCoordinates[1].x << " " << shapeBorderCoordinates[1].y << ",";
cutlinePolygon << shapeBorderCoordinates[3].x << " " << shapeBorderCoordinates[3].y << ",";
cutlinePolygon << shapeBorderCoordinates[2].x << " " << shapeBorderCoordinates[2].y;
}
else
{
cutlinePolygon << shapeBorderCoordinates[0].x << " " << shapeBorderCoordinates[0].y << ",";
// Additional cut dots
double lat = top1m;
for (double lon = left1m + 1; lon < right1m; lon += 1.00)
{
double u = lon;
double v = lat;
if (transform)
{
PJ_COORD coord{};
coord.uv.u = u;
coord.uv.v = v;
coord = proj_trans(transform, PJ_INV, coord);
u = coord.uv.u;
v = coord.uv.v;
}
cutlinePolygon << u << " " << v << ",";
}
cutlinePolygon << shapeBorderCoordinates[1].x << " " << shapeBorderCoordinates[1].y << ",";
cutlinePolygon << shapeBorderCoordinates[3].x << " " << shapeBorderCoordinates[3].y << ",";
// Additional cut dots
lat = bottom1m;
for (double lon = right1m - 1; lon > left1m; lon -= 1.00)
{
double u = lon;
double v = lat;
if (transform)
{
PJ_COORD coord{};
coord.uv.u = u;
coord.uv.v = v;
coord = proj_trans(transform, PJ_INV, coord);
u = coord.uv.u;
v = coord.uv.v;
}
cutlinePolygon << u << " " << v << ",";
}
cutlinePolygon << shapeBorderCoordinates[2].x << " " << shapeBorderCoordinates[2].y;
}
// Close Polygon to make Gdal happy
cutlinePolygon << "," << shapeBorderCoordinates[0].x << " " << shapeBorderCoordinates[0].y;
cutlinePolygon << "))";
*cutline << cutlinePolygon.str();
*cutline << "\",\n";
cutline.reset();
clog << cutlineFile << endl;
clog << "Polygon:\n" << cutlinePolygon.str() << endl;
if (!generateOnly)
{
{
auto pid = fork();
if (pid == 0)
{
vector<char*> args = {
::strdup(gdalwarpPath.c_str()),
::strdup("-of"),
::strdup(ouDriver.c_str()),
::strdup("-dstalpha"),
::strdup("-cutline"),
::strdup(cutlineFile.c_str()),
};
if (cropToCutline)
args.push_back(::strdup("-crop_to_cutline"));
if (!gdalwarpOpts.empty())
{
// Reserve +1 for future nullptr and input/output file
args.reserve(args.size() + gdalwarpOpts.size() + 3);
copy(begin(gdalwarpOpts), end(gdalwarpOpts), back_inserter(args));
}
args.insert(args.end(), {::strdup(inFileName.c_str()),
::strdup(ouFileName.c_str()),
nullptr});
clog << "gdalwarp args:\n";
for (auto arg : args)
{
if (arg)
clog << " " << arg << endl;
}
if (execvp(gdalwarpPath.c_str(), args.data()) < 0)
exit(1);
}
waitpid(pid, nullptr, 0);
}
unlink(cutlineFile.c_str());
}
}
return 0;
}
CrsInstance::CrsInstance()
: m_crs(nullptr, deleter)
{
}
CrsInstance::CrsInstance(std::string_view definition)
: CrsInstance()
{
m_definition = definition;
m_crs.reset(proj_create(PJ_DEFAULT_CTX,
pj_add_type_crs_if_needed(definition).c_str()));
if (m_crs)
// can be checked via `operator bool()`
return;
auto type = proj_get_type(m_crs.get());
if (type == PJ_TYPE_BOUND_CRS) {
m_crs.reset(proj_get_source_crs(PJ_DEFAULT_CTX, m_crs.get()));
type = proj_get_type(m_crs.get());
}
if (type == PJ_TYPE_GEOGRAPHIC_2D_CRS ||
type == PJ_TYPE_GEOGRAPHIC_3D_CRS ||
type == PJ_TYPE_GEODETIC_CRS) {
pj_ptr_t cs = {proj_crs_get_coordinate_system(PJ_DEFAULT_CTX, m_crs.get()), deleter};
assert(cs);
const char *axisName = "";
proj_cs_get_axis_info(PJ_DEFAULT_CTX, cs.get(), 0,
&axisName, // name
nullptr, // abbrev
nullptr, // direction
&m_toRadians,
nullptr, // unit name
nullptr, // unit authority
nullptr // unit code
);
std::clog << __PRETTY_FUNCTION__ << ": axisName=" << axisName << '\n';
auto axisNameView = std::string_view(axisName);
m_isLatFirst = axisNameView.find("latitude") != std::string_view::npos;
m_isLongLat = m_isLatFirst || axisNameView.find("longitude") != std::string_view::npos;
}
}
bool CrsInstance::isLatLong() const
{
return m_isLongLat;
}
bool CrsInstance::isLatFirst() const
{
return m_isLatFirst;
}
double CrsInstance::toRadians() const
{
return m_toRadians;
}
std::string_view CrsInstance::definition() const
{
return m_definition;
}
CrsInstance::operator bool() const
{
return bool(m_crs);
}
PJ *CrsInstance::get() const
{
return m_crs.get();
}
void CrsInstance::reset()