-
Notifications
You must be signed in to change notification settings - Fork 1
/
tilesGenExcl.pl
executable file
·1723 lines (1454 loc) · 60.4 KB
/
tilesGenExcl.pl
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
#!/usr/bin/perl
use lib '.';
use LWP::Simple;
use LWP::UserAgent;
use Math::Trig;
use File::Copy;
use Digest::MD5 qw(md5_hex);
use File::Temp qw(tempfile);
use FindBin qw($Bin);
use tahconfig;
use tahlib;
use English '-no_match_vars';
use GD qw(:DEFAULT :cmp);
use strict;
use POSIX qw(locale_h);
#-----------------------------------------------------------------------------
# OpenStreetMap tiles@home
#
# Contact OJW on the Openstreetmap wiki for help using this program
#-----------------------------------------------------------------------------
# Copyright 2006, Oliver White, Etienne Cherdlu, Dirk-Lueder Kreie,
# Sebastian Spaeth and others
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#-----------------------------------------------------------------------------
# Read the config file
my %Config = ReadConfig(
"general.conf", "authentication.conf",
"layers.conf", "freemapdisk.conf",
"freemapdiskclient.conf",
);
$Config{"LowZoom"} = 0 unless defined( $Config{"LowZoom"} );
# detect the current system locale: comma (,) => SK, dot (.) => EN
my ($decimalSep) = @{localeconv()}{"mon_decimal_point"};
printf STDERR "-- Running as PID: %d\n", $PID;
my %EnvironmentInfo = CheckConfig(%Config);
# Get version number from version-control system, as integer
my $Version = '$Revision: 5175 $';
my $VerifyHash;
$Version =~ s/\$Revision:\s*(\d+)\s*\$/$1/;
printf STDERR "This is version %d (%s) of tilesgen running on %s\n", $Version,
$Config{ClientVersion}, $^O;
# check GD
eval GD::Image->trueColor(1);
if ( $@ ne '' ) {
print STDERR "please update your libgd to version 2 for TrueColor support";
cleanUpAndDie( "init:libGD check failed, exiting", "EXIT", 4, $PID );
}
# Setup GD options
# currently unused (GD 2 truecolor mode)
#
# my $numcolors = 256; # 256 is maximum for paletted output and should be used
# my $dither = 0; # dithering on or off.
#
# dithering off should try to find a good palette, looks ugly on
# neighboring tiles with different map features as the "optimal"
# palette is chosen differently for different tiles.
# create a comparison blank image
my $EmptyTransparentImage = newFromPng GD::Image("temptycheck.png");
$EmptyTransparentImage->saveAlpha(1);
my $EmptyLandImage = new GD::Image( 256, 256 );
my $MapLandBackground = $EmptyLandImage->colorAllocate( 248, 248, 248 );
$EmptyLandImage->fill( 127, 127, $MapLandBackground );
my $EmptySeaImage = new GD::Image( 256, 256 );
my $MapSeaBackground = $EmptySeaImage->colorAllocate( 181, 214, 241 );
$EmptySeaImage->fill( 127, 127, $MapSeaBackground );
# Some broken versions of Inkscape occasionally produce totally black
# output. We detect this case and throw an error when that happens.
my $BlackTileImage = new GD::Image( 256, 256 );
my $BlackTileBackground = $BlackTileImage->colorAllocate( 0, 0, 0 );
$BlackTileImage->fill( 127, 127, $BlackTileBackground );
# set the progress indicator variables
my $currentSubTask;
my $progress = 0;
my $progressJobs = 0;
my $progressPercent = 0;
my $CurrentPerformance = 0;
# Check the on disk image tiles havn't been corrupted
if ( -s "emptyland.png" != 67 ) {
print STDERR
"Corruption detected in emptyland.png. Trying to redownload from svn automatically.\n";
statusMessage( "Downloading: emptyland.png",
$Config{Verbose}, $currentSubTask, $progressJobs, $progressPercent, 0 );
DownloadFile(
"http://svn.openstreetmap.org/applications/rendering/tilesAtHome/emptyland.png"
, # TODO: should be svn update, instead of http get...
"emptyland.png",
0
); ## 0=delete old file from disk first
}
if ( -s "emptysea.png" != 69 ) {
print STDERR
"Corruption detected in emptysea.png. Trying to redownload from svn automatically.\n";
statusMessage( "Downloading: emptysea.png",
$Config{Verbose}, $currentSubTask, $progressJobs, $progressPercent, 0 );
DownloadFile(
"http://svn.openstreetmap.org/applications/rendering/tilesAtHome/emptysea.png"
, # TODO: should be svn update, instead of http get...
"emptysea.png",
0
); ## 0=delete old file from disk first
}
# Check the on disk image tiles are now in order
if ( -s "emptyland.png" != 67
or -s "emptysea.png" != 69 )
{
print STDERR "\nAutomatic fix failed. Exiting.\n";
cleanUpAndDie( "init.emptytile_template_check", "EXIT", 4, $PID );
}
# Setup map projection
my $LimitY = ProjectF(85.0511);
my $LimitY2 = ProjectF(-85.0511);
my $RangeY = $LimitY - $LimitY2;
# Create the working directory if necessary
mkdir $Config{WorkingDirectory} if ( !-d $Config{WorkingDirectory} );
# Subdirectory for the current job (layer & z12 tileset),
# as used in sub GenerateTileset() and tileFilename()
my $JobDirectory;
# keep track of time running
my $progstart = time();
my $dirent;
# keep track of the server time for current job
my $JobTime;
# Handle the command-line
my $Mode = shift();
our $ConfigName;
# list of tiles excluded from the rendering
my $exclTilesReload = "./excludedtiles.reload";
my $exclTilesFilename = "excludedtiles.dat";
my %excludedTiles = ReadExcludedTilesList($exclTilesFilename);
my $excludedInRow = 0; # number of tiles excluded in a row
if ( $Mode eq "config" ) {
$ConfigName = shift();
if ( not defined $ConfigName ) {
die "Must specify config file name \n";
}
AppendConfig ($ConfigName);
# precitam dalsi prikaz
$Mode = shift();
}
if ( $Mode eq "xy" ) {
# ----------------------------------
# "xy" as first argument means you want to specify a tileset to render
# ----------------------------------
my $X = shift();
my $Y = shift();
if ( not defined $X or not defined $Y ) {
die "Must specify tile coordinates\n";
}
my $Zoom = shift() || 12;
GenerateTileset( $X, $Y, $Zoom );
}
elsif ( $Mode eq "loop" ) {
# create PID file... loop until PID file exists
if ( open( FAILFILE, ">", "./$PID.pid" ) ) {
print FAILFILE $PID;
close FAILFILE;
}
# ----------------------------------
# Continuously process requests from server
# ----------------------------------
# if this is a re-exec, we want to capture some of our status
# information from the command line. this feature allows setting
# any numeric variable by specifying "variablename=value" on the
# command line after the keyword "reexec". Currently unsuitable
# for alphanumeric variables.
if ( shift() eq "reexec" ) {
my $idleSeconds;
my $idleFor;
while ( my $evalstr = shift() ) {
die unless $evalstr =~ /^[A-Za-z]+=\d+/;
eval( '$' . $evalstr );
print STDERR "$evalstr\n" if ( $Config{Verbose} );
}
setIdle( $idleSeconds, 1 );
setIdle( $idleFor, 0 );
}
# this is the actual processing loop
while ( -e "./$PID.pid" ) {
reExecIfRequired();
if ( -e "$exclTilesReload" ) { # reload the list of excluded files
%excludedTiles = ReadExcludedTilesList($exclTilesFilename);
killafile($exclTilesReload);
}
my ( $did_something, $message ) = ProcessRequestsFromServer();
uploadIfEnoughTiles();
if ( $did_something == 0 ) {
talkInSleep( $message, 300 );
}
else {
setIdle( 0, 0 );
}
}
cleanUpAndDie( "endless loop terminated :)", "EXIT", 7, $PID );
}
elsif ( $Mode eq "upload" ) {
upload();
}
elsif ( $Mode eq "upload_conditional" ) {
uploadIfEnoughTiles();
}
elsif ( $Mode eq "version" ) {
exit(1);
}
elsif ( $Mode eq "" ) {
# ----------------------------------
# Normal mode downloads request from server
# ----------------------------------
my ( $did_something, $message ) = ProcessRequestsFromServer();
if ( !$did_something ) {
statusMessage(
"you may safely press Ctrl-C now if you are not running this from a script",
$Config{Verbose},
$currentSubTask,
$progressJobs,
$progressPercent,
1
);
talkInSleep( $message, 60 );
}
statusMessage( "if you want to run this program continuously use loop mode",
$Config{Verbose}, $currentSubTask, $progressJobs, $progressPercent, 1 );
}
else {
# ----------------------------------
# "help" (or any other non understood parameter) as first argument tells how to use the program
# ----------------------------------
my $Bar = "-" x 78;
print "\n$Bar\nOpenStreetMap tiles\@home client\n$Bar\n";
print
"Usage: \nNormal mode:\n \"$0\", will download requests from server\n";
print
"Specific area:\n \"$0 xy <x> <y> [z]\"\n (x and y coordinates of a zoom-12 (default) tile in the slippy-map coordinate system)\n See [[Slippy Map Tilenames]] on wiki.openstreetmap.org for details\nz is optional and can be used for low-zoom tilesets\n";
print "Other modes:\n";
print " $0 loop - runs continuously\n";
print " $0 upload - uploads any tiles\n";
print " $0 upload_conditional - uploads tiles if there are many waiting\n";
print " $0 version - prints out version string and exits\n";
print "\nGNU General Public license, version 2 or later\n$Bar\n";
}
sub uploadIfEnoughTiles {
my $Count = 0;
my $ZipCount = 0;
# compile a list of the "Prefix" values of all configured layers,
# separated by |
my $allowedPrefixes = join( "|",
map( $Config{"Layer.$_.Prefix"}, split( /,/, $Config{"Layers"} ) ) );
if ( opendir( my $dp, $Config{WorkingDirectory} ) ) {
while ( my $File = readdir($dp) ) {
$Count++ if ( $File =~ /($allowedPrefixes)_.*\.png/ );
$Count += 200 if ( $File =~ /($allowedPrefixes)_.*\.dir/ );
}
closedir($dp);
}
else {
mkdir $Config{WorkingDirectory};
}
if ( opendir( my $dp, $Config{WorkingDirectory} . "uploadable" ) ) {
while ( my $File = readdir($dp) ) {
$ZipCount++ if ( $File =~ /\.zip/ );
}
closedir($dp);
}
else {
mkdir $Config{WorkingDirectory} . "uploadable";
}
if ( ( $Count >= 200 ) or ( $ZipCount >= 1 ) ) {
upload();
}
}
sub upload {
## Run upload directly because it uses same messaging as tilesGen.pl,
## no need to hide output at all.
my $UploadScript = "perl $Bin/upload.pl $progressJobs";
if ( defined $ConfigName ) {
$UploadScript = "perl $Bin/upload.pl config $ConfigName $progressJobs";
}
my $retval = system($UploadScript);
return $retval;
}
#-----------------------------------------------------------------------------
# Ask the server what tileset needs rendering next
#-----------------------------------------------------------------------------
sub ProcessRequestsFromServer {
my $LocalFilename = $Config{WorkingDirectory} . "request-" . $PID . ".txt";
if ( $Config{"LocalSlippymap"} ) {
print "Config option LocalSlippymap is set. Downloading requests\n";
print "from the server in this mode would take them from the tiles\@home\n";
print "queue and never upload the results. Program aborted.\n";
cleanUpAndDie( "ProcessRequestFromServer:LocalSlippymap set, exiting",
"EXIT", 1, $PID );
}
# ----------------------------------
# Download the request, and check it
# Note: to find out exactly what this server is telling you,
# add ?help to the end of the URL and view it in a browser.
# It will give you details of other help pages available,
# such as the list of fields that it's sending out in requests
# ----------------------------------
killafile($LocalFilename);
my $RequestUrlString =
$Config{DiSKRequestURL}
. "&Email="
. $Config{DiSKUsername}
. "&ClientVersion="
. $Config{DiSKAPIVersion}
. "&PasswordMD5="
. md5_hex( $Config{DiSKPassword} );
# DEBUG: print "using URL " . $RequestUrlString . "\n";
statusMessage( "Downloading: Request from server",
$Config{Verbose}, $currentSubTask, $progressJobs, $progressPercent, 0 );
DownloadFile( $RequestUrlString, $LocalFilename, 0 );
print($RequestUrlString) if ( $Config{Debug} );
if ( !-f $LocalFilename ) {
return ( 0, "Error reading request from server" );
}
# Read into memory
open( my $fp, "<", $LocalFilename ) || return;
my $Request = <$fp>;
chomp $Request;
close $fp;
print($Request) if ( $Config{Debug} );
# Parse the request
my ( $ValidFlag, $ClientVersion, $X, $Y, $Z, $ModuleName, $VerifyString, $StylesheetVersion ) =
split( /\|/, $Request );
# Check what format the results were in
# If you get this message, please do check for a new version, rather than
# commenting-out the test - it means the field order has changed and this
# program no longer makes sense!
if ( $ClientVersion != $Config{DiSKAPIVersion} ) {
#print STDERR "\n";
#print STDERR "Server is speaking a different version of the protocol to us.\n";
#print STDERR "Check to see whether a new version of this program was released!\n";
#cleanUpAndDie("ProcessRequestFromServer:Request API version mismatch, exiting",
# "EXIT", 1, $PID );
return ( 0, "Server has some difficulties, waiting for a while" );
}
if ( $StylesheetVersion != $Config{StylesheetVersion} ) {
if ( $ValidFlag eq "OK" ) {
PutRequestBackToServer( $X, $Y, $Z, "OldStyleSheets" );
}
print STDERR "\n";
print STDERR "Server has a different version of stylesheets.\n";
print STDERR "You should update your client to render consistent map!\n";
cleanUpAndDie("ProcessRequestFromServer:Stylesheet version mismatch, exiting",
"EXIT", 1, $PID );
## No need to return, we exit the program at this point
}
# First field is always "OK" if the server has actually sent a request
if ( $ValidFlag eq "XX" ) {
return ( 0, "Server has no work for us ($ModuleName)" );
}
elsif ( $ValidFlag ne "OK" ) {
return ( 0, "Server dysfunctional ($ModuleName)" );
}
# Information text to say what's happening
statusMessage( "Got work from the \"$ModuleName\" server module",
$Config{Verbose}, $currentSubTask, $progressJobs, $progressPercent, 0 );
$VerifyHash = $VerifyString;
# DEBUG: print "$VerifyHash\n";
# check, if the tile is excluded from rendering
my $lastExclTime = GetTileExcludedTime( $X, $Y, \%excludedTiles );
if ( $lastExclTime ) {
SetTileExcludedTime( $X, $Y, \%excludedTiles );
print STDERR "\nTile $X,$Y excluded from rendering, returning it back to the server!\n";
PutRequestBackToServer( $X, $Y, $Z, "ManuallyExcluded" );
my $difSec = time() - $lastExclTime;
if ( $difSec < 300 ) { # the same tile was received in last 5 minutes, sleep
talkInSleep( "Tile $X,$Y last excluded $difSec seconds ago, sleeping 15 min." , 900 );
$excludedInRow = 0; # slept for a while, reset counter to avoid additional sleep
return ( 1, "" ); # avoid sleeping next 5 min in caller
}
$excludedInRow++;
if ( $excludedInRow == 3 ) { # too many excluded tiles in a row, sleep
return ( 0, "Excluded 3 tiles in a row, sleeping 5 minutes");
}
return ( 1, "");
}
$excludedInRow = 0;
# Create the tileset requested
GenerateTileset( $X, $Y, $Z );
return ( 1, "" );
}
sub PutRequestBackToServer {
## TODO: will not be called in some libGD abort situations
my ( $X, $Y, $Z, $Cause ) = @_;
## do not do this if called in xy mode!
return if ( $Mode eq "xy" );
my $Prio = $Config{ReRequestPrio};
my $LocalFilename =
$Config{WorkingDirectory} . "requesting-" . $PID . ".txt";
killafile($LocalFilename) if ( !$Config{Debug} ); # maybe not necessary if DownloadFile is called correctly?
my $RequestUrlString = $Config{DiSKReRequestURL} . "&TileX=" . $X . "&TileY=" . $Y . "&Zoom=" .$Z ."&Verify=&Message=" . $Cause;
statusMessage( "Putting Job " . $X . "," . $Y . "@" . $Z . " back to server",
$Config{Verbose}, $currentSubTask, $progressJobs, $progressPercent, 0 );
DownloadFile( $RequestUrlString, $LocalFilename, 0 );
if ( !-f $LocalFilename ) {
return ( 0, "Error reading response from server" );
}
# Read into memory
open( my $fp, "<", $LocalFilename ) || return;
my $Request = <$fp>;
chomp $Request;
close $fp;
## TODO: Check response for "OK" or "Duplicate Entry" (which would be OK, too)
killafile($LocalFilename) if ( !$Config{Debug} ); # don't leave old files laying around
}
#-----------------------------------------------------------------------------
# Render a tile (and all subtiles, down to a certain depth)
#-----------------------------------------------------------------------------
sub GenerateTileset {
my ( $X, $Y, $Zoom ) = @_;
my ( $N, $S ) = Project( $Y, $Zoom );
my ( $W, $E ) = ProjectL( $X, $Zoom );
printf "Source (%s,%s): Lat %1.3f,%1.3f, Long %1.3f,%1.3f\n",
$X, $Y, $N, $S, $W, $E
if ( $Config{"Debug"} );
$progress = 0;
$progressPercent = 0;
$progressJobs++;
$currentSubTask = "jobinit";
my $exist =0;
foreach my $layer ( split( /,/, $Config{Layers} ) ) {
my $FinalDirectory = sprintf(
"%s%s_%d_%d_%d.dir$Config{Slash}",
$Config{WorkingDirectory},
$Config{"Layer.$layer.Prefix"},
$Zoom, $X, $Y
);
$exist++; # assume missing
$exist-- if ( -d $FinalDirectory ); #if exist do not count as missing
}
if ($exist == 0 && $Config{SkipExisting}) {
print ("\nTileSet already prerendered and SkipExisting is ON - skipping\n");
return();
}
my $maxCoords = ( 2**$Zoom - 1 );
statusMessage(
sprintf(
"Doing tileset $X,$Y from Freemap TRAPI",
),
$Config{Verbose},
$currentSubTask,
$progressJobs,
$progressPercent,
1
);
if ( ( $X < 0 )
or ( $X > $maxCoords )
or ( $Y < 0 )
or ( $Y > $maxCoords ) )
{
#maybe do something else here
die("\n Coordinates out of bounds (0..$maxCoords)\n");
}
$currentSubTask = "Preproc";
# Adjust requested area to avoid boundary conditions
my $N1 = $N + ( $N - $S ) * $Config{BorderN};
my $S1 = $S - ( $N - $S ) * $Config{BorderS};
my $E1 = $E + ( $E - $W ) * $Config{BorderE};
my $W1 = $W - ( $E - $W ) * $Config{BorderW};
# TODO: verify the current system cannot handle segments/ways crossing the
# 180/-180 deg meridian and implement proper handling of this case, until
# then use this workaround:
if ( $W1 <= -180 ) {
$W1 = -180; # api apparently can handle -180
}
if ( $E1 > 180 ) {
$E1 = 180;
}
$N = ProjectLat2Merc($N1);
$S = ProjectLat2Merc($S1);
$W = ProjectLon2Merc($W1);
$E = ProjectLon2Merc($E1);
my $bbox = sprintf( "%f,%f,%f,%f", $W1, $S1, $E1, $N1 );
#------------------------------------------------------
# Download data
#------------------------------------------------------
my $DataFile = $Config{WorkingDirectory} . "data-$PID.osm";
killafile($DataFile);
my $URLS;
$URLS = sprintf( "%s/map?bbox=%s&zoom=%d%s", $Config{DiSKDataURL}, $bbox, $Zoom, $Config{DiSKDataURLPostfix} );
printf("%s\n", $URLS ) if ( $Config{Debug} );
my @tempfiles;
push( @tempfiles, $DataFile );
my $filelist = [];
my $i = 0;
foreach my $URL ( split( / /, $URLS ) ) {
++$i;
my $partialFile;
$partialFile = $Config{WorkingDirectory} . "data-$PID-$i.osm";
push( @{$filelist}, $partialFile );
push( @tempfiles, $partialFile );
statusMessage( "Downloading: Map data to $partialFile",
$Config{Verbose}, $currentSubTask, $progressJobs, $progressPercent,
0 );
DownloadFile( $URL, $partialFile, 0 );
if ( -s $partialFile == 0 ) {
printf("No data here...\n");
# if loop was requested just return or else exit with an error.
# (to enable wrappers to better handle this situation
# i.e. tell the server the job hasn't been done yet)
PutRequestBackToServer( $X, $Y, 12, "NoData" );
foreach my $file (@tempfiles) { killafile($file); }
return cleanUpAndDie( "GenerateTileset", $Mode, 1, $PID );
}
}
mergeOsmFiles( $DataFile, $filelist );
# Get the server time for the data so we can assign it to the generated image (for tracking from when a tile actually is)
$JobTime = [ stat $DataFile ]->[9];
# Check for correct UTF8 (else inkscape will run amok later)
# FIXME: This doesn't seem to catch all string errors that inkscape trips over.
statusMessage( "Checking for UTF-8 errors in $DataFile",
$Config{Verbose}, $currentSubTask, $progressJobs, $progressPercent, 0 );
open( OSMDATA, $DataFile )
|| die("could not open $DataFile for UTF-8 check");
my @toCheck = <OSMDATA>;
close(OSMDATA);
my $osmtagfound = 0;
while ( my $osmline = shift @toCheck ) {
if ( utf8::is_utf8($osmline)) {
# this might require perl 5.8.1 or an explicit use statement
statusMessage(
"found incorrect UTF-8 chars in $DataFile, job $X $Y $Zoom",
$Config{Verbose},
$currentSubTask,
$progressJobs,
$progressPercent,
1
);
PutRequestBackToServer( $X, $Y, 12,"BadUTF8" );
return cleanUpAndDie( "GenerateTileset:UTF8 test failed",
$Mode, 1, $PID );
}
if ($osmline =~ /\<\/osm\>/ ) {
$osmtagfound=1;
}
}
if ($osmtagfound ==0) {
PutRequestBackToServer( $X, $Y, 12,"InvalidData" );
return cleanUpAndDie( "Invalid OSM Data",$Mode, 1, $PID );
}
my $StartTime = time();
my $DataFileSize = ( -s $DataFile );
#------------------------------------------------------
# Adjust OSM data
#------------------------------------------------------
my $AdjustCmd = sprintf("%s perl adjustosmdata.pl --in-file %s --out-file %s --actions addfmrel,joinmpmembers,crop,isolatempmembers",
$Config{Niceness}, "$DataFile", "$DataFile");
print("\n" . $AdjustCmd . "\n") if ( $Config{Debug} );
statusMessage("Running OSM data adjustment", $Config{Verbose}, $currentSubTask, $progressJobs, $progressPercent, 0);
runCommand($AdjustCmd, $PID);
#------------------------------------------------------
# Handle all layers, one after the other
#------------------------------------------------------
foreach my $layer ( split( /,/, $Config{Layers} ) ) {
#reset progress for each layer
$progress = 0;
$progressPercent = 0;
$currentSubTask = $layer;
$JobDirectory = sprintf(
"%s%s_%d_%d_%d.tmpdir$Config{Slash}",
$Config{WorkingDirectory},
$Config{"Layer.$layer.Prefix"},
$Zoom, $X, $Y
);
mkdir $JobDirectory unless -d $JobDirectory;
my $maxzoom = $Config{"Layer.$layer.MaxZoom"};
my $minzoom = $Config{"Layer.$layer.MinZoom"};
my $layerDataFile;
# Faff around
for ( my $i = $minzoom ; $i <= $maxzoom ; $i++ ) {
killafile( $Config{WorkingDirectory} . "output-$PID-z$i.svg" ) if ( !$Config{Debug} );
}
my $Margin = " " x ( $Zoom - 8 );
#printf "%03d %s%d,%d: %1.2f - %1.2f, %1.2f - %1.2f\n", $Zoom, $Margin, $X, $Y, $S,$N, $W,$E;
#------------------------------------------------------
# Go through preprocessing steps for the current layer
#------------------------------------------------------
my @ppchain = ($PID);
# config option may be empty, or a comma separated list of preprocessors
foreach my $preprocessor ( split /,/, $Config{"Layer.$layer.Preprocessor"} ) {
my $inputFile = sprintf( "%sdata-%s.osm", $Config{WorkingDirectory}, join( "-", @ppchain ) );
push( @ppchain, $preprocessor );
my $outputFile = sprintf( "%sdata-%s.osm", $Config{WorkingDirectory}, join( "-", @ppchain ) );
if ( -f $outputFile ) {
# no action; files for this preprocessing step seem to have been created
# by another layer already!
} elsif ( $preprocessor eq "close-areas" ) {
my $Cmd =
sprintf( "%s perl close-areas.pl $X $Y $Zoom < %s > %s",
$Config{Niceness}, "$inputFile", "$outputFile" );
statusMessage( "Running close-areas",
$Config{Verbose}, $currentSubTask, $progressJobs,
$progressPercent, 0 );
runCommand( $Cmd, $PID );
} elsif ( $preprocessor eq "simplify" ) {
my $sfactor;
$sfactor = 0.00001;
my $Cmd = sprintf("%s perl simplify.pl --osm-file=%s --out=%s --simplify=%f",
$Config{Niceness}, "$inputFile",
"$outputFile", $sfactor
);
statusMessage( "Running Simplification",
$Config{Verbose}, $currentSubTask, $progressJobs,
$progressPercent, 0 );
runCommand( $Cmd, $PID );
} elsif ( $preprocessor eq "relation" ) {
my $Cmd = sprintf("%s perl analyze_missing_relations.pl --osm-file=%s --out=%s",
$Config{Niceness}, "$inputFile",
"$outputFile"
);
statusMessage( "Running Analyze relations",
$Config{Verbose}, $currentSubTask, $progressJobs,
$progressPercent, 0 );
runCommand( $Cmd, $PID );
} else {
die "Invalid preprocessing step '$preprocessor'";
}
push( @tempfiles, $outputFile );
}
#------------------------------------------------------
# Preprocessing per zoom preprocessors
#------------------------------------------------------
my $layerDataFile;
my $empty = 0;
for ( my $i = $minzoom ; $i <= $maxzoom ; $i++ ) {
my @ppchainz = ();
my $LayerZoomPreprocessor = $Config{"Layer.$layer.$i.Preprocessor"};
#remove mercator projection from preprocessors
$LayerZoomPreprocessor =~ s/mercator//g;
$LayerZoomPreprocessor =~ s/,,//g;
if ($LayerZoomPreprocessor eq "") {
$LayerZoomPreprocessor = "mercator,analyze_way_length";
} elsif (!($LayerZoomPreprocessor =~ /\mercator/)){
$LayerZoomPreprocessor = $LayerZoomPreprocessor . ",mercator";
}
if ($LayerZoomPreprocessor ne "") {
my $originalFile = sprintf( "%sdata-%s.osm", $Config{WorkingDirectory}, join( "-", @ppchain ));
$layerDataFile = $originalFile;
# config option may be empty, or a comma separated list of preprocessors
foreach my $preprocessor ( split /,/, $LayerZoomPreprocessor ) {
my $inputFile = sprintf( "%sdata-%s-%s-%d.osm", $Config{WorkingDirectory}, join( "-", @ppchain ),join( "-", @ppchainz ), $i );
if ( ! -f $inputFile ) { # preprocessor is executed for the first time, use the original file
$inputFile = $originalFile;
}
push( @ppchainz, $preprocessor );
my $outputFile = sprintf( "%sdata-%s-%s-%d.osm", $Config{WorkingDirectory}, join( "-", @ppchain ),join( "-", @ppchainz ), $i );
if ( -f $outputFile ) {
# no action; files for this preprocessing step seem to have been created
# by another layer already!
} elsif ( $preprocessor eq "mercator" ) {
my $deltaZoom = $i - 12;
my $Cmd = sprintf( "%s perl mercatorize.pl -in-file %s -out-file %s -z $Zoom -x $X -y $Y -s $deltaZoom ",
$Config{Niceness}, "$inputFile", "$outputFile" );
statusMessage( "Running Mercatorization",
$Config{Verbose}, $currentSubTask, $progressJobs,
$progressPercent, 0 );
runCommand( $Cmd, $PID );
} elsif ( $preprocessor eq "analyze_way_length" ) {
my $Cmd = sprintf( "%s perl analyze_way_length.pl -in-file=%s -out-file=%s --mode=merc ",
$Config{Niceness}, "$inputFile", "$outputFile" );
statusMessage( "Running Analyze way length",
$Config{Verbose}, $currentSubTask, $progressJobs,
$progressPercent, 0 );
runCommand( $Cmd, $PID );
} elsif ( $preprocessor eq "simplify" ) {
my $sfactor;
$sfactor = $Config{"Layer.$layer.$i.Preprocessor.simplify.factor"};
my $Cmd = sprintf("%s perl simplify.pl --osm-file=%s --out=%s --simplify=%f",
$Config{Niceness}, "$inputFile",
"$outputFile", $sfactor
);
statusMessage( "Running Simplification",
$Config{Verbose}, $currentSubTask, $progressJobs,
$progressPercent, 0 );
runCommand( $Cmd, $PID );
} else {
die "Invalid preprocessing step '$preprocessor'";
}
#zapamatame si vystup
$layerDataFile = $outputFile;
push( @tempfiles, $outputFile );
}
}
if ( -f $layerDataFile ) {
#ok use it ...
} else {
# fall back to whole-layer-datafile
$layerDataFile = sprintf( "%sdata-%s.osm", $Config{WorkingDirectory}, join( "-", @ppchain ));
}
# Create a new copy of rules file to allow background update
# don't need zoom or layer in name of file as we'll
# process one after the other
my $source = $Config{FeaturesPathMercator} . $Config{"Layer.$layer.Rules.$i"};
my $tmpFeaturesXml = $Config{WorkingDirectory} . "map-features-$PID.xml";
print ("\nsource: $source\n") if ( $Config{Debug} );
copy( $source, $tmpFeaturesXml )
or die "Cannot make copy of $source";
# Update the rules file with details of what to do (where to get data, what bounds to use)
#AddBounds( $tmpFeaturesXml, $W, $S, $E, $N );
my $deltaZoom = $i - 12;
print ("Delta Zoom: $deltaZoom\n") if ( $Config{Debug} );
AddBounds2( $tmpFeaturesXml, $deltaZoom );
SetDataSource( $layerDataFile, $tmpFeaturesXml );
# Render the file
if (
xml2svg(
$tmpFeaturesXml,
"$Config{WorkingDirectory}output-$PID-z$i.svg",
$layer, $i
)
)
{
# Delete temporary rules file
killafile($tmpFeaturesXml) if ( !$Config{Debug} );
}
else {
# Delete temporary rules file
killafile($tmpFeaturesXml);
foreach my $file (@tempfiles) {
killafile($file) if ( !$Config{Debug} );
}
return 0;
}
# Find the size of the SVG file
my ( $ImgH, $ImgW, $Valid ) = getSize("$Config{WorkingDirectory}output-$PID-z$i.svg");
print "\nImage Dimension: $ImgH, $ImgW \n\n" if ( $Config{Debug} );
# Render it as loads of recursive tiles
$empty = RenderTile($layer, $X, $Y, $i, 12, 0, 0, $ImgW, $ImgH, 0);
# Clean-up the SVG file for current zoom
killafile("$Config{WorkingDirectory}output-$PID-z$i.svg") if ( !$Config{Debug} );
}
#if $empty then the next zoom level was empty, so we only upload one tile
if ( $empty == 1 && $Config{GatherBlankTiles} ) {
my $Filename = sprintf( "%s_%s_%s_%s.png",
$Config{"Layer.$layer.Prefix"},
$Zoom, $X, $Y );
my $oldFilename = sprintf( "%s%s", $JobDirectory, $Filename );
my $newFilename =
sprintf( "%s%s", $Config{WorkingDirectory}, $Filename );
rename( $oldFilename, $newFilename );
rmdir($JobDirectory);
} else {
# This directory is now ready for upload.
# How should errors in renaming be handled?
my $Dir = $JobDirectory;
$Dir =~ s|\.tmpdir|.dir|;
print "\nRenaming \"$JobDirectory\" to \"$Dir\"\n" if ( $Config{Debug} );
rename $JobDirectory, $Dir;
}
if ( $Config{LayerUpload} ) {
uploadIfEnoughTiles();
}
}
my $TimeTaken = ( time() - $StartTime );
$CurrentPerformance = $DataFileSize / $TimeTaken;
printf(
"\n\nCurrent Performance: %6f\nTime Taken: %f\nDtat File Size: %d\n\n",
$CurrentPerformance, $TimeTaken, $DataFileSize );
foreach my $file (@tempfiles) {
killafile($file) if ( !$Config{Debug} );
}
return 1;
}
#-----------------------------------------------------------------------------
# Render a tile
# $X, $Y - which tileset (Always the z12 tilenumbers)
# $Ytile, $Zoom - which tilestripe
# $ZOrig, the lowest zoom level which called tileset generation
# $ImgX1,$ImgY1,$ImgX2,$ImgY2 - location of the tile in the SVG file
# $empty - put forward "empty" tilestripe information.
#-----------------------------------------------------------------------------
sub RenderTile {
my (
$layer, $X, $Y, $Zoom, $ZOrig,
$X1, $Y1, $X2, $Y2, $empty
) = @_;
return if ( $Zoom > $Config{"Layer.$layer.MaxZoom"} );
my $AAL = $Config{"AAL"};
if ( $Config{"Layer.$layer.AAL.$Zoom"} != 0 ) {
$AAL = $Config{"Layer.$layer.AAL.$Zoom"};
}
# no need to render subtiles if empty
return if ( $empty == 1 );
# Render it to PNG
printf "Tilestripe (%s,%s): X %1.1f,%1.1f, Y %1.1f,%1.1f\n",
$X, $Y, $X1, $X2, $Y1, $Y2
if ( $Config{"Debug"} );
my $Width =
( $AAL * 256 ) * ( 2**( $Zoom - $ZOrig ) ); # Pixel size of tiles
my $Height = $Width; # Pixel height of tile
# svg2png returns true if all tiles extracted were empty. this might break
# if a higher zoom tile would contain data that is not rendered at the
# current zoom level.
if (defined $Config{"OutputSVG"} ) {
copy( $Config{WorkingDirectory}."output-$PID-z$Zoom.svg",$Config{WorkingDirectory}."$layer-$Zoom-$X-$Y.svg");
}
if ( defined $Config{"NoTiles"} ) {
# nothing :)
} else {
if ( $Zoom >= $Config{"Layer.$layer.MinZoom"} ) {
if (
svg2png(
$layer, $X, $Y, $Zoom, $ZOrig,
$X1, $Y1, $X2, $Y2, $Width, $Height
)
and !$Config{"Layer.$layer.RenderFullTileset"}
)
{
$empty = 1;
}
}
}
# Get progress percentage
if ( $empty == 1 ) {
# leap forward because this tile and all higher zoom tiles of it are "done" (empty).
for ( my $j = $Config{"Layer.$layer.MaxZoom"} ; $j >= $Zoom ; $j-- ) {
$progress += 2**( $Config{"Layer.$layer.MaxZoom"} - $j );
}
}
else {
$progress += 1;
}
if (
(
$progressPercent = $progress * 100 /
($Config{"Layer.$layer.MaxZoom"} - $Config{"Layer.$layer.MinZoom"} + 1)
) == 100
)
{
statusMessage( "Finished $X,$Y for layer $layer",
$Config{Verbose}, $currentSubTask, $progressJobs, $progressPercent,
1 );
}
else {