-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
2869 lines (2659 loc) · 184 KB
/
Copy pathmain.cpp
File metadata and controls
2869 lines (2659 loc) · 184 KB
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
#define UNICODE
#include <iostream>
#include "fileformat.pb.h"
#include "osmformat.pb.h"
#include "OBF.pb.h"
#include "vector_tile.pb.h"
#include "osmand_region_info.pb.h"
#include "osmand_index.pb.h"
#include <fstream>
#include <string>
#include "sqlite3.h"
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <iomanip>
#include <unordered_set>
#if defined(_WIN32)
#include <windows.h>
#include <process.h>
#include <commctrl.h>
#endif
#include <wchar.h>
#include <codecvt>
#include <filesystem>
#include <unordered_map>
#include <memory>
#include <string_view>
#include <filesystem>
#include <array>
#include <atomic>
#include <iomanip>
#include <sstream>
#include <cmath>
#if defined(__linux__)
#include <unistd.h>
#endif
#include <thread>
#include <chrono>
using namespace std;
void writeOBFVarint32or64BE(google::protobuf::io::CodedOutputStream &i, uint64_t n);
uint64_t copyRawFileIntoCodedOutputStream(google::protobuf::io::CodedOutputStream &cos, string filename, int64_t size);
void copyRawInputStreamIntoCodedOutputStream(google::protobuf::io::CodedOutputStream &cos, istream *inputFile, int64_t size);
static inline int64_t getFileSize(string name);
std::wstring utf8_to_wstring(const std::string& str);
std::string wstring_to_utf8(const std::wstring& str);
uint64_t writeMapIndex(string name);
void writeOsmAndStructure_mapIndex_rules(google::protobuf::io::CodedOutputStream &cos);
void writeMapEncodingRule(string tag, string value, uint32_t minZoom);
static inline uint64_t GetSystemTimeAsUnixTime();
static inline int32_t latitudeToInt32(double latitude, uint32_t zoom, bool fullAccuracy = false);
static inline int32_t longitudeToInt32(double longitude, uint32_t zoom, bool fullAccuracy = false);
void writeOsmAndStructure_mapIndex_detailed_level_1x1(unsigned char *coordinatesByteArrayPtrWithinThread, unsigned char *typesByteArrayPtrWithinThread, unsigned char *additionalTypesByteArrayPtrWithinThread, unsigned char *stringNamesByteArrayPtrWithinThread);
void writeOsmAndStructure_mapIndex_detailed_level_single_power_of_2_split(int pow2, bool mediumZoom);
void writeOsmAndStructure_mapIndex_detailed_level_4_4_pow2_split(int pow2, bool mediumZoom);
void writeOsmAndStructure_mapIndex_detailed_level_4_4_4_pow2_split(int pow2, bool mediumZoom);
double int32ToLatitude(uint64_t in, uint32_t zoom);
double int32ToLongitude(uint64_t in, uint32_t zoom);
uint32_t getVarintRequiredBytes(uint64_t i);
void printHelp();
static inline int min3(int64_t a, int64_t b, int64_t c);
void writeOsmAndStructure_mapIndex_levels_block_SingleSplitThreadWorker(void *param);
#if defined(_WIN32)
LRESULT CALLBACK WndProc(HWND hwndMainWin, UINT msg, WPARAM wParam, LPARAM lParam);
bool CALLBACK SetFont(HWND child, LPARAM font);
#endif
void VWSimplify(vector<uint64_t> *nodeIDVector, vector<uint64_t> *latVector, vector<uint64_t> *lonVector, uint64_t minAreaX2);
string humanReadableTimeFromSeconds(unsigned int seconds);
void createOBFFile(void *param);
void calculateTotalRectanglesForGUI();
#define FILE_COPY_BUFFER_SIZE (32 * 1048576) //This needs the parentheses or it will evaluate the numbers separately
#define PI 3.1415926535
unsigned char *fileCopyBuffer = nullptr;
#define PROTOBUF_SERIALIZE_TEMP_BUFFER_SIZE 1048576
//Multiples of 32 so this is 1024
#define NODE_BLOCK_OVERLAP 32
#define IDEAL_BLOCK_MAX_SIZE 750000
static const char* GET_KEYS_AND_VALUES_SORTED_QUERY = "SELECT key, value, (key in (%HUMAN_READABLE_WHITELIST%) or key like 'addr:%') as human_readable, COUNT(*) p, COUNT(*) OVER () AS total_rows FROM (SELECT key, value FROM node_tags WHERE %MACHINE_READABLE_BLACKLIST% UNION ALL SELECT key, value FROM way_tags WHERE %MACHINE_READABLE_BLACKLIST%) q1 GROUP BY concat(key, \"=\", value) ORDER BY p DESC;";
static const char* GET_WAY_AND_NODE_KEYS_SORTED_QUERY_BLACKLIST = "select key, count(key) as p, way from (select q1.*, 1 as way from way_tags q1 union all select q2.*, 0 as way from node_tags q2) where key not like 'tiger%' and key not like 'source%' and key not like 'attribution%' and key not like 'nhd%' and key not like 'power%' and key not like 'created_by%' and key not like 'seamark%' and key not like 'gnis%' and key not like 'fid%' and key not like 'fixme%' and key not like 'roof%' group by key order by p desc;";
static const char* QUERY_GET_UNIQUE_WAY_AND_NODE_TAG_VALUES_BLACKLIST = "select value, count(*) as p, way, count(*) over () as total from (select q1.value, 1 as way from way_tags q1 inner join way_nodes q4 on q4.way_id=q1.way_id and q4.node_order=1 inner join rtree_node q5 on q5.node_id=q4.node_id and q5.max_lat >= :bottom and q5.min_lat <= :top and q5.max_lon >= :left and q5.min_lon <= :right where q1.key not like 'tiger%' and q1.key not like 'source%' and q1.key not like 'attribution%' and q1.key not like 'nhd%' and q1.key not like 'power%' and q1.key not like 'created_by%' and q1.key not like 'seamark%' and q1.key not like 'gnis%' and q1.key not like 'fid%' and q1.key not like 'fixme%' and q1.key not like 'roof%' union all select q2.value, 0 as way from node_tags q2 inner join rtree_node q3 on q3.node_id=q2.node_id and q3.max_lat >= :bottom and q3.min_lat <= :top and q3.max_lon >= :left and q3.min_lon <= :right where q2.key not like 'tiger%' and q2.key not like 'source%' and q2.key not like 'attribution%' and q2.key not like 'nhd%' and q2.key not like 'power%' and q2.key not like 'created_by%' and q2.key not like 'seamark%' and q2.key not like 'gnis%' and q2.key not like 'fid%' and q2.key not like 'fixme%' and q2.key not like 'roof%') group by value order by p desc;";
static const char* QUERY_GET_MEDIAN_UNIQUE_ID = "select median(id) from (select q1.way_id as id from way_nodes q1 inner join rtree_node q2 on q2.node_id=q1.node_id where q1.node_order=1 and (q2.max_lat >= :bottom and q2.min_lat <= :top) and (q2.max_lon >= :left and q2.min_lon <= :right) union all select node_id as id from rtree_node q4 where (q4.max_lat >= :bottom and q4.min_lat <= :top) and (q4.max_lon >= :left and q4.min_lon <= :right));";
static const char* QUERY_GET_UNIQUE_WAY_AND_NODE_TAG_VALUES_BLACKLIST_MEDIUM_ZOOM = "select value, count(value) as p, way, count(*) over () from (select q1.*, 1 as way from way_tags q1 inner join way_nodes q4 on q4.node_order=1 and q4.way_id=q1.way_id inner join rtree_node q5 on q5.node_id=q4.node_id where (q5.max_lat >= :bottom and q5.min_lat <= :top) and (q5.max_lon >= :left and q5.min_lon <= :right) union all select q2.*, 0 as way from node_tags q2 inner join rtree_node q3 on q3.node_id=q2.node_id where (q3.max_lat >= :bottom and q3.min_lat <= :top) and (q3.max_lon >= :left and q3.min_lon <= :right)) where way_id in (select q1.way_id from (select q1.way_id from way_nodes q1 inner join rtree_node q2 on q2.node_id=q1.node_id inner join way_tags q3 on q3.way_id=q1.way_id where q1.node_order=1 and (q2.max_lat >= :bottom and q2.min_lat <= :top) and (q2.max_lon >= :left and q2.min_lon <= :right) and ((key = 'highway' and value in ('motorway', 'motorway_link', 'motorway_junction', 'primary', 'primary_link', 'secondary', 'secondary_link', 'tertiary', 'tertiary_link', 'trunk', 'trunk_link')) or (key in ('lanes', 'lanes:forward', 'lanes:backward', 'hgv', 'maxspeed', 'oneway', 'destination', 'motorway_link')))) q1) and ((key = 'highway' and value in ('motorway', 'motorway_link', 'motorway_junction', 'primary', 'primary_link', 'secondary', 'secondary_link', 'tertiary', 'tertiary_link', 'trunk', 'trunk_link')) or (key in ('lanes', 'lanes:forward', 'lanes:backward', 'hgv', 'maxspeed', 'oneway', 'name', 'ref', 'destination', 'motorway_link'))) group by value order by p desc;";
static const char* QUERY_GET_WAY_NODES = "select q1.*, lag(q1.lat, 1) over () as prevLat, lag(q1.lon, 1) over () as prevLon, row_number() over (partition by q1.way_id order by way_id asc, node_order asc) as index_within_way from ( select way_id, q1.node_id, node_order, lat, lon from way_nodes q1 left join nodes q2 on q1.node_id=q2.node_id order by way_id asc, node_order asc) q1 WHERE lat is not null AND lon is not null /*and way_id=1527655305*/;";
static const char* QUERY_GET_WAY_TAGS = "select q1.key, q1.value, (case when q1.key in (%HIGH_PRIORITY_WHITELIST%) then 0 when key in (%HUMAN_READABLE_WHITELIST%) then 2 else 1 end) as tagType from way_tags q1 where %MACHINE_READABLE_BLACKLIST% %WAY_ID% group by key, value order by tagType asc, key asc, value asc;";
static const char* QUERY_GET_NODE_TAGS_MACHINE_READABLE = "select concat(q1.key, '=', q1.value) as tag, (case when q1.key in (%HIGH_PRIORITY_WHITELIST%) then 1 else 0 end) as high_priority from node_tags q1 where %KEY_BLACKLIST% and node_id=%NODE_ID% group by key, value order by high_priority desc, key asc, value asc";
static const string TAG_KEYS_HIGH_PRIORITY_WHITELIST = "'highway', 'service', 'building', 'amenity', 'barrier'";
static const string TAG_KEYS_BLACKLIST = "key not like 'tiger%' AND key NOT LIKE 'source%' AND key NOT LIKE 'attribution%' AND key NOT LIKE 'nhd%' AND key NOT LIKE 'power%' AND key NOT LIKE 'created_by%' AND key NOT LIKE 'seamark%' AND key NOT LIKE 'gnis%' AND key NOT LIKE 'fid%' AND key NOT LIKE 'fixme%' AND key NOT LIKE 'roof%' AND key NOT LIKE 'ref' AND key NOT LIKE 'ref:%' AND key NOT LIKE 'website%' AND key NOT LIKE 'wikipedia%' AND key NOT LIKE 'wikimedia_commons%' AND key NOT LIKE 'ele%' AND key NOT LIKE 'description%' AND key NOT LIKE 'length%' AND key NOT LIKE 'architect%' AND key NOT LIKE '%colour%' AND key NOT LIKE 'operator:wikidata%' AND key NOT LIKE 'height%' AND key NOT LIKE 'image%' AND key NOT LIKE 'mapillary%' AND key NOT LIKE 'mascot%' AND key NOT LIKE 'note%' AND key NOT LIKE 'artist_name%' AND key NOT LIKE 'check_date%' AND key NOT LIKE 'reg_name%' AND key NOT LIKE 'short_name%' AND key NOT LIKE 'distance%' AND key NOT LIKE 'direction%' AND key NOT LIKE 'heritage%'";
static const string TAG_KEYS_MACHINE_READABLE_BLACKLIST = "key not like 'tiger%' AND key NOT LIKE 'source%' AND key NOT LIKE 'attribution%' AND key NOT LIKE 'nhd%' AND key NOT LIKE 'power%' AND key NOT LIKE 'created_by%' AND key NOT LIKE 'seamark%' AND key NOT LIKE 'gnis%' AND key NOT LIKE 'fid%' AND key NOT LIKE 'fixme%' AND key NOT LIKE 'roof%' AND key NOT LIKE 'addr:%' AND key NOT LIKE 'ref' AND key NOT LIKE 'ref:%' AND key NOT LIKE 'website%' AND key NOT LIKE 'wikipedia%' AND key NOT LIKE 'wikimedia_commons%' AND key NOT LIKE 'ele%' AND key NOT LIKE 'description%' AND key NOT LIKE 'length%' AND key NOT LIKE 'architect%' AND key NOT LIKE '%colour%' AND key NOT LIKE 'operator:wikidata%' AND key NOT LIKE 'height%' AND key NOT LIKE 'image%' AND key NOT LIKE 'mapillary%' AND key NOT LIKE 'mascot%' AND key NOT LIKE 'note%' AND key NOT LIKE 'artist_name%' AND key NOT LIKE 'check_date%' AND key NOT LIKE 'reg_name%' AND key NOT LIKE 'short_name%' AND key NOT LIKE 'distance%' AND key NOT LIKE 'direction%' AND key NOT LIKE 'heritage%'";
static const string TAG_KEYS_HUMAN_READABLE_WHITELIST = "'name', 'name_1', 'name_2', 'old_name', 'official_name', 'addr:', 'addr:housenumber', 'addr:street', 'addr:city', 'addr:state', 'addr:postcode', 'ref', 'website', 'wikipedia', 'wikidata', 'wikimedia_commons', 'opening_hours', 'brand', 'alt_name', 'start_date', 'contact', 'phone', 'fax', 'description', 'email', 'addr:country', 'operator'";
static const string KEY_BLACKLIST = "key NOT LIKE 'tiger%' AND key NOT LIKE 'source%' AND key NOT LIKE 'attribution%' AND key NOT LIKE 'nhd%' AND key NOT LIKE 'power%' AND key NOT LIKE 'created_by%' AND key NOT LIKE 'seamark%' AND key NOT LIKE 'gnis%' AND key NOT LIKE 'fid%' AND key NOT LIKE 'fixme%' AND key NOT LIKE 'roof%' AND key NOT LIKE 'ncos%' AND key NOT LIKE 'was:%' AND key NOT LIKE 'old_name%'";
static unordered_map<string, uint32_t> keyMap;
static inline uint32_t getSInt32FromInt32(int32_t i) {
return (static_cast<uint32_t>(i) << 1) ^ static_cast<uint32_t>(i >> 31);
}
unsigned int getClosestNextLowerPowerOf2(unsigned int i) {
unsigned int j = 0;
unsigned int retVal = 0;
while ((2 << retVal) <= i) retVal++;
return retVal;
}
class BoundingRectangle {
public:
double left = 0;
double bottom = 0;
double right = 0;
double top = 0;
double width = 0;
double height = 0;
uint64_t leftInt32 = 0;
uint64_t rightInt32 = 0;
uint64_t topInt32 = 0;
uint64_t bottomInt32 = 0;
uint64_t widthInt32 = 0;
uint64_t heightInt32 = 0;
uint64_t MapDataBoxBytesSizeWithoutTagAndFixed32Size = 0;
void calculateDoubleValuesFromInt32() {
this->left = int32ToLongitude(this->leftInt32, 21);
this->right = int32ToLongitude(this->rightInt32, 21);
this->top = int32ToLatitude(this->topInt32, 21);
this->bottom = int32ToLatitude(this->bottomInt32, 21);
this->width = this->right - this->left;
this->height = this->top - this->bottom;
this->widthInt32 = this->rightInt32 - this->leftInt32;
this->heightInt32 = this->bottomInt32 - this->topInt32;
}
void calculateMapDataBoxBytesSizeWithoutTagAndFixed32Size(BoundingRectangle *outerRectangle) {
MapDataBoxBytesSizeWithoutTagAndFixed32Size =
1 + getVarintRequiredBytes(getSInt32FromInt32(this->leftInt32 - outerRectangle->leftInt32)) +
1 + getVarintRequiredBytes(getSInt32FromInt32(this->rightInt32 - outerRectangle->rightInt32)) +
1 + getVarintRequiredBytes(getSInt32FromInt32(this->topInt32 - outerRectangle->topInt32)) +
1 + getVarintRequiredBytes(getSInt32FromInt32(this->bottomInt32 - outerRectangle->bottomInt32)) +
1 + 4;
}
void calculateInt32ValuesFromDouble() {
this->leftInt32 = longitudeToInt32(this->left, 21) & 0xffffffe0;
this->rightInt32 = longitudeToInt32(this->right, 21) & 0xffffffe0;
this->topInt32 = latitudeToInt32(this->top, 21) & 0xffffffe0;
this->bottomInt32 = latitudeToInt32(this->bottom, 21) & 0xffffffe0;
this->width = this->right - this->left;
this->height = this->top - this->bottom;
this->widthInt32 = this->rightInt32 - this->leftInt32;
this->heightInt32 = this->bottomInt32 - this->topInt32;
}
void expandByPercent(double percent) {
uint64_t widthExpandAmountInt32 = (this->widthInt32 * percent) / 100.0;
uint64_t heightExpandAmountInt32 = (this->heightInt32 * percent) / 100.0;
this->leftInt32 -= widthExpandAmountInt32;
this->leftInt32 &= 0xffffffe0;
this->rightInt32 += widthExpandAmountInt32;
this->rightInt32 &= 0xffffffe0;
this->topInt32 -= heightExpandAmountInt32;
this->topInt32 &= 0xffffffe0;
this->bottomInt32 += heightExpandAmountInt32;
this->bottomInt32 &= 0xffffffe0;
this->calculateDoubleValuesFromInt32();
}
void expandByAbsoluteValue(int64_t n) {
this->leftInt32 -= n;
if ((this->leftInt32 & 0x1f) >= 16) this->leftInt32 -= 32;
this->leftInt32 &= 0xffffffe0;
this->rightInt32 += n;
if ((this->rightInt32 & 0x1f) >= 16) this->rightInt32 -= 32;
this->rightInt32 &= 0xffffffe0;
this->topInt32 -= n;
if ((this->topInt32 & 0x1f) >= 16) this->topInt32 += 32;
this->topInt32 &= 0xffffffe0;
this->bottomInt32 += n;
if ((this->bottomInt32 & 0x1f) >= 16) this->bottomInt32 += 32;
this->bottomInt32 &= 0xffffffe0;
this->calculateDoubleValuesFromInt32();
}
};
static BoundingRectangle overallBoundingRectangle;
struct MapDataBlockThreadInfo {
string tempFilename;
BoundingRectangle *rectangles;
int rectanglesCount;
int rectanglesStartIdx;
int stride;
sqlite3 *dbConnection;
sqlite3_stmt *stmt;
int threadID;
unsigned char *coordinatesByteArrayPtrWithinThread;
unsigned char *typesByteArrayPtrWithinThread;
unsigned char *additionalTypesByteArrayPtrWithinThread;
unsigned char *stringNamesByteArrayPtrWithinThread;
bool mediumZoom;
uint64_t *mapDataBlockSizes;
MapDataBlockThreadInfo():tempFilename(""),rectangles(nullptr),rectanglesCount(0),rectanglesStartIdx(0),stride(0),dbConnection(nullptr),stmt(nullptr),threadID(0),coordinatesByteArrayPtrWithinThread(nullptr),typesByteArrayPtrWithinThread(nullptr),additionalTypesByteArrayPtrWithinThread(nullptr),stringNamesByteArrayPtrWithinThread(nullptr),mediumZoom(false),mapDataBlockSizes(nullptr){}
};
void writeOsmAndStructure_mapIndex_levels_block(string tempFilename, BoundingRectangle *rectangle, unsigned int blockIdx, sqlite3 *dbConnection, sqlite3_stmt *stmt, sqlite3_stmt *wayNodeStmt, sqlite3_stmt *wayTagStmt, int threadID, unsigned char *coordinatesByteArrayPtrWithinThread, unsigned char *typesByteArrayPtrWithinThread, unsigned char *additionalTypesByteArrayPtrWithinThread, unsigned char *stringNamesByteArrayPtrWithinThread, bool mediumZoom);
template <typename T>
T swap_endian(T u) {
static_assert(sizeof(char) == 1, "Bytes must be 8 bits");
union {
T u;
unsigned char s[sizeof(T)];
} source, dest;
source.u = u;
for (size_t i = 0; i < sizeof(T); ++i) {
dest.s[i] = source.s[sizeof(T) - i - 1];
}
return dest.u;
}
static uint64_t currentDiskUsage = 0;
static sqlite3 *db;
static sqlite3_stmt *res;
static string databaseFilename = "";
static bool shouldKeepTempFiles = false;
static int forcedSplitPowerOf2 = -1;
static int forceSplitMode = -1; //-1 = automatic, 0 = single, 1 = 2-level quadtree, 2 = 3-level quadtree
static bool verbose = false;
uint32_t screenWidth, screenHeight;
//static unsigned int threads = 4;
static unsigned int progressBitmapWidth, progressBitmapHeight, progressTotalRectangles;
atomic<unsigned int> progressCompletedRectangles = {0};
static unsigned char *progressBitmapPtr = nullptr;
static bool shouldShowGUI = true;
static unsigned int guiSelectedQuadtreeSplit = 0;
static unsigned int guiSelectedSplitWithinQuadtree = 0;
uint32_t pid = 0;
uint64_t sqliteCacheSizeMiBPerThread = 64;
uint64_t sqliteMMAPSizeMiBPerThread = 64;
#define ID_STARTBTN 1
#define ID_INPUT_FILENAME_FIELD 2
#define ID_OUTPUT_FILENAME_FIELD 3
#define WM_USER_REDRAW (WM_USER + 1)
#define ID_QUADTREE_COMBOBOX 4
#define ID_SPLIT_COMBOBOX 5
#define ID_BROWSE_INPUT_FILE 6
#define ID_BROWSE_OUTPUT_FILE 7
#if defined(_WIN32)
static HWND hwndMainWin;
static HWND hwndStartBtn;
static HWND hwndInputFilenameLabel;
static HWND hwndOutputFilenameLabel;
static HWND hwndInputFilenameField;
static HWND hwndOutputFilenameField;
static HWND hwndSplitLabel;
static HWND hwndQuadtreeCombobox;
static HWND hwndSplitCombobox;
static HWND hwndRectangleCountLabel;
static HWND hwndDetailedVectorMapProgressLabel;
static HWND hwndDetailedVectorMapProgressBar;
static HWND hwndProgressPercentLabel;
static HWND hwndInputFilenameBrowseButton;
static HWND hwndOutputFilenameBrowseButton;
#endif
struct SQLite3StatementDeleter {
void operator()(sqlite3_stmt* stmt) const {
if (stmt) {
sqlite3_finalize(stmt);
stmt = nullptr;
}
}
};
string inputFilename = "";
string outputFilename = "";
bool foundInputFilenameArgument = false;
bool foundOutputFilenameArgument = false;
int main(int argc, char** argv) {
cout << "OsmAndMapCreator++ v0.1.12" << endl;
#if defined(_WIN32)
pid = GetCurrentProcessId();
#elif defined(__linux__)
pid = getpid();
#endif
//If there is only 1 argument that is not the help option then assume that it's the input filename
if (argc == 2) {
filesystem::path inputFilePathTmp = string(argv[1]);
if (filesystem::exists(inputFilePathTmp)) {
inputFilename = string(argv[1]);
filesystem::path outputFilenamePath = inputFilename;
outputFilenamePath = outputFilenamePath.parent_path() / outputFilenamePath.stem();
outputFilename = outputFilenamePath.string() + ".obf";
} else {
string_view arg_view(argv[1]);
printHelp();
#if defined(__linux__)
cout << endl;
#endif
return 0;
}
} else if (argc > 2) {
for (int i = 1; i < argc; i++) {
string_view arg_view(argv[i]);
if ((arg_view == "-i"sv || arg_view == "-input"sv || arg_view == "--input"sv || arg_view == "/i"sv) && i < (argc - 1) /* Don't try to read past the end of the arguments */) {
inputFilename = string(argv[i + 1]);
foundInputFilenameArgument = true;
filesystem::path outputFilenamePath = inputFilename;
outputFilenamePath = outputFilenamePath.parent_path() / outputFilenamePath.stem();
outputFilename = outputFilenamePath.string() + ".obf";
}
if ((arg_view == "-o"sv || arg_view == "-output"sv || arg_view == "--output"sv || arg_view == "/o"sv) && i < (argc - 1)) {
foundOutputFilenameArgument = true;
outputFilename = string(argv[i + 1]);
}
if ((arg_view == "-keep-temp-files"sv || arg_view == "--keep-temp-files"sv || arg_view == "-keep_temp_files"sv || arg_view == "--keep_temp_files"sv || arg_view == "/keep-temp-files" || arg_view == "/keep_temp_files")) {
shouldKeepTempFiles = true;
}
//if ((arg_view == "-force-single-split"sv || arg_view == "--force-single-split"sv || arg_view == "/force-single-split"sv) && i < (argc - 1)) {
//if (forceSplitMode < 0 /* single split*/) {
//forceSplitMode = 0;
//forcedSplitPowerOf2 = atoi(argv[i + 1]); //A forced quadtree split takes precedence
//}
//}
if ((arg_view == "-force-quadtree2-split"sv || arg_view == "--force-quadtree2-split"sv || arg_view == "/force-quadtree2-split"sv) && i < (argc - 1)) {
if (forceSplitMode < 1 /* 2-level quadtree */) {
forceSplitMode = 1;
forcedSplitPowerOf2 = atoi(argv[i + 1]);
}
}
if ((arg_view == "-force-quadtree3-split"sv || arg_view == "--force-quadtree3-split"sv || arg_view == "/force-quadtree3-split"sv) && i < (argc - 1)) {
if (forceSplitMode < 2 /* 3-level quadtree */) {
forceSplitMode = 2;
forcedSplitPowerOf2 = atoi(argv[i + 1]);
}
}
if ((arg_view == "-nogui"sv || arg_view == "--nogui"sv || arg_view == "/nogui"sv || arg_view == "-no-gui"sv || arg_view == "--no-gui"sv || arg_view == "/no-gui"sv)) {
shouldShowGUI = false;
}
if ((arg_view == "-verbose"sv || arg_view == "--verbose"sv || arg_view == "/verbose"sv)) {
verbose = true;
}
if ((arg_view == "-cache-size"sv || arg_view == "--cache-size"sv || arg_view == "/cache-size"sv) && i < (argc - 1)) {
sqliteCacheSizeMiBPerThread = atoi(argv[i + 1]);
if (sqliteCacheSizeMiBPerThread == 0) sqliteCacheSizeMiBPerThread = 64;
}
if ((arg_view == "-mmap-size"sv || arg_view == "--mmap-size"sv || arg_view == "/mmap-size"sv) && i < (argc - 1)) {
sqliteMMAPSizeMiBPerThread = atoi(argv[i + 1]);
if (sqliteMMAPSizeMiBPerThread == 0) sqliteMMAPSizeMiBPerThread = 64;
}
}
}
if (shouldShowGUI) {
#if defined(_WIN32)
INITCOMMONCONTROLSEX iccx;
iccx.dwSize = sizeof(INITCOMMONCONTROLSEX);
iccx.dwICC = ICC_LISTVIEW_CLASSES;
InitCommonControlsEx(&iccx);
MSG msg;
WNDCLASS wc = { 0 };
wc.lpszClassName = TEXT("OMCPPMainWin");
HINSTANCE hInstance = GetModuleHandle(NULL);
wc.hInstance = hInstance;
wc.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1);
wc.lpfnWndProc = WndProc;
RegisterClass(&wc);
screenWidth = GetSystemMetrics(SM_CXSCREEN);
screenHeight = GetSystemMetrics(SM_CYSCREEN);
uint32_t windowWidth, windowHeight;
windowWidth = 800;
windowHeight = 900;
hwndMainWin = CreateWindowW(wc.lpszClassName, L"OsmAndMapCreator++", WS_OVERLAPPEDWINDOW | WS_VISIBLE, 0, 0, windowWidth, windowHeight, 0, 0, hInstance, 0);
hwndStartBtn = CreateWindowEx(0, L"BUTTON", L"Convert", WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, 650, 812, 120, 25, hwndMainWin, (HMENU)ID_STARTBTN, (HINSTANCE)GetWindowLongPtr(hwndMainWin, GWLP_HINSTANCE), NULL);
hwndInputFilenameLabel = CreateWindowEx(0, L"STATIC", L"Input filename", WS_CHILD | WS_VISIBLE | SS_LEFT, 12, 680, 200, 20, hwndMainWin, NULL, (HINSTANCE)GetWindowLongPtr(hwndMainWin, GWLP_HINSTANCE), NULL);
hwndOutputFilenameLabel = CreateWindowEx(0, L"STATIC", L"Output filename", WS_CHILD | WS_VISIBLE | SS_LEFT, 12, 710, 200, 20, hwndMainWin, NULL, (HINSTANCE)GetWindowLongPtr(hwndMainWin, GWLP_HINSTANCE), NULL);
hwndInputFilenameField = CreateWindowEx(WS_EX_CLIENTEDGE, L"EDIT", utf8_to_wstring(inputFilename).c_str(), WS_CHILD | WS_VISIBLE | WS_TABSTOP | ES_LEFT, 100, 680, 390, 20, hwndMainWin, (HMENU)ID_INPUT_FILENAME_FIELD, (HINSTANCE)GetWindowLongPtr(hwndMainWin, GWLP_HINSTANCE), NULL);
hwndOutputFilenameField = CreateWindowEx(WS_EX_CLIENTEDGE, L"EDIT", utf8_to_wstring(outputFilename).c_str(), WS_CHILD | WS_VISIBLE | WS_TABSTOP | ES_LEFT, 100, 708, 390, 20, hwndMainWin, (HMENU)ID_OUTPUT_FILENAME_FIELD, (HINSTANCE)GetWindowLongPtr(hwndMainWin, GWLP_HINSTANCE), NULL);
hwndSplitLabel = CreateWindowEx(0, L"STATIC", L"Split mode", WS_CHILD | WS_VISIBLE | SS_LEFT, 12, 740, 150, 20, hwndMainWin, NULL, (HINSTANCE)GetWindowLongPtr(hwndMainWin, GWLP_HINSTANCE), NULL);
hwndQuadtreeCombobox = CreateWindowEx(0, L"COMBOBOX", NULL, WS_CHILD | WS_VISIBLE | CBS_DROPDOWNLIST, 100, 738, 140, 20, hwndMainWin, (HMENU)ID_QUADTREE_COMBOBOX, (HINSTANCE)GetWindowLongPtr(hwndMainWin, GWLP_HINSTANCE), NULL);
//SendMessage(hwndQuadtreeCombobox, CB_ADDSTRING, 0, (LPARAM)L"1-level quadtree 4:");
SendMessage(hwndQuadtreeCombobox, CB_ADDSTRING, 0, (LPARAM)L"2-level quadtree 4:4:");
SendMessage(hwndQuadtreeCombobox, CB_ADDSTRING, 0, (LPARAM)L"3-level quadtree 4:4:4:");
if (forceSplitMode == -1) {
SendMessage(hwndQuadtreeCombobox, CB_SETCURSEL, (WPARAM)1, 0);
guiSelectedQuadtreeSplit = 1;
} else {
SendMessage(hwndQuadtreeCombobox, CB_SETCURSEL, (WPARAM)(forceSplitMode - 1), 0);
guiSelectedQuadtreeSplit = (forceSplitMode - 1);
}
hwndSplitCombobox = CreateWindowEx(0, L"COMBOBOX", NULL, WS_CHILD | WS_VISIBLE | CBS_DROPDOWNLIST, 250, 738, 240, 20, hwndMainWin, (HMENU)ID_SPLIT_COMBOBOX, (HINSTANCE)GetWindowLongPtr(hwndMainWin, GWLP_HINSTANCE), NULL);
SendMessage(hwndSplitCombobox, CB_ADDSTRING, 0, (LPARAM)L"Auto");
SendMessage(hwndSplitCombobox, CB_ADDSTRING, 0, (LPARAM)L"1x1 (single box)");
SendMessage(hwndSplitCombobox, CB_ADDSTRING, 0, (LPARAM)L"2x2 (4 boxes)");
SendMessage(hwndSplitCombobox, CB_ADDSTRING, 0, (LPARAM)L"4x4 (16 boxes)");
SendMessage(hwndSplitCombobox, CB_ADDSTRING, 0, (LPARAM)L"8x8 (64 boxes)");
SendMessage(hwndSplitCombobox, CB_ADDSTRING, 0, (LPARAM)L"16x16 (256 boxes)");
SendMessage(hwndSplitCombobox, CB_ADDSTRING, 0, (LPARAM)L"32x32 (1024 boxes)");
SendMessage(hwndSplitCombobox, CB_ADDSTRING, 0, (LPARAM)L"64x64 (4096 boxes; max recommended)");
SendMessage(hwndSplitCombobox, CB_ADDSTRING, 0, (LPARAM)L"128x128 (16384 boxes; very slow to render)");
//SendMessage(hwndSplitCombobox, CB_ADDSTRING, 0, (LPARAM)L"");
SendMessage(hwndSplitCombobox, CB_SETCURSEL, (WPARAM)(forcedSplitPowerOf2 + 1), 0);
guiSelectedSplitWithinQuadtree = (forcedSplitPowerOf2 + 1);
calculateTotalRectanglesForGUI();
hwndRectangleCountLabel = CreateWindowEx(0, L"STATIC", L"Data blocks", WS_CHILD | WS_VISIBLE | SS_LEFT, 500, 740, 200, 20, hwndMainWin, NULL, (HINSTANCE)GetWindowLongPtr(hwndMainWin, GWLP_HINSTANCE), NULL);
calculateTotalRectanglesForGUI();
hwndDetailedVectorMapProgressLabel = CreateWindowEx(0, L"STATIC", L"Detailed map", WS_CHILD | WS_VISIBLE | SS_LEFT, 12, 770, 85, 20, hwndMainWin, NULL, (HINSTANCE)GetWindowLongPtr(hwndMainWin, GWLP_HINSTANCE), NULL);
hwndDetailedVectorMapProgressBar = CreateWindowEx(0, PROGRESS_CLASS, NULL, WS_CHILD | WS_VISIBLE | SS_LEFT, 100, 768, 390, 20, hwndMainWin, NULL, (HINSTANCE)GetWindowLongPtr(hwndMainWin, GWLP_HINSTANCE), NULL);
hwndProgressPercentLabel = CreateWindowEx(0, L"STATIC", L"0%", WS_VISIBLE | WS_CHILD | SS_LEFT, 500, 770, 80, 20, hwndMainWin, NULL, (HINSTANCE)GetWindowLongPtr(hwndMainWin, GWLP_HINSTANCE), NULL);
SendMessage(hwndDetailedVectorMapProgressBar, PBM_SETRANGE, 0, (WPARAM)MAKELONG(0, 65535));
hwndInputFilenameBrowseButton = CreateWindowEx(0, L"BUTTON", L"Browse...", WS_TABSTOP | WS_VISIBLE | WS_CHILD, 500, 680, 80, 20, hwndMainWin, (HMENU)ID_BROWSE_INPUT_FILE, (HINSTANCE)GetWindowLongPtr(hwndMainWin, GWLP_HINSTANCE), NULL);
hwndOutputFilenameBrowseButton = CreateWindowEx(0, L"BUTTON", L"Browse...", WS_TABSTOP | WS_VISIBLE | WS_CHILD, 500, 708, 80, 20, hwndMainWin, (HMENU)ID_BROWSE_OUTPUT_FILE, (HINSTANCE)GetWindowLongPtr(hwndMainWin, GWLP_HINSTANCE), NULL);
EnumChildWindows(hwndMainWin, (WNDENUMPROC)SetFont, (LPARAM)GetStockObject(DEFAULT_GUI_FONT));
//if (!inputFilename.empty()) _beginthread(createOBFFile, 0, nullptr);
thread t;
if (!inputFilename.empty()) t = thread(createOBFFile, (void*)nullptr);
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
delete[] progressBitmapPtr;
#elif defined(__linux__)
createOBFFile(nullptr);
#endif
} else {
createOBFFile(nullptr);
}
#if defined(__linux__)
cout << endl;
#endif
return 0;
}
void createOBFFile(void *param) {
uint64_t overallStartTime = GetSystemTimeAsUnixTime();
if (inputFilename.empty()) {
cout << endl << "A database filename is required";
return;
}
filesystem::path inputFilePath = inputFilename;
//Use a default output filename if the user didn't choose one
if (!foundOutputFilenameArgument) {
filesystem::path outputFilenamePath = inputFilename;
outputFilenamePath = outputFilenamePath.parent_path() / outputFilenamePath.stem();
outputFilename = outputFilenamePath.string() + ".obf";
}
cout << endl << "Input file: \"" << inputFilename << "\"";
cout << endl << "Output file: \"" << outputFilename << "\"";
cout << endl << "Using " << sqliteCacheSizeMiBPerThread << " MiB cache, " << sqliteMMAPSizeMiBPerThread << " MiB MMAP (" << ((sqliteCacheSizeMiBPerThread + sqliteMMAPSizeMiBPerThread) << 2) << " MiB total peak RAM)";
unique_ptr<unsigned char[]> fileCopyBufferUniquePtr = make_unique<unsigned char[]>(FILE_COPY_BUFFER_SIZE);
unique_ptr<unsigned char[]> coordinatesByteArrayTmpUniquePtr = make_unique<unsigned char[]>(1048576);
unique_ptr<unsigned char[]> typesByteArrayTmpUniquePtr = make_unique<unsigned char[]>(1048576);
unique_ptr<unsigned char[]> additionalTypesByteArrayTmpUniquePtr = make_unique<unsigned char[]>(1048576);
unique_ptr<unsigned char[]> stringNamesByteArrayTmpUniquePtr = make_unique<unsigned char[]>(1048576);
fileCopyBuffer = fileCopyBufferUniquePtr.get();
databaseFilename = inputFilename;
int rc = sqlite3_open_v2(inputFilename.c_str(), &db, SQLITE_OPEN_READONLY | SQLITE_OPEN_NOMUTEX, NULL);
if (rc != SQLITE_OK) {
cout << endl << "Error opening database";
sqlite3_close(db);
return;
}
//Get the overall bounding rectangle
uint64_t boundingRectangleStartTime;
double boundingRectangleTime;
boundingRectangleStartTime = GetSystemTimeAsUnixTime();
string query = "select min(min_lon) as \"left\", min(min_lat) as bottom, max(max_lon) as \"right\", max(max_lat) as top from rtree_node;";
rc = sqlite3_prepare_v2(db, query.c_str(), -1, &res, 0);
if (rc != SQLITE_OK) {
cout << endl << "Error while creating the overall bounding box prepared statement";
return;
}
if (sqlite3_step(res) == SQLITE_ROW) {
overallBoundingRectangle.left = sqlite3_column_double(res, 0);
overallBoundingRectangle.bottom = sqlite3_column_double(res, 1);
overallBoundingRectangle.right = sqlite3_column_double(res, 2);
overallBoundingRectangle.top = sqlite3_column_double(res, 3);
overallBoundingRectangle.calculateInt32ValuesFromDouble();
} else {
cout << endl << "Could not get the overall bounding rectangle";
return;
}
sqlite3_finalize(res);
boundingRectangleTime = (GetSystemTimeAsUnixTime() - boundingRectangleStartTime) / 1000.0;
if (verbose) cout << endl << setprecision(12) << "Overall bounding rectangle: " << overallBoundingRectangle.left << ", " << overallBoundingRectangle.top << ", " << overallBoundingRectangle.right << ", " << overallBoundingRectangle.bottom << " (" << boundingRectangleTime << " second" << (boundingRectangleTime == 1 ? "" : "s") << ")";
if (verbose) cout << endl << "(left, right, top, bottom) " << overallBoundingRectangle.leftInt32 << ", " << overallBoundingRectangle.rightInt32 << ", " << overallBoundingRectangle.topInt32 << ", " << overallBoundingRectangle.bottomInt32;
if (verbose) cout << endl << "Bounding rectangle size(int32): width=" << (overallBoundingRectangle.rightInt32 - overallBoundingRectangle.leftInt32) << ", height=" << (overallBoundingRectangle.bottomInt32 - overallBoundingRectangle.topInt32);
//TODO: split the map based on the int32 width and height
ofstream output(outputFilename, ios::binary);
google::protobuf::io::OstreamOutputStream ostream_output(&output);
google::protobuf::io::CodedOutputStream cos(&ostream_output);
//Version 2
cos.WriteTag(OsmAnd::OBF::OsmAndStructure::kVersionFieldNumber << 3);
cos.WriteVarint32(2);
//Creation time (Unix milliseconds)
cos.WriteTag(OsmAnd::OBF::OsmAndStructure::kDateCreatedFieldNumber << 3);
cos.WriteVarint64(GetSystemTimeAsUnixTime());
cos.WriteTag((OsmAnd::OBF::OsmAndStructure::kMapIndexFieldNumber << 3) | 6);
//Save the MapIndex to a temp file but don't write it to the OBF file yet
uint64_t mapIndexSize = 0;
writeMapIndex(inputFilePath.stem().string());
mapIndexSize = getFileSize(string("mapIndex_" + to_string(pid)));
currentDiskUsage += mapIndexSize;
//cout << endl << "mapIndex temp file size: " << mapIndexSize;
writeOBFVarint32or64BE(cos, mapIndexSize);
copyRawFileIntoCodedOutputStream(cos, "mapIndex_" + to_string(pid), mapIndexSize);
if (!shouldKeepTempFiles) remove(string("mapIndex_" + to_string(pid)).c_str());
currentDiskUsage = -mapIndexSize;
//Version 2
//cout << endl << "About to write versionConfirm";
cos.WriteTag(OsmAnd::OBF::OsmAndStructure::kVersionConfirmFieldNumber << 3);
cos.WriteVarint32(2);
//sqlite3_finalize(res);
sqlite3_close(db);
/*int tmp;
cout << endl << endl << "Enter a number to exit";
cin >> tmp;*/
uint64_t overallEndTime = GetSystemTimeAsUnixTime();
double finishedSeconds = (overallEndTime - overallStartTime) / 1000.0;
cout << endl << "Finished in " << (finishedSeconds < 10 ? to_string(finishedSeconds) + " seconds" : humanReadableTimeFromSeconds(finishedSeconds));
}
void calculateTotalRectanglesForGUI() {
unsigned int totalRectangles = 0;
wstring text = L"";
switch (guiSelectedQuadtreeSplit) {
case 0: //2-level quadtree
{
totalRectangles = 16;
}
break;
case 1: //3-level quadtree
{
totalRectangles = 64;
}
break;
}
#if defined(_WIN32)
if (guiSelectedSplitWithinQuadtree == 0 /* Auto */) {
text = L"At least " + to_wstring((unsigned long)totalRectangles) + L" data blocks";
} else {
/*switch (guiSelectedSplitWithinQuadtree) {
}*/
totalRectangles *= ((1 << (guiSelectedSplitWithinQuadtree - 1)) * (1 << (guiSelectedSplitWithinQuadtree - 1)));
text = to_wstring((unsigned long)totalRectangles) + L" data blocks";
}
SetWindowText(hwndRectangleCountLabel, text.c_str());
#elif defined(__linux__)
#endif
}
#if defined(_WIN32)
LRESULT CALLBACK WndProc(HWND hwndMainWin, UINT msg, WPARAM wParam, LPARAM lParam) {
RECT windowRect;
int width, height;
HDC hdc;
HWND hctrlWnd;
PAINTSTRUCT ps;
HPEN h_LightGray_Pen, hOldPen;
HGDIOBJ originalGDIObj;
BITMAP bmp;
HDC bmpHDC;
LPMINMAXINFO lpMMI;
//Making these static prevents odd drawing errors in WM_PAINT
static int statusBarParts[4] = { 0, 0, 0, 0 };
switch (msg) {
case WM_CREATE:
{
//Apply the correct (non-bold) font to all the UI elements
EnumChildWindows(hwndMainWin, (WNDENUMPROC)SetFont, (LPARAM)GetStockObject(DEFAULT_GUI_FONT));
//Set the default cursor
SetCursor(LoadCursor(0, IDC_ARROW));
}
break;
case WM_PAINT:
{
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwndMainWin, &ps);
RECT windowRect;
HGDIOBJ hOldPen;
HGDIOBJ hOldBrush;
unsigned int progressAreaWidth, progressAreaHeight;
GetWindowRect(hwndMainWin, &windowRect);
progressAreaWidth = (windowRect.right - windowRect.left) - 28;
progressAreaHeight = (windowRect.bottom - windowRect.top) - 250;
if (progressBitmapWidth > 0 && progressBitmapHeight > 0) {
SetStretchBltMode(hdc, COLORONCOLOR);
HDC progressImageHDC = CreateCompatibleDC(hdc);
BITMAP bm;
bm.bmType = 0;
bm.bmWidth = progressBitmapWidth;
bm.bmHeight = progressBitmapHeight;
bm.bmWidthBytes = progressBitmapWidth * 4;
bm.bmPlanes = 1;
bm.bmBitsPixel = 32;
bm.bmBits = progressBitmapPtr;
HBITMAP progressBitmap = CreateBitmapIndirect(&bm);
SelectObject(progressImageHDC, progressBitmap);
StretchBlt(hdc, 12, 12, progressAreaWidth - 12, progressAreaHeight - 12, progressImageHDC, 0, 0, progressBitmapWidth, progressBitmapHeight, SRCCOPY);
DeleteObject(progressBitmap);
DeleteDC(progressImageHDC);
} else {
HBRUSH hBrush = CreateSolidBrush(RGB(255, 255, 255));
hOldPen = SelectObject(hdc, GetStockObject(NULL_PEN));
hOldBrush = SelectObject(hdc, hBrush);
Rectangle(hdc, 12, 12, progressAreaWidth + 1, progressAreaHeight + 1);
SelectObject(hdc, hOldPen);
SelectObject(hdc, hOldBrush);
DeleteObject(hBrush);
}
//Draw the 3D edge
MoveToEx(hdc, 10, 10, NULL);
HPEN lightGrayOuterBorderColor = CreatePen(PS_SOLID, 1, RGB(208, 208, 208));
HPEN lightGrayMiddleBorderColor = CreatePen(PS_SOLID, 1, RGB(128, 128, 128));
HPEN darkGrayInnerBorderColor = CreatePen(PS_SOLID, 1, RGB(64, 64, 64));
hOldPen = SelectObject(hdc, lightGrayOuterBorderColor);
hOldBrush = SelectObject(hdc, GetStockObject(NULL_BRUSH));
Rectangle(hdc, 10, 10, progressAreaWidth + 2, progressAreaHeight + 2);
SelectObject(hdc, lightGrayMiddleBorderColor);
MoveToEx(hdc, 11, 11, NULL);
LineTo(hdc, progressAreaWidth, 11);
SelectObject(hdc, darkGrayInnerBorderColor);
MoveToEx(hdc, 12, 12, NULL);
LineTo(hdc, progressAreaWidth - 1, 12);
MoveToEx(hdc, 10, 11, NULL);
SelectObject(hdc, lightGrayOuterBorderColor);
SelectObject(hdc, lightGrayMiddleBorderColor);
MoveToEx(hdc, 11, 12, NULL);
LineTo(hdc, 11, progressAreaHeight);
MoveToEx(hdc, 12, 13, NULL);
SelectObject(hdc, darkGrayInnerBorderColor);
LineTo(hdc, 12, progressAreaHeight - 1);
MoveToEx(hdc, 12, progressAreaHeight - 1, NULL);
SelectObject(hdc, lightGrayOuterBorderColor);
LineTo(hdc, progressAreaWidth, progressAreaHeight - 1);
MoveToEx(hdc, progressAreaWidth - 1, 12, NULL);
SelectObject(hdc, lightGrayOuterBorderColor);
LineTo(hdc, progressAreaWidth - 1, progressAreaHeight);
MoveToEx(hdc, 11, progressAreaHeight, NULL);
SelectObject(hdc, GetStockObject(WHITE_PEN));
LineTo(hdc, progressAreaWidth - 1, progressAreaHeight);
SelectObject(hdc, hOldBrush);
SelectObject(hdc, hOldPen);
DeleteObject(lightGrayOuterBorderColor);
DeleteObject(lightGrayMiddleBorderColor);
DeleteObject(darkGrayInnerBorderColor);
EndPaint(hwndMainWin, &ps);
}
}
break;
case WM_SIZE:
{
RECT windowRect;
unsigned int windowWidth, windowHeight;
GetWindowRect(hwndMainWin, &windowRect);
windowWidth = windowRect.right - windowRect.left;
windowHeight = windowRect.bottom - windowRect.top;
MoveWindow(hwndStartBtn, (windowWidth - 150), (windowHeight - 88), 120, 25, TRUE);
MoveWindow(hwndInputFilenameLabel, 12, (windowHeight - 220), 200, 20, TRUE);
MoveWindow(hwndOutputFilenameLabel, 12, (windowHeight - 190), 200, 20, TRUE);
MoveWindow(hwndInputFilenameField, 100, (windowHeight - 220), 390, 20, TRUE);
MoveWindow(hwndOutputFilenameField, 100, (windowHeight - 192), 390, 20, TRUE);
MoveWindow(hwndSplitLabel, 12, (windowHeight - 160), 150, 20, TRUE);
MoveWindow(hwndQuadtreeCombobox, 100, (windowHeight - 162), 140, 20, TRUE);
MoveWindow(hwndSplitCombobox, 250, (windowHeight - 162), 240, 20, TRUE);
MoveWindow(hwndRectangleCountLabel, 500, (windowHeight - 160), 200, 20, TRUE);
MoveWindow(hwndDetailedVectorMapProgressLabel, 12, (windowHeight - 130), 85, 20, TRUE);
MoveWindow(hwndDetailedVectorMapProgressBar, 100, (windowHeight - 132), 390, 20, TRUE);
MoveWindow(hwndProgressPercentLabel, 500, (windowHeight - 130), 80, 20, TRUE);
MoveWindow(hwndInputFilenameBrowseButton, 500, (windowHeight - 220), 80, 20, TRUE);
MoveWindow(hwndOutputFilenameBrowseButton, 500, (windowHeight - 192), 80, 20, TRUE);
InvalidateRect(hwndMainWin, NULL, TRUE);
UpdateWindow(hwndMainWin);
}
break;
case WM_COMMAND:
{
if (HIWORD(wParam) == BN_CLICKED) {
switch (LOWORD(wParam)) {
case ID_STARTBTN:
{
WCHAR buffer[MAX_PATH];
GetWindowText(hwndInputFilenameField, buffer, MAX_PATH);
inputFilename = wstring_to_utf8(wstring(buffer));
GetWindowText(hwndOutputFilenameField, buffer, MAX_PATH);
outputFilename = wstring_to_utf8(wstring(buffer));
thread(createOBFFile, nullptr);
}
break;
case ID_BROWSE_INPUT_FILE:
{
OPENFILENAME ofn;
TCHAR szFileName[MAX_PATH] = L"";
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hwndMainWin;
ofn.lpstrFilter = L"SQLite Database Files (*.db)\0*.db\0All Files (*.*)\0*.*\0";
ofn.lpstrFile = szFileName;
ofn.nMaxFile = MAX_PATH;
ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
ofn.lpstrDefExt = L"db";
if (GetOpenFileName(&ofn)) SetWindowText(hwndInputFilenameField, szFileName);
if (GetWindowTextLength(hwndOutputFilenameField) == 0) {
filesystem::path outputFilenamePath = wstring(szFileName);
outputFilenamePath = outputFilenamePath.parent_path() / outputFilenamePath.stem();
outputFilename = outputFilenamePath.string() + ".obf";
SetWindowText(hwndOutputFilenameField, utf8_to_wstring(outputFilename).c_str());
}
}
break;
case ID_BROWSE_OUTPUT_FILE:
{
OPENFILENAME ofn;
TCHAR szFileName[MAX_PATH] = L"";
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hwndMainWin;
ofn.lpstrFilter = L"OsmAnd OBF Files (*.obf)\0*.obf\0All Files (*.*)\0*.*\0";
ofn.lpstrFile = szFileName;
ofn.nMaxFile = MAX_PATH;
ofn.Flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT;
ofn.lpstrDefExt = L"obf";
if (GetSaveFileName(&ofn)) SetWindowText(hwndOutputFilenameField, szFileName);
}
break;
}
}
if (LOWORD(wParam) == ID_QUADTREE_COMBOBOX) {
guiSelectedQuadtreeSplit = SendMessage(hwndQuadtreeCombobox, CB_GETCURSEL, 0, 0);
calculateTotalRectanglesForGUI();
} else if (LOWORD(wParam) == ID_SPLIT_COMBOBOX) {
guiSelectedSplitWithinQuadtree = SendMessage(hwndSplitCombobox, CB_GETCURSEL, 0, 0);
calculateTotalRectanglesForGUI();
}
}
break;
case WM_USER_REDRAW:
{
SendMessage(hwndDetailedVectorMapProgressBar, PBM_SETPOS, (WPARAM)((unsigned int)((progressCompletedRectangles * 65535) / progressTotalRectangles)), 0);
ostringstream percentStream;
percentStream << fixed << setprecision(3) << ((progressCompletedRectangles * 100.0) / progressTotalRectangles);
wstring percentString = utf8_to_wstring(percentStream.str());
percentString += L"%";
SendMessage(hwndProgressPercentLabel, WM_SETTEXT, 0, (LPARAM)percentString.c_str());
InvalidateRect(hwndMainWin, NULL, TRUE);
UpdateWindow(hwndMainWin);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
}
return DefWindowProc(hwndMainWin, msg, wParam, lParam);
}
bool CALLBACK SetFont(HWND child, LPARAM font) {
SendMessage(child, WM_SETFONT, font, true);
return true;
}
#endif
void printHelp() {
cout << "OsmAndMapCreator++ version 0.1.12";
cout << endl << endl << "This utility generates OBF map files for OsmAnd from an OpenStreetMap SQLite database";
cout << endl << endl << "Usage:";
cout << endl << "\t-i [path]\t\t\t\tInput filename (required)";
cout << endl << "\t-o [path]\t\t\t\tOutput filename";
cout << endl << "\t--keep-temp-files\t\t\tPreserve temp files for debugging (disabled by default)";
//cout << endl << "\t--force-single-split [integer]\t\tForce a single power-of-2 split (for example, 2 would be 4x4)";
cout << endl << "\t--force-quadtree2-split [integer]\tForce a 2-level quadtree split with a power-of-2 split in each section (for example, 2 would be 4:4:4x4). Takes precedence when combined with --force-single-split";
cout << endl << "\t--force-quadtree3-split [integer]\tForce a 3-level quadtree split with a power-of-2 split in each section (for example, 2 would be 4:4:4:4x4). Takes precedence when combined with --force-quadtree2-split or --force-single-split";
cout << endl << "\t--no-gui\t\t\t\tOnly show the command-line window";
cout << endl << "\t--verbose\t\t\t\tPrint debug messages";
cout << endl << "\t--cache-size\t\t\t\tSQLite per-thread cache size in MiB (default 64)";
cout << endl << "\t--mmap-size\t\t\t\tSQLite per-thread memory-mapped file size in MiB (default 64)";
cout << endl << "\t-h\t\t\t\t\tPrint this message";
}
uint64_t writeMapIndex(string name) {
//Create a temp file for the MapIndex
ofstream mapIndexTemp("mapIndex_" + to_string(pid), ios::binary);
google::protobuf::io::OstreamOutputStream mapIndexTempOstream(&mapIndexTemp);
google::protobuf::io::CodedOutputStream mapIndexCos(&mapIndexTempOstream);
uint64_t mapIndexSize = 0;
//MapIndex.name
mapIndexCos.WriteTag((OsmAnd::OBF::OsmAndMapIndex::kNameFieldNumber << 3) | 2);
//string mapIndexName = "OsmAndMapCreator++ test";
mapIndexCos.WriteVarint32(name.length());
mapIndexCos.WriteString(name);
//MapIndex.rules
//mapIndexCos.WriteTag((OsmAnd::OBF::OsmAndMapIndex::kRulesFieldNumber << 3) | 2); //" | 2" is the wire type
writeOsmAndStructure_mapIndex_rules(mapIndexCos);
//MapIndex.levels
mapIndexCos.WriteTag((OsmAnd::OBF::OsmAndMapIndex::kLevelsFieldNumber << 3) | 6);
unsigned int powerOf2Split = 1; //Start with 2x2 by default
//Eventually we should set this automatically if the user didn't force a split option
unsigned int multiplierForBlockSizeDivider = 16;
if (forceSplitMode == 1 /* 2-level quadtree */) {
multiplierForBlockSizeDivider = 16;
} else if (forceSplitMode == 2 /* 3-level quadtree */) {
multiplierForBlockSizeDivider = 8;
}
if (forceSplitMode >= 0) {
powerOf2Split = forcedSplitPowerOf2;
} else {
//Automatically find a good split value
powerOf2Split = getClosestNextLowerPowerOf2(max(overallBoundingRectangle.widthInt32 / (IDEAL_BLOCK_MAX_SIZE * multiplierForBlockSizeDivider), overallBoundingRectangle.heightInt32 / (IDEAL_BLOCK_MAX_SIZE * multiplierForBlockSizeDivider))); //Default to a bigger split (fewer blocks)
#if defined(_WIN32)
SendMessage(hwndSplitCombobox, CB_SETCURSEL, (WPARAM)(powerOf2Split + 1), 0);
#endif
guiSelectedSplitWithinQuadtree = powerOf2Split + 1;
calculateTotalRectanglesForGUI();
}
if (forceSplitMode == -1 || forceSplitMode == 0 /* automatic or single split */) {
//writeOsmAndStructure_mapIndex_detailed_level_single_power_of_2_split(powerOf2Split, false /* detailed zoom */);
writeOsmAndStructure_mapIndex_detailed_level_4_4_4_pow2_split(powerOf2Split, false /* detailed zoom */);
} else if (forceSplitMode == 1 /* 2-level quadtree */) {
writeOsmAndStructure_mapIndex_detailed_level_4_4_pow2_split(powerOf2Split, false /* detailed zoom */);
} else if (forceSplitMode == 2 /* 3-level quadtree */) {
writeOsmAndStructure_mapIndex_detailed_level_4_4_4_pow2_split(powerOf2Split, false /* detailed zoom */);
}
int64_t mapRootLevelSize = getFileSize(string("mapRootLevel_" + to_string(pid)));
writeOBFVarint32or64BE(mapIndexCos, mapRootLevelSize);
//cout << endl << "mapRootLevel size = " << mapRootLevelSize;
copyRawFileIntoCodedOutputStream(mapIndexCos, "mapRootLevel_" + to_string(pid), mapRootLevelSize);
if (!shouldKeepTempFiles) remove(string("mapRootLevel_" + to_string(pid)).c_str());
mapIndexCos.WriteTag((OsmAnd::OBF::OsmAndMapIndex::kLevelsFieldNumber << 3) | 6);
if (powerOf2Split >= 4) {
powerOf2Split -= 3;
} else if (powerOf2Split >= 3) {
powerOf2Split -= 2;
}
if (forceSplitMode == -1 || forceSplitMode == 0 /* automatic or single split */) {
//writeOsmAndStructure_mapIndex_detailed_level_single_power_of_2_split(powerOf2Split, true /* detailed zoom */);
writeOsmAndStructure_mapIndex_detailed_level_4_4_4_pow2_split(powerOf2Split, true /* detailed zoom */);
} else if (forceSplitMode == 1 /* 2-level quadtree */) {
writeOsmAndStructure_mapIndex_detailed_level_4_4_pow2_split(powerOf2Split, true /* detailed zoom */);
} else if (forceSplitMode == 2 /* 3-level quadtree */) {
writeOsmAndStructure_mapIndex_detailed_level_4_4_4_pow2_split(powerOf2Split, true /* detailed zoom */);
}
mapRootLevelSize = getFileSize(string("mapRootLevel_" + to_string(pid)));
writeOBFVarint32or64BE(mapIndexCos, mapRootLevelSize);
//cout << endl << "mapRootLevel size = " << mapRootLevelSize;
copyRawFileIntoCodedOutputStream(mapIndexCos, "mapRootLevel_" + to_string(pid), mapRootLevelSize);
if (!shouldKeepTempFiles) remove(string("mapRootLevel_" + to_string(pid)).c_str());
return 0;
}
void writeOsmAndStructure_mapIndex_rules(google::protobuf::io::CodedOutputStream &cos) {
string getKeysAndValuesQuery = GET_KEYS_AND_VALUES_SORTED_QUERY;
getKeysAndValuesQuery.replace(getKeysAndValuesQuery.find("%HUMAN_READABLE_WHITELIST%"), 26, TAG_KEYS_HUMAN_READABLE_WHITELIST);
getKeysAndValuesQuery.replace(getKeysAndValuesQuery.find("%MACHINE_READABLE_BLACKLIST%"), 28, TAG_KEYS_BLACKLIST);
getKeysAndValuesQuery.replace(getKeysAndValuesQuery.find("%MACHINE_READABLE_BLACKLIST%"), 28, TAG_KEYS_BLACKLIST);
int rc = sqlite3_prepare_v2(db, getKeysAndValuesQuery.c_str(), -1, &res, 0);
uint64_t i = 2; //Reserve indices 0 and 1 for object_type=node and osmand_highway_integrity
uint64_t rowCount = 0;
uint64_t mapEncodingRuleSize = 0;
OsmAnd::OBF::OsmAndMapIndex::MapEncodingRule r;
string key, value;
value = "";
bool machineReadable = false;
keyMap.emplace("object_type=node", 0);
keyMap.emplace("osmand_highway_integrity=4", 1);
r.Clear();
r.set_tag("object_type");
r.set_value("node");
r.set_minzoom(5);
r.set_type(1);
cos.WriteTag((OsmAnd::OBF::OsmAndMapIndex::kRulesFieldNumber << 3) | 2);
cos.WriteVarint32(r.ByteSizeLong());
r.SerializeToCodedStream(&cos);
r.Clear();
r.set_tag("osmand_highway_integrity");
r.set_value("4");
r.set_minzoom(5);
r.set_type(1);
cos.WriteTag((OsmAnd::OBF::OsmAndMapIndex::kRulesFieldNumber << 3) | 2);
cos.WriteVarint32(r.ByteSizeLong());
r.SerializeToCodedStream(&cos);
while ((rc = sqlite3_step(res)) == SQLITE_ROW) {
if (i == 2) {
rowCount = sqlite3_column_int64(res, 4);
keyMap.reserve(rowCount);
if (verbose) cout << endl << "Found " << rowCount << " unique key/value pair" << (rowCount == 1 ? "" : "s");
}
//These are tiny so we can generate them in memory instead of in a file
r.Clear();
key = string((char*)sqlite3_column_text(res, 0));
value = string((char*)sqlite3_column_text(res, 1));
machineReadable = sqlite3_column_int64(res, 2) == 0;
if (machineReadable) {
keyMap.emplace(key + "=" + value, i);
if (!value.empty()) r.set_value(value);
//cout << endl << "Added machine-readable tag " << key << "=" << value;
} else {
if (keyMap.find(key + "=") == keyMap.end()) {
keyMap.emplace(key + "=", i);
} else {
continue; //Don't duplicate the human-readable keys like writing name= for every instance of the "name" tag
//TODO: do this in SQL
}
//cout << endl << "Added human-readable key " << key << "=";
}
r.set_tag(key);
r.set_minzoom(5);
cos.WriteTag((OsmAnd::OBF::OsmAndMapIndex::kRulesFieldNumber << 3) | 2);
cos.WriteVarint32(r.ByteSizeLong());
r.SerializeToCodedStream(&cos);
i++;
}
sqlite3_finalize(res);
}
//OsmAndMapIndex.MapRootLevel
void writeOsmAndStructure_mapIndex_detailed_level_1x1(unsigned char *coordinatesByteArrayPtrWithinThread, unsigned char *typesByteArrayPtrWithinThread, unsigned char *additionalTypesByteArrayPtrWithinThread, unsigned char *stringNamesByteArrayPtrWithinThread) {
remove(string("mapRootLevel_" + to_string(pid)).c_str());
ofstream mapRootLevelTemp("mapRootLevel_" + to_string(pid), ios::binary);
google::protobuf::io::OstreamOutputStream mapRootLevelTempOstream(&mapRootLevelTemp);
google::protobuf::io::CodedOutputStream mapRootLevelTempCos(&mapRootLevelTempOstream);
mapRootLevelTempCos.WriteTag((OsmAnd::OBF::OsmAndMapIndex::MapRootLevel::kMaxZoomFieldNumber << 3));
mapRootLevelTempCos.WriteVarint32(22);
mapRootLevelTempCos.WriteTag((OsmAnd::OBF::OsmAndMapIndex::MapRootLevel::kMinZoomFieldNumber << 3));
mapRootLevelTempCos.WriteVarint32(15);
mapRootLevelTempCos.WriteTag((OsmAnd::OBF::OsmAndMapIndex::MapRootLevel::kLeftFieldNumber << 3));
mapRootLevelTempCos.WriteVarint32(overallBoundingRectangle.leftInt32);
mapRootLevelTempCos.WriteTag((OsmAnd::OBF::OsmAndMapIndex::MapRootLevel::kRightFieldNumber << 3));
mapRootLevelTempCos.WriteVarint32(overallBoundingRectangle.rightInt32);
mapRootLevelTempCos.WriteTag((OsmAnd::OBF::OsmAndMapIndex::MapRootLevel::kTopFieldNumber << 3));
mapRootLevelTempCos.WriteVarint32(overallBoundingRectangle.topInt32);
mapRootLevelTempCos.WriteTag((OsmAnd::OBF::OsmAndMapIndex::MapRootLevel::kBottomFieldNumber << 3));
mapRootLevelTempCos.WriteVarint32(overallBoundingRectangle.bottomInt32);
//MapRootLevel.boxes
//For some reason, the box has to be built in an EXACT way that includes shiftToMapData with a wiretype of 6
mapRootLevelTempCos.WriteTag((OsmAnd::OBF::OsmAndMapIndex::MapRootLevel::kBoxesFieldNumber << 3) | 6);
uint32_t boxSize = 0;
boxSize += 4;
boxSize++;
boxSize += getVarintRequiredBytes(0);
boxSize++;
boxSize += getVarintRequiredBytes(0);
boxSize++;
boxSize += getVarintRequiredBytes(0);
boxSize++;
boxSize += getVarintRequiredBytes(0);
boxSize++;
boxSize = swap_endian(boxSize);
mapRootLevelTempCos.WriteRaw(&boxSize, 4);
boxSize = swap_endian(boxSize);
mapRootLevelTempCos.WriteTag(OsmAnd::OBF::OsmAndMapIndex::MapDataBox::kLeftFieldNumber << 3);
mapRootLevelTempCos.WriteVarint32(0);