2 * Navit, a modular navigation system.
3 * Copyright (C) 2005-2008 Navit Team
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * version 2 as published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the
16 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
17 * Boston, MA 02110-1301, USA.
21 #define _FILE_OFFSET_BITS 64
22 #define _LARGEFILE_SOURCE
23 #define _LARGEFILE64_SOURCE
39 #ifdef HAVE_POSTGRESQL
43 #define BUFFER_SIZE 1280
45 #define GENERATE_INDEX
48 #define debug_tile(x) 0
50 #define debug_tile(x) (!strcmp(x,"bcdbd") || !strcmp(x,"bcdbd") || !strcmp(x,"bcdbda") || !strcmp(x,"bcdbdb") || !strcmp(x,"bcdbdba") || !strcmp(x,"bcdbdbb") || !strcmp(x,"bcdbdbba") || !strcmp(x,"bcdbdbaa") || !strcmp(x,"bcdbdbacaa") || !strcmp(x,"bcdbdbacab") || !strcmp(x,"bcdbdbacaba") || !strcmp(x,"bcdbdbacabaa") || !strcmp(x,"bcdbdbacabab") || !strcmp(x,"bcdbdbacababb") || !strcmp(x,"bcdbdbacababba") || !strcmp(x,"bcdbdbacababbb") || !strcmp(x,"bcdbdbacababbd") || !strcmp(x,"bcdbdbacababaa") || !strcmp(x,"bcdbdbacababab") || !strcmp(x,"bcdbdbacababac") || !strcmp(x,"bcdbdbacababad") || !strcmp(x,"bcdbdbacabaaa") || !strcmp(x,"bcdbdbacabaaba") || !strcmp(x,"bcdbdbacabaabb") || !strcmp(x,"bcdbdbacabaabc") || !strcmp(x,"bcdbdbacabaabd") || !strcmp(x,"bcdbdbacabaaaa") || !strcmp(x,"bcdbdbacabaaab") || !strcmp(x,"bcdbdbacabaaac") || !strcmp(x,"bcdbdbacabaaad") || 0)
54 static GHashTable *dedupe_ways_hash;
56 static int attr_debug_level=1;
57 static int nodeid,wayid;
58 static int report,phase;
59 static int ignore_unkown = 0, coverage=0;
61 static char *attrmap={
63 "n amenity=hospital poi_hospital\n"
64 "n amenity=atm poi_bank\n"
65 "n amenity=bank poi_bank\n"
66 "n amenity=pub poi_bar\n"
67 "n amenity=cafe poi_cafe\n"
68 "n amenity=bus_station poi_bus_station\n"
69 "n amenity=parking poi_car_parking\n"
70 "n amenity=cinema poi_cinema\n"
71 "n amenity=fire_station poi_firebrigade\n"
72 "n amenity=fuel poi_fuel\n"
73 "n amenity=courthouse poi_justice\n"
74 "n amenity=library poi_library\n"
75 "n amenity=pharmacy poi_pharmacy\n"
76 "n amenity=place_of_worship,religion=christian poi_church\n"
77 "n amenity=police poi_police\n"
78 "n amenity=post_office poi_post\n"
79 "n amenity=post_box poi_post\n"
80 "n amenity=public_building poi_public_office\n"
81 "n amenity=restaurant poi_restaurant\n"
82 "n amenity=fast_food poi_fastfood\n"
83 "n amenity=toilets poi_restroom\n"
84 "n amenity=school poi_school\n"
85 "n amenity=university poi_school\n"
86 "n amenity=college poi_school\n"
87 "n amenity=telephone poi_telephone\n"
88 "n amenity=theatre poi_theater\n"
89 "n amenity=townhall poi_townhall\n"
90 "n highway=bus_stop poi_bus_stop\n"
91 "n highway=mini_roundabout mini_roundabout\n"
92 "n highway=motorway_junction highway_exit\n"
93 "n highway=traffic_signals traffic_signals\n"
94 "n highway=turning_circle turning_circle\n"
95 "n leisure=slipway poi_boat_ramp\n"
96 "n leisure=fishing poi_fish\n"
97 "n sport=golf poi_golf\n"
98 "n leisure=golf_course poi_golf\n"
99 "n leisure=marina poi_marine\n"
100 "n leisure=sports_centre poi_sport\n"
101 "n leisure=stadium poi_stadium\n"
102 "n shop=supermarket poi_shopping\n"
103 "n shop=convenience poi_shop_grocery\n"
104 "n tourism=attraction poi_attraction\n"
105 "n tourism=camp_site poi_camp_rv\n"
106 "n tourism=caravan_site poi_camp_rv\n"
107 "n tourism=hotel poi_hotel\n"
108 "n tourism=motel poi_hotel\n"
109 "n tourism=guest_house poi_hotel\n"
110 "n tourism=hostel poi_hotel\n"
111 "n tourism=information poi_information\n"
112 "n tourism=museum poi_museum_history\n"
113 "n tourism=picnic_site poi_picnic\n"
114 "n tourism=theme_park poi_resort\n"
115 "n tourism=zoo poi_zoo\n"
116 "n amenity=grave_yard poi_cemetery\n"
117 "n landuse=cemetery poi_cemetery\n"
118 "n military=airfield poi_military\n"
119 "n military=bunker poi_military\n"
120 "n military=barracks poi_military\n"
121 "n military=range poi_military\n"
122 "n military=danger_area poi_danger_area\n"
123 "n sport=swimming poi_swimming\n"
124 "n sport=skiing poi_skiing\n"
125 "n aeroway=aerodrome poi_airport\n"
126 "n aeroway=airport poi_airport\n"
127 "n aeroway=terminal poi_airport\n"
128 "n aeroway=helipad poi_heliport\n"
129 "n man_made=tower poi_tower\n"
130 "n natural=bay poi_bay\n"
131 "n natural=peak poi_peak\n"
132 "n place=suburb district_label\n"
133 "n place=city town_label_2e5\n"
134 "n place=town town_label_2e4\n"
135 "n place=village town_label_2e3\n"
136 "n place=hamlet town_label_2e2\n"
137 "n place=locality town_label_2e0\n"
138 "n railway=halt poi_rail_halt\n"
139 "n railway=level_crossing poi_level_crossing\n"
140 "n railway=station poi_rail_station\n"
141 "n railway=tram_stop poi_rail_tram_stop\n"
142 "w *=* street_unkn\n"
143 "w amenity=place_of_worship poly_building\n"
144 "w building=* poly_building\n"
145 "w aeroway=aerodrome poly_airport\n"
146 "w aeroway=apron poly_apron\n"
147 "w aeroway=runway aeroway_runway\n"
148 "w aeroway=taxiway aeroway_taxiway\n"
149 "w aeroway=terminal poly_terminal\n"
150 "w highway=bridleway bridleway\n"
151 "w highway=cycleway cycleway\n"
152 "w highway=cyclepath cycleway\n"
153 "w highway=footway footway\n"
154 "w highway=steps steps\n"
155 "w highway=unsurfaced track_gravelled\n"
156 "w highway=track track_gravelled\n"
157 "w highway=track,tracktype=grade1 track_paved\n"
158 "w highway=track,surface=paved track_paved\n"
159 "w highway=track,tracktype=grade2 track_gravelled\n"
160 "w highway=track,surface=gravel track_gravelled\n"
161 "w highway=track,tracktype=grade3 track_unpaved\n"
162 "w highway=track,surface=unpaved track_unpaved\n"
163 "w highway=track,tracktype=grade4 track_ground\n"
164 "w highway=track,surface=ground track_ground\n"
165 "w highway=track,tracktype=grade5 track_grass\n"
166 "w highway=track,surface=grass track_grass\n"
167 "w highway=service street_service\n"
168 "w highway=construction street_construction\n"
169 "w highway=pedestrian street_pedestrian\n"
170 "w highway=pedestrian,area=1 poly_pedestrian\n"
171 "w highway=plaza poly_plaza\n"
172 "w landuse=plaza poly_plaza\n"
173 "w highway=residential street_1_city\n"
174 "w highway=living_street living_street\n"
175 "w highway=unclassified street_1_city\n"
176 "w highway=road street_1_city\n"
177 "w highway=minor street_1_land\n"
178 "w highway=tertiary street_2_city\n"
179 "w highway=tertiary_link ramp\n"
180 "w highway=secondary street_3_city\n"
181 "w highway=secondary_link ramp\n"
182 "w highway=primary street_4_city\n"
183 "w highway=primary_link ramp\n"
184 "w highway=trunk street_4_city\n"
185 "w highway=trunk_link ramp\n"
186 "w highway=motorway highway_city\n"
187 "w highway=motorway_link ramp\n"
188 "w historic=town gate poly_building\n"
189 "w cycleway=track cycleway\n"
190 "w amenity=parking poly_car_parking\n"
191 "w landuse=allotments poly_allotments\n"
192 "w landuse=cemetery poly_cemetery\n"
193 "w amenity=grave_yard poly_cemetery\n"
194 "w landuse=forest poly_wood\n"
195 "w landuse=industrial poly_industry\n"
196 "w landuse=residential poly_town\n"
197 "w landuse=residential,area=1 poly_town\n"
198 "w amenity=college poly_college\n"
199 "w amenity=university poly_university\n"
200 "w tourism=camp_site poly_camp_site\n"
201 "w tourism=caravan_site poly_caravan_site\n"
202 "w tourism=picnic_site poly_picnic_site\n"
203 "w tourism=theme_park poly_theme_park\n"
204 "w tourism=attraction poly_attraction\n"
205 "w tourism=zoo poly_zoo\n"
206 "w tourism=artwork poly_artwork\n"
207 "w historic=archaeological_site poly_archaeological_site\n"
208 "w historic=ruins poly_ruins\n"
209 "w historic=battlefield poly_battlefield\n"
210 "w landuse=quarry poly_quarry\n"
211 "w landuse=landfill poly_landfill\n"
212 "w landuse=retail poly_retail\n"
213 "w landuse=commercial poly_commercial\n"
214 "w landuse=brownfield poly_brownfield\n"
215 "w landuse=greenfield poly_greenfield\n"
216 "w landuse=construction poly_construction\n"
217 "w landuse=railway poly_railway\n"
218 "w natural=glacier poly_glacier\n"
219 "w natural=scree poly_scree\n"
220 "w natural=scrub poly_scrub\n"
221 "w natural=fell poly_fell\n"
222 "w natural=heath poly_heath\n"
223 "w natural=marsh poly_marsh\n"
224 "w natural=mud poly_mud\n"
225 "w natural=beach poly_beach\n"
226 "w natural=land poly_land\n"
227 "w landuse=basin poly_basin\n"
228 "w landuse=reservoir poly_reservoir\n"
229 "w landuse=farm poly_farm\n"
230 "w landuse=vineyard poly_farm\n"
231 "w leisure=park poly_park\n"
232 "w landuse=village_green poly_village_green\n"
233 "w landuse=recreation_ground poly_recreation_ground\n"
234 "w natural=wood poly_wood\n"
235 "w natural=water poly_water\n"
236 "w natural=coastline water_line\n"
237 "w place=suburb poly_town\n"
238 "w place=town poly_town\n"
239 "w landuse=military poly_military\n"
240 "w military=airfield poly_airfield\n"
241 "w military=barracks poly_barracks\n"
242 "w military=danger_area poly_danger_area\n"
243 "w military=range poly_range\n"
244 "w military=naval_base poly_naval_base\n"
245 "w power=line powerline\n"
246 "w railway=rail rail\n"
247 "w railway=narrow_gauge rail_narrow_gauge\n"
248 "w railway=light_rail rail_light\n"
249 "w railway=subway rail_subway\n"
250 "w railway=tram rail_tram\n"
251 "w railway=monorail rail_mono\n"
252 "w railway=preserved rail_preserved\n"
253 "w railway=disused rail_disused\n"
254 "w railway=abandoned rail_abandoned\n"
255 "w aerialway=cable_car lift_cable_car\n"
256 "w aerialway=chair_lift lift_chair\n"
257 "w aerialway=drag_lift lift_drag\n"
258 "w leisure=golf_course poly_golf_course\n"
259 "w sport=* poly_sport\n"
260 "w leisure=sports_centre poly_sport\n"
261 "w leisure=stadium poly_sports_stadium\n"
262 "w leisure=track poly_sports_track\n"
263 "w leisure=pitch poly_sports_pitch\n"
264 "w leisure=water_park poly_water_park\n"
265 "w leisure=marina poly_marina\n"
266 "w leisure=fishing poly_fishing\n"
267 "w leisure=garden poly_garden\n"
268 "w leisure=common poly_common\n"
269 "w leisure=playground poly_playground\n"
270 "w leisure=nature_reserve poly_nature_reserve\n"
271 "w waterway=canal water_canal\n"
272 "w waterway=river water_river\n"
273 "w waterway=stream water_stream\n"
274 "w waterway=drain water_drain\n"
275 "w waterway=riverbank poly_water\n"
276 "w boundary=administrative border_country\n"
277 "w boundary=civil border_civil\n"
278 "w boundary=political border_political\n"
279 "w boundary=national_park border_national_park\n"
280 "w route=ferry ferry\n"
281 "w highway=bus_guideway bus_guideway\n"
287 } coord_buffer[65536];
289 #define IS_REF(c) ((c).x >= (1 << 30))
290 #define REF(c) ((c).y)
291 #define SET_REF(c,ref) do { (c).x = 1 << 30; (c).y = ref ; } while(0)
297 static void bbox_extend(struct coord *c, struct rect *r);
299 #ifdef GENERATE_INDEX
301 static GHashTable *aux_tile_hash;
302 GList *aux_tile_list;
304 struct country_table {
311 } country_table[] = {
312 { 40,"Austria,Österreich,AUT"},
314 {276,"Germany,Deutschland,Bundesrepublik Deutschland"},
315 {528,"Nederland,The Netherlands,Niederlande,NL"},
320 static GHashTable *country_table_hash;
323 struct attr_mapping {
325 int attr_present_idx_count;
326 int attr_present_idx[0];
329 static struct attr_mapping **attr_mapping_node;
330 static int attr_mapping_node_count;
331 static struct attr_mapping **attr_mapping_way;
332 static int attr_mapping_way_count;
334 static char *attr_present;
335 static int attr_present_count;
336 static GHashTable *attr_hash;
339 static GHashTable *strings_hash = NULL;
342 static char* string_hash_lookup( const char* key )
344 char* key_ptr = NULL;
346 if ( strings_hash == NULL ) {
347 strings_hash = g_hash_table_new(g_str_hash, g_str_equal);
350 if ( ( key_ptr = g_hash_table_lookup(strings_hash, key )) == NULL ) {
351 key_ptr = g_strdup( key );
352 g_hash_table_insert(strings_hash, key_ptr, (gpointer)key_ptr );
359 build_attrmap_line(char *line)
361 char *t=NULL,*kvl=NULL,*i=NULL,*p,*kv;
362 struct attr_mapping ***attr_mapping_curr,*attr_mapping=g_malloc0(sizeof(struct attr_mapping));
363 int idx,attr_mapping_count=0,*attr_mapping_curr_count;
380 attr_mapping_curr=&attr_mapping_way;
381 attr_mapping_curr_count=&attr_mapping_way_count;
385 attr_mapping_curr=&attr_mapping_node;
386 attr_mapping_curr_count=&attr_mapping_node_count;
388 attr_mapping->type=item_from_name(i);
389 while ((kv=strtok(kvl, ","))) {
391 if (!(idx=(int)g_hash_table_lookup(attr_hash, kv))) {
392 idx=attr_present_count++;
393 g_hash_table_insert(attr_hash, kv, (gpointer) idx);
395 attr_mapping=g_realloc(attr_mapping, sizeof(struct attr_mapping)+(attr_mapping_count+1)*sizeof(int));
396 attr_mapping->attr_present_idx[attr_mapping_count++]=idx;
397 attr_mapping->attr_present_idx_count=attr_mapping_count;
399 *attr_mapping_curr=g_realloc(*attr_mapping_curr, sizeof(**attr_mapping_curr)*(*attr_mapping_curr_count+1));
400 (*attr_mapping_curr)[(*attr_mapping_curr_count)++]=attr_mapping;
404 build_attrmap(char *map)
407 attr_hash=g_hash_table_new(g_str_hash, g_str_equal);
408 attr_present_count=1;
414 build_attrmap_line(map);
417 attr_present=g_malloc0(sizeof(*attr_present)*attr_present_count);
420 #ifdef GENERATE_INDEX
422 build_countrytable(void)
425 char *names,*str,*tok;
426 country_table_hash=g_hash_table_new(g_str_hash, g_str_equal);
427 for (i = 0 ; i < sizeof(country_table)/sizeof(struct country_table) ; i++) {
428 names=g_strdup(country_table[i].names);
430 while ((tok=strtok(str, ","))) {
432 g_hash_table_insert(country_table_hash, tok, (gpointer)&country_table[i]);
440 static int processed_nodes, processed_nodes_out, processed_ways, processed_relations, processed_tiles;
441 static int in_way, in_node, in_relation;
447 signal(SIGALRM, sig_alrm);
450 fprintf(stderr,"PROGRESS%d: Processed %d nodes (%d out) %d ways %d relations %d tiles\n", phase, processed_nodes, processed_nodes_out, processed_ways, processed_relations, processed_tiles);
464 struct attr_bin label_attr = {
467 char label_attr_buffer[BUFFER_SIZE];
469 struct attr_bin town_name_attr = {
473 struct attr_bin street_name_attr = {
477 struct attr_bin street_name_systematic_attr = {
478 0, attr_street_name_systematic
480 char street_name_systematic_attr_buffer[BUFFER_SIZE];
482 struct attr_bin debug_attr = {
485 char debug_attr_buffer[BUFFER_SIZE];
487 struct attr_bin flags_attr = {
490 int flags_attr_value;
492 char is_in_buffer[BUFFER_SIZE];
495 static void write_zipmember(FILE *out, FILE *dir_out, char *name, int filelen, char *data, int data_size, int compression_level);
498 pad_text_attr(struct attr_bin *a, char *buffer)
501 if (buffer && buffer[0]) {
511 xml_get_attribute(char *xml, char *attribute, char *buffer, int buffer_size)
513 int len=strlen(attribute);
514 char *pos,*i,s,attr[len+2];
515 strcpy(attr, attribute);
516 strcpy(attr+len, "=");
517 pos=strstr(xml, attr);
527 if (i - pos > buffer_size) {
528 fprintf(stderr,"Buffer overflow %d vs %d\n", i-pos, buffer_size);
531 strncpy(buffer, pos, i-pos);
536 static int node_is_tagged;
539 add_tag(char *k, char *v)
541 GHashTable *value_hash;
544 char buffer[BUFFER_SIZE*2+2];
545 if (! strcmp(k,"ele"))
547 if (! strcmp(k,"time"))
549 if (! strcmp(k,"created_by"))
551 if (! strncmp(k,"tiger:",6) || !strcmp(k,"AND_nodes"))
553 if (! strcmp(k,"converted_by") || ! strcmp(k,"source"))
555 if (! strncmp(k,"osmarender:",11) || !strncmp(k,"svg:",4))
557 if (! strcmp(k,"layer"))
559 if (! strcasecmp(v,"true") || ! strcasecmp(v,"yes"))
561 if (! strcmp(k,"oneway")) {
562 if (!strcmp(v,"1")) {
563 flags_attr_value=AF_ONEWAY;
566 if (! strcmp(v,"-1")) {
567 flags_attr_value=AF_ONEWAYREV;
575 if (! strcmp(k,"junction")) {
576 if (! strcmp(v,"roundabout")) {
577 flags_attr_value=AF_ONEWAY;
581 if (! strcmp(k,"maxspeed")) {
584 if (! strcmp(k,"bicycle")) {
587 if (! strcmp(k,"foot")) {
590 if (! strcmp(k,"note"))
592 if (! strcmp(k,"name")) {
593 strcpy(label_attr_buffer, v);
594 pad_text_attr(&label_attr, label_attr_buffer);
597 if (! strcmp(k,"ref")) {
599 strcpy(street_name_systematic_attr_buffer, v);
600 pad_text_attr(&street_name_systematic_attr, street_name_systematic_attr_buffer);
604 if (! strcmp(k,"is_in")) {
605 strcpy(is_in_buffer, v);
608 if (! strcmp(k,"gnis:ST_alpha")) {
609 /* assume a gnis tag means it is part of the USA:
610 http://en.wikipedia.org/wiki/Geographic_Names_Information_System
611 many US towns do not have is_in tags
613 strcpy(is_in_buffer, "USA");
616 if (! strcmp(k,"lanes")) {
619 if (attr_debug_level >= level) {
620 int bytes_left = sizeof( debug_attr_buffer ) - strlen(debug_attr_buffer) - 1;
621 if ( bytes_left > 0 )
623 snprintf(debug_attr_buffer+strlen(debug_attr_buffer), bytes_left, " %s=%s", k, v);
624 debug_attr_buffer[ sizeof( debug_attr_buffer ) - 1 ] = '\0';
633 strcpy(buffer,"*=*");
634 if ((idx=(int)g_hash_table_lookup(attr_hash, buffer)))
637 sprintf(buffer,"%s=*", k);
638 if ((idx=(int)g_hash_table_lookup(attr_hash, buffer)))
641 sprintf(buffer,"*=%s", v);
642 if ((idx=(int)g_hash_table_lookup(attr_hash, buffer)))
645 sprintf(buffer,"%s=%s", k, v);
646 if ((idx=(int)g_hash_table_lookup(attr_hash, buffer)))
662 decode_entities(char *buffer)
667 while ((pos=strchr(pos, '&'))) {
669 for (i = 0 ; i < sizeof(entities)/sizeof(struct entity); i++) {
670 len=strlen(entities[i].entity);
671 if (!strncmp(pos, entities[i].entity, len)) {
673 memmove(pos+1, pos+len, strlen(pos+len)+1);
685 char k_buffer[BUFFER_SIZE];
686 char v_buffer[BUFFER_SIZE];
687 if (!xml_get_attribute(p, "k", k_buffer, BUFFER_SIZE))
689 if (!xml_get_attribute(p, "v", v_buffer, BUFFER_SIZE))
691 decode_entities(v_buffer);
692 add_tag(k_buffer, v_buffer);
704 static struct tile_head {
712 struct tile_head *next;
728 static struct buffer node_buffer = {
733 static char** th_get_subtile( const struct tile_head* th, int idx )
735 char* subtile_ptr = NULL;
736 subtile_ptr = (char*)th + sizeof( struct tile_head ) + idx * sizeof( char *);
737 return (char**)subtile_ptr;
741 extend_buffer(struct buffer *b)
743 b->malloced+=b->malloced_step;
744 b->base=realloc(b->base, b->malloced);
745 if (b->base == NULL) {
746 fprintf(stderr,"realloc of %d bytes failed\n",b->malloced);
753 GHashTable *node_hash;
756 node_buffer_to_hash(void)
758 int i,count=node_buffer.size/sizeof(struct node_item);
759 struct node_item *ni=(struct node_item *)node_buffer.base;
760 for (i = 0 ; i < count ; i++)
761 g_hash_table_insert(node_hash, (gpointer)(ni[i].id), (gpointer)i);
764 static struct node_item *ni;
767 add_node(int id, double lat, double lon)
769 if (node_buffer.size + sizeof(struct node_item) > node_buffer.malloced)
770 extend_buffer(&node_buffer);
773 item.type=type_point_unkn;
775 town_name_attr.len=0;
777 is_in_buffer[0]='\0';
778 sprintf(debug_attr_buffer,"nodeid=%d", nodeid);
779 ni=(struct node_item *)(node_buffer.base+node_buffer.size);
785 ni->c.x=lon*6371000.0*M_PI/180;
786 ni->c.y=log(tan(M_PI_4+lat*M_PI/360))*6371000.0;
787 node_buffer.size+=sizeof(struct node_item);
789 if (ni->id > nodeid_last) {
792 fprintf(stderr,"INFO: Nodes out of sequence (new %d vs old %d), adding hash\n", ni->id, nodeid_last);
793 node_hash=g_hash_table_new(NULL, NULL);
794 node_buffer_to_hash();
797 if (!g_hash_table_lookup(node_hash, (gpointer)(ni->id)))
798 g_hash_table_insert(node_hash, (gpointer)(ni->id), (gpointer)(ni-(struct node_item *)node_buffer.base));
800 node_buffer.size-=sizeof(struct node_item);
809 char id_buffer[BUFFER_SIZE];
810 char lat_buffer[BUFFER_SIZE];
811 char lon_buffer[BUFFER_SIZE];
812 if (!xml_get_attribute(p, "id", id_buffer, BUFFER_SIZE))
814 if (!xml_get_attribute(p, "lat", lat_buffer, BUFFER_SIZE))
816 if (!xml_get_attribute(p, "lon", lon_buffer, BUFFER_SIZE))
818 add_node(atoi(id_buffer), atof(lat_buffer), atof(lon_buffer));
823 static struct node_item *
824 node_item_get(int id)
826 struct node_item *ni=(struct node_item *)(node_buffer.base);
827 int count=node_buffer.size/sizeof(struct node_item);
828 int interval=count/4;
832 i=(int)(g_hash_table_lookup(node_hash, (gpointer)id));
835 while (ni[p].id != id) {
837 fprintf(stderr,"p=%d count=%d interval=%d id=%d ni[p].id=%d\n", p, count, interval, id, ni[p].id);
872 struct node_item *ni=node_item_get(id);
874 fprintf(stderr,"WARNING: node id %d not found\n", id);
886 item.type=type_street_unkn;
888 street_name_attr.len=0;
889 street_name_systematic_attr.len=0;
892 sprintf(debug_attr_buffer,"wayid=%d", wayid);
898 char id_buffer[BUFFER_SIZE];
899 if (!xml_get_attribute(p, "id", id_buffer, BUFFER_SIZE))
901 add_way(atoi(id_buffer));
906 parse_relation(char *p)
908 debug_attr_buffer[0]='\0';
913 write_attr(FILE *out, struct attr_bin *attr, void *buffer)
916 fwrite(attr, sizeof(*attr), 1, out);
917 fwrite(buffer, (attr->len-1)*4, 1, out);
922 attr_longest_match(struct attr_mapping **mapping, int mapping_count, enum item_type *types, int types_count)
924 int i,j,longest=0,ret=0,sum,val;
925 struct attr_mapping *curr;
926 for (i = 0 ; i < mapping_count ; i++) {
929 for (j = 0 ; j < curr->attr_present_idx_count ; j++) {
930 val=attr_present[curr->attr_present_idx[j]];
942 if (sum > 0 && sum == longest && ret < types_count)
943 types[ret++]=curr->type;
945 memset(attr_present, 0, sizeof(*attr_present)*attr_present_count);
953 enum item_type types[5];
957 if (dedupe_ways_hash) {
958 if (g_hash_table_lookup(dedupe_ways_hash, (gpointer)wayid))
960 g_hash_table_insert(dedupe_ways_hash, (gpointer)wayid, (gpointer)1);
962 count=attr_longest_match(attr_mapping_way, attr_mapping_way_count, types, sizeof(types)/sizeof(enum item_type));
963 pad_text_attr(&debug_attr, debug_attr_buffer);
965 alen+=label_attr.len+1;
966 if (street_name_systematic_attr.len)
967 alen+=street_name_systematic_attr.len+1;
969 alen+=debug_attr.len+1;
971 alen+=flags_attr.len+1;
975 item.type=type_street_unkn;
976 if (coverage && item_is_street(item))
977 item.type=type_coverage;
978 item.clen=coord_count*2;
979 item.len=item.clen+2+alen;
980 fwrite(&item, sizeof(item), 1, out);
981 fwrite(coord_buffer, coord_count*sizeof(struct coord), 1, out);
982 if (item_is_street(item)) {
983 street_name_attr.len=label_attr.len;
984 write_attr(out, &street_name_attr, label_attr_buffer);
986 write_attr(out, &label_attr, label_attr_buffer);
987 write_attr(out, &street_name_systematic_attr, street_name_systematic_attr_buffer);
988 write_attr(out, &debug_attr, debug_attr_buffer);
989 write_attr(out, &flags_attr, &flags_attr_value);
995 int alen=0,conflict=0,count;
996 enum item_type types[5];
997 struct country_table *result=NULL, *lookup;
998 if (!out || ! node_is_tagged || ! nodeid)
1000 count=attr_longest_match(attr_mapping_node, attr_mapping_node_count, types, sizeof(types)/sizeof(enum item_type));
1001 pad_text_attr(&debug_attr, debug_attr_buffer);
1003 alen+=label_attr.len+1;
1005 alen+=debug_attr.len+1;
1009 item.type=type_point_unkn;
1011 item.len=item.clen+2+alen;
1012 fwrite(&item, sizeof(item), 1, out);
1013 fwrite(&ni->c, 1*sizeof(struct coord), 1, out);
1014 if (item_is_town(item)) {
1015 town_name_attr.len=label_attr.len;
1016 write_attr(out, &town_name_attr, label_attr_buffer);
1018 write_attr(out, &label_attr, label_attr_buffer);
1019 write_attr(out, &debug_attr, debug_attr_buffer);
1020 #ifdef GENERATE_INDEX
1021 if (item_is_town(item) && town_name_attr.len) {
1022 char *tok,*buf=is_in_buffer;
1023 while ((tok=strtok(buf, ","))) {
1026 lookup=g_hash_table_lookup(country_table_hash,tok);
1028 if (result && result->countryid != lookup->countryid) {
1029 fprintf(stderr,"conflict for %s %s country %d vs %d\n", label_attr_buffer, debug_attr_buffer, lookup->countryid, result->countryid);
1036 if (result && !conflict) {
1037 if (!result->file) {
1038 char *name=g_strdup_printf("country_%d.bin.unsorted", result->countryid);
1039 result->file=fopen(name,"w");
1044 item.len=item.clen+2+label_attr.len+1;
1045 fwrite(&item, sizeof(item), 1, result->file);
1046 fwrite(&ni->c, 1*sizeof(struct coord), 1, result->file);
1047 write_attr(result->file, &town_name_attr, label_attr_buffer);
1049 result->size+=(item.clen+3+label_attr.len+1)*4;
1055 processed_nodes_out++;
1059 sort_countries_compare(const void *p1, const void *p2)
1061 struct item_bin *ib1=*((struct item_bin **)p1),*ib2=*((struct item_bin **)p2);
1062 struct attr_bin *attr1,*attr2;
1064 assert(ib1->clen==2);
1065 assert(ib2->clen==2);
1066 attr1=(struct attr_bin *)((int *)(ib1+1)+ib1->clen);
1067 attr2=(struct attr_bin *)((int *)(ib2+1)+ib1->clen);
1068 assert(attr1->type == attr_town_name);
1069 assert(attr2->type == attr_town_name);
1070 s1=(char *)(attr1+1);
1071 s2=(char *)(attr2+1);
1072 return strcmp(s1, s2);
1074 fprintf(stderr,"sort_countries_compare p1=%p p2=%p %s %s\n",p1,p2,s1,s2);
1079 #ifdef GENERATE_INDEX
1081 sort_countries(void)
1084 struct country_table *co;
1086 struct item_bin *ib;
1088 char *p,*buffer,**idx,*name;
1089 for (i = 0 ; i < sizeof(country_table)/sizeof(struct country_table) ; i++) {
1090 co=&country_table[i];
1096 buffer=malloc(co->size);
1097 assert(buffer != NULL);
1098 idx=malloc(co->count*sizeof(void *));
1099 assert(idx != NULL);
1100 name=g_strdup_printf("country_%d.bin.unsorted", co->countryid);
1103 fread(buffer, co->size, 1, f);
1108 for (j = 0 ; j < co->count ; j++) {
1110 p+=(*((int *)p)+1)*4;
1112 qsort(idx, co->count, sizeof(void *), sort_countries_compare);
1113 name=g_strdup_printf("country_%d.bin", co->countryid);
1115 for (j = 0 ; j < co->count ; j++) {
1116 ib=(struct item_bin *)(idx[j]);
1117 c=(struct coord *)(ib+1);
1118 fwrite(ib, (ib->len+1)*4, 1, f);
1120 bbox_extend(c, &co->r);
1132 add_nd(char *p, int ref)
1135 struct node_item *ni;
1136 ni=node_item_get(ref);
1139 coord_buffer[coord_count++]=ni->c;
1141 SET_REF(coord_buffer[coord_count], ref);
1147 if (len > 0 && p[len-1]=='\n')
1149 fprintf(stderr,"WARNING: way %d: node %d not found (%s)\n",wayid,ref,p);
1151 if (coord_count > 65536) {
1152 fprintf(stderr,"ERROR: Overflow\n");
1160 char ref_buffer[BUFFER_SIZE];
1161 if (!xml_get_attribute(p, "ref", ref_buffer, BUFFER_SIZE))
1163 add_nd(p, atoi(ref_buffer));
1169 save_buffer(char *filename, struct buffer *b)
1172 f=fopen(filename,"wb+");
1173 fwrite(b->base, b->size, 1, f);
1178 load_buffer(char *filename, struct buffer *b)
1184 f=fopen(filename,"rb");
1185 fseek(f, 0, SEEK_END);
1186 b->size=b->malloced=ftell(f);
1187 fprintf(stderr,"reading %d bytes from %s\n", b->size, filename);
1188 fseek(f, 0, SEEK_SET);
1189 b->base=malloc(b->size);
1190 assert(b->base != NULL);
1191 fread(b->base, b->size, 1, f);
1196 phase1(FILE *in, FILE *out_ways, FILE *out_nodes)
1202 while (fgets(buffer, size, in)) {
1203 p=strchr(buffer,'<');
1205 fprintf(stderr,"WARNING: wrong line %s\n", buffer);
1208 if (!strncmp(p, "<?xml ",6)) {
1209 } else if (!strncmp(p, "<osm ",5)) {
1210 } else if (!strncmp(p, "<bound ",7)) {
1211 } else if (!strncmp(p, "<node ",6)) {
1213 fprintf(stderr,"WARNING: failed to parse %s\n", buffer);
1216 } else if (!strncmp(p, "<tag ",5)) {
1218 fprintf(stderr,"WARNING: failed to parse %s\n", buffer);
1219 } else if (!strncmp(p, "<way ",5)) {
1222 fprintf(stderr,"WARNING: failed to parse %s\n", buffer);
1224 } else if (!strncmp(p, "<nd ",4)) {
1226 fprintf(stderr,"WARNING: failed to parse %s\n", buffer);
1227 } else if (!strncmp(p, "<relation ",10)) {
1229 if (!parse_relation(p))
1230 fprintf(stderr,"WARNING: failed to parse %s\n", buffer);
1231 processed_relations++;
1232 } else if (!strncmp(p, "<member ",8)) {
1233 } else if (!strncmp(p, "</node>",7)) {
1235 end_node(out_nodes);
1236 } else if (!strncmp(p, "</way>",6)) {
1239 } else if (!strncmp(p, "</relation>",11)) {
1241 } else if (!strncmp(p, "</osm>",6)) {
1243 fprintf(stderr,"WARNING: unknown tag in %s\n", buffer);
1251 #ifdef HAVE_POSTGRESQL
1253 phase1_db(char *dbstr, FILE *out_ways, FILE *out_nodes)
1256 PGresult *res,*node,*way,*tag;
1257 int count,tagged,i,j,k;
1258 long min, max, id, tag_id, node_id;
1262 conn=PQconnectdb(dbstr);
1264 fprintf(stderr,"Failed to connect to database with '%s'\n",dbstr);
1267 res=PQexec(conn, "begin");
1269 fprintf(stderr, "Cannot begin transaction: %s\n", PQerrorMessage(conn));
1273 res=PQexec(conn, "set transaction isolation level serializable");
1275 fprintf(stderr, "Cannot set isolation level: %s\n", PQerrorMessage(conn));
1279 res=PQexec(conn, "declare node cursor for select id,x(coordinate),y(coordinate) from node order by id");
1281 fprintf(stderr, "Cannot setup cursor for nodes: %s\n", PQerrorMessage(conn));
1285 res=PQexec(conn, "declare way cursor for select id from way order by id");
1287 fprintf(stderr, "Cannot setup cursor for nodes: %s\n", PQerrorMessage(conn));
1291 res=PQexec(conn, "declare relation cursor for select id from relation order by id");
1293 fprintf(stderr, "Cannot setup cursor for nodes: %s\n", PQerrorMessage(conn));
1298 node=PQexec(conn, "fetch 100000 from node");
1300 fprintf(stderr, "Cannot setup cursor for nodes: %s\n", PQerrorMessage(conn));
1304 count=PQntuples(node);
1307 min=atol(PQgetvalue(node, 0, 0));
1308 max=atol(PQgetvalue(node, count-1, 0));
1309 sprintf(query,"select node_id,name,value from node_tag where node_id >= %ld and node_id <= %ld order by node_id", min, max);
1310 tag=PQexec(conn, query);
1312 fprintf(stderr, "Cannot query node_tag: %s\n", PQerrorMessage(conn));
1316 for (i = 0 ; i < count ; i++) {
1317 id=atol(PQgetvalue(node, i, 0));
1318 add_node(id, atof(PQgetvalue(node, i, 1)), atof(PQgetvalue(node, i, 2)));
1322 while (j < PQntuples(tag)) {
1323 tag_id=atol(PQgetvalue(tag, j, 0));
1325 add_tag(PQgetvalue(tag, j, 1), PQgetvalue(tag, j, 2));
1335 end_node(out_nodes);
1342 way=PQexec(conn, "fetch 100000 from way");
1344 fprintf(stderr, "Cannot setup cursor for ways: %s\n", PQerrorMessage(conn));
1348 count=PQntuples(way);
1351 min=atol(PQgetvalue(way, 0, 0));
1352 max=atol(PQgetvalue(way, count-1, 0));
1353 sprintf(query,"select way_id,node_id from way_node where way_id >= %ld and way_id <= %ld order by way_id,sequence_id", min, max);
1354 node=PQexec(conn, query);
1356 fprintf(stderr, "Cannot query way_node: %s\n", PQerrorMessage(conn));
1359 sprintf(query,"select way_id,name,value from way_tag where way_id >= %ld and way_id <= %ld order by way_id", min, max);
1360 tag=PQexec(conn, query);
1362 fprintf(stderr, "Cannot query way_tag: %s\n", PQerrorMessage(conn));
1367 for (i = 0 ; i < count ; i++) {
1368 id=atol(PQgetvalue(way, i, 0));
1373 while (k < PQntuples(node)) {
1374 node_id=atol(PQgetvalue(node, k, 0));
1375 if (node_id == id) {
1376 add_nd("",atol(PQgetvalue(node, k, 1)));
1385 while (j < PQntuples(tag)) {
1386 tag_id=atol(PQgetvalue(tag, j, 0));
1388 add_tag(PQgetvalue(tag, j, 1), PQgetvalue(tag, j, 2));
1406 res=PQexec(conn, "commit");
1408 fprintf(stderr, "Cannot commit transaction: %s\n", PQerrorMessage(conn));
1418 static char buffer[150000];
1422 static struct item_bin *
1425 struct item_bin *ib=(struct item_bin *) buffer;
1427 r=fread(ib, sizeof(*ib), 1, in);
1431 assert((ib->len+1) < sizeof(buffer));
1432 s=(ib->len+1)*4-sizeof(*ib);
1433 r=fread(ib+1, s, 1, in);
1441 bbox_extend(struct coord *c, struct rect *r)
1454 bbox(struct coord *c, int count, struct rect *r)
1467 contains_bbox(int xl, int yl, int xh, int yh, struct rect *r)
1469 if (r->h.x < xl || r->h.x > xh) {
1472 if (r->l.x > xh || r->l.x < xl) {
1475 if (r->h.y < yl || r->h.y > yh) {
1478 if (r->l.y > yh || r->l.y < yl) {
1484 struct rect world_bbox = {
1485 { -20000000, -20000000},
1486 { 20000000, 20000000},
1490 tile(struct rect *r, char *ret, int max)
1499 for (i = 0 ; i < max ; i++) {
1506 if ( contains_bbox(x0,y0,x2,y2,r)) {
1510 } else if (contains_bbox(x2,y0,x4,y2,r)) {
1514 } else if (contains_bbox(x0,y2,x2,y4,r)) {
1518 } else if (contains_bbox(x2,y2,x4,y4,r)) {
1528 tile_bbox(char *tile, struct rect *r)
1533 c.x=(r->l.x+r->h.x)/2;
1534 c.y=(r->l.y+r->h.y)/2;
1557 GHashTable *tile_hash;
1558 GHashTable *tile_hash2;
1561 tile_extend(char *tile, struct item_bin *ib, GList **tiles_list)
1563 struct tile_head *th=NULL;
1564 if (debug_tile(tile))
1565 fprintf(stderr,"Tile:Writing %d bytes to '%s' (%p,%p)\n", (ib->len+1)*4, tile, g_hash_table_lookup(tile_hash, tile), tile_hash2 ? g_hash_table_lookup(tile_hash2, tile) : NULL);
1567 th=g_hash_table_lookup(tile_hash2, tile);
1569 th=g_hash_table_lookup(tile_hash, tile);
1571 th=malloc(sizeof(struct tile_head)+ sizeof( char* ) );
1573 // strcpy(th->subtiles, tile);
1576 th->total_size_used=0;
1579 th->name=string_hash_lookup(tile);
1580 *th_get_subtile( th, 0 ) = th->name;
1583 g_hash_table_insert(tile_hash2, string_hash_lookup( th->name ), th);
1585 *tiles_list=g_list_append(*tiles_list, string_hash_lookup( th->name ) );
1587 if (debug_tile(tile))
1588 fprintf(stderr,"new '%s'\n", tile);
1590 th->total_size+=ib->len*4+4;
1591 if (debug_tile(tile))
1592 fprintf(stderr,"New total size of %s(%p):%d\n", th->name, th, th->total_size);
1593 g_hash_table_insert(tile_hash, string_hash_lookup( th->name ), th);
1597 tile_data_size(char *tile)
1599 struct tile_head *th;
1600 th=g_hash_table_lookup(tile_hash, tile);
1603 return th->total_size;
1607 merge_tile(char *base, char *sub)
1609 struct tile_head *thb, *ths;
1610 thb=g_hash_table_lookup(tile_hash, base);
1611 ths=g_hash_table_lookup(tile_hash, sub);
1614 if (debug_tile(base) || debug_tile(sub))
1615 fprintf(stderr,"merging '%s'(%p) (%d) with '%s'(%p) (%d)\n", base, thb, thb ? thb->total_size : 0, sub, ths, ths->total_size);
1618 g_hash_table_remove(tile_hash, sub);
1619 thb->name=string_hash_lookup(base);
1620 g_hash_table_insert(tile_hash, string_hash_lookup( thb->name ), thb);
1623 thb=realloc(thb, sizeof(struct tile_head)+( ths->num_subtiles+thb->num_subtiles ) * sizeof( char*) );
1624 assert(thb != NULL);
1625 memcpy( th_get_subtile( thb, thb->num_subtiles ), th_get_subtile( ths, 0 ), ths->num_subtiles * sizeof( char*) );
1626 thb->num_subtiles+=ths->num_subtiles;
1627 thb->total_size+=ths->total_size;
1628 g_hash_table_insert(tile_hash, string_hash_lookup( thb->name ), thb);
1629 g_hash_table_remove(tile_hash, sub);
1637 get_tiles_list_func(char *key, struct tile_head *th, GList **list)
1639 *list=g_list_prepend(*list, key);
1643 get_tiles_list(void)
1646 g_hash_table_foreach(tile_hash, (GHFunc)get_tiles_list_func, &ret);
1652 write_tile(char *key, struct tile_head *th, gpointer dummy)
1656 fprintf(stderr,"DEBUG: Writing %s\n", key);
1657 strcpy(buffer,"tiles/");
1660 strcat(buffer,".bin");
1662 f=fopen(buffer, "wb+");
1664 fwrite(th->data, th->size, 1, f);
1672 write_item(char *tile, struct item_bin *ib)
1674 struct tile_head *th;
1677 th=g_hash_table_lookup(tile_hash2, tile);
1679 th=g_hash_table_lookup(tile_hash, tile);
1681 if (th->process != 0 && th->process != 1) {
1682 fprintf(stderr,"error with tile '%s' of length %d\n", tile, strlen(tile));
1687 if (debug_tile(tile))
1688 fprintf(stderr,"Data:Writing %d bytes to '%s' (%p,%p)\n", (ib->len+1)*4, tile, g_hash_table_lookup(tile_hash, tile), tile_hash2 ? g_hash_table_lookup(tile_hash2, tile) : NULL);
1690 if (th->total_size_used+size > th->total_size) {
1691 fprintf(stderr,"Overflow in tile %s (used %d max %d item %d)\n", tile, th->total_size_used, th->total_size, size);
1695 memcpy(th->zip_data+th->total_size_used, ib, size);
1696 th->total_size_used+=size;
1698 fprintf(stderr,"no tile hash found for %s\n", tile);
1705 write_item_part(FILE *out, struct item_bin *orig, int first, int last)
1707 struct item_bin new;
1708 struct coord *c=(struct coord *)(orig+1);
1709 char *attr=(char *)(c+orig->clen/2);
1710 int attr_len=orig->len-orig->clen-2;
1712 new.type=orig->type;
1713 new.clen=(last-first+1)*2;
1714 new.len=new.clen+attr_len+2;
1716 fprintf(stderr,"first %d last %d type 0x%x len %d clen %d attr_len %d\n", first, last, new.type, new.len, new.clen, attr_len);
1718 fwrite(&new, sizeof(new), 1, out);
1719 fwrite(c+first, new.clen*4, 1, out);
1720 fwrite(attr, attr_len*4, 1, out);
1724 phase2(FILE *in, FILE *out)
1727 int i,ccount,last,ndref;
1728 struct item_bin *ib;
1729 struct node_item *ni;
1731 processed_nodes=processed_nodes_out=processed_ways=processed_relations=processed_tiles=0;
1733 while ((ib=read_item(in))) {
1735 fprintf(stderr,"type 0x%x len %d clen %d\n", ib->type, ib->len, ib->clen);
1738 c=(struct coord *)(ib+1);
1740 for (i = 0 ; i < ccount ; i++) {
1743 ni=node_item_get(ndref);
1745 fprintf(stderr,"ni=%p\n", ni);
1748 if (ni->ref_way > 1 && i != 0 && i != ccount-1 && item_is_street(*ib)) {
1749 write_item_part(out, ib, last, i);
1754 write_item_part(out, ib, last, ccount-1);
1762 phase34_process_file(int phase, FILE *in)
1764 struct item_bin *ib;
1769 while ((ib=read_item(in))) {
1770 if (ib->type < 0x80000000)
1774 bbox((struct coord *)(ib+1), ib->clen/2, &r);
1777 if (ib->type == type_street_n_lanes || ib->type == type_highway_city || ib->type == type_highway_land || ib->type == type_ramp)
1779 if (ib->type == type_street_3_city || ib->type == type_street_4_city || ib->type == type_street_3_land || ib->type == type_street_4_land)
1782 tile(&r, buffer, max);
1784 fprintf(stderr,"%s\n", buffer);
1787 tile_extend(buffer, ib, NULL);
1789 write_item(buffer, ib);
1794 struct item_bin item;
1796 struct attr_bin attr_order_limit;
1799 struct attr_bin attr_zipfile_ref;
1804 index_submap_add(int phase, struct tile_head *th, GList **tiles_list)
1806 struct index_item ii;
1807 int len=strlen(th->name);
1808 char index_tile[len+1];
1810 ii.min=(len > 4) ? len-4 : 0;
1812 strcpy(index_tile, th->name);
1818 tile_bbox(th->name, &ii.r);
1820 ii.item.len=sizeof(ii)/4-1;
1821 ii.item.type=type_submap;
1824 ii.attr_order_limit.len=2;
1825 ii.attr_order_limit.type=attr_order_limit;
1827 ii.attr_zipfile_ref.len=2;
1828 ii.attr_zipfile_ref.type=attr_zipfile_ref;
1829 ii.zipfile_ref=th->zipnum;
1832 tile_extend(index_tile, (struct item_bin *)&ii, tiles_list);
1834 write_item(index_tile, (struct item_bin *)&ii);
1836 unsigned int *c=(unsigned int *)ⅈ
1838 for (i = 0 ; i < sizeof(ii)/4 ; i++) {
1839 fprintf(stderr,"%08x ", c[i]);
1841 fprintf(stderr,"\n");
1846 add_tile_hash(struct tile_head *th)
1848 int idx,len,maxnamelen=0;
1852 g_hash_table_insert(tile_hash2, string_hash_lookup( th->name ), th);
1854 for( idx = 0; idx < th->num_subtiles; idx++ ) {
1856 data = th_get_subtile( th, idx );
1858 if (debug_tile(data) || debug_tile(th->name)) {
1859 fprintf(stderr,"Parent for '%s' is '%s'\n", *data, th->name);
1862 g_hash_table_insert(tile_hash2, *data, th);
1864 len = strlen( *data );
1866 if (len > maxnamelen) {
1875 create_tile_hash(void)
1877 struct tile_head *th;
1878 int len,maxnamelen=0;
1880 tile_hash2=g_hash_table_new(g_str_hash, g_str_equal);
1883 len=add_tile_hash(th);
1884 if (len > maxnamelen)
1892 create_tile_hash_list(GList *list)
1895 struct tile_head *th;
1897 tile_hash2=g_hash_table_new(g_str_hash, g_str_equal);
1899 fprintf(stderr,"list=%p\n", list);
1900 next=g_list_first(list);
1902 th=g_hash_table_lookup(tile_hash, next->data);
1904 fprintf(stderr,"No tile found for '%s'\n", (char *)(next->data));
1907 next=g_list_next(next);
1912 destroy_tile_hash(void)
1914 g_hash_table_destroy(tile_hash2);
1920 static void write_countrydir(int phase, int maxnamelen);
1923 write_tilesdir(int phase, int maxlen, FILE *out)
1926 GList *tiles_list,*next;
1928 struct tile_head *th,**last=NULL;
1931 tiles_list=get_tiles_list();
1933 create_tile_hash_list(tiles_list);
1934 next=g_list_first(tiles_list);
1935 last=&tile_head_root;
1938 if (strlen(next->data) > maxlen)
1939 maxlen=strlen(next->data);
1940 next=g_list_next(next);
1946 fprintf(stderr,"PROGRESS: collecting tiles with len=%d\n", len);
1948 #ifdef GENERATE_INDEX
1950 write_countrydir(phase, maxlen);
1952 next=g_list_first(tiles_list);
1954 if (strlen(next->data) == len) {
1955 th=g_hash_table_lookup(tile_hash, next->data);
1961 fprintf(out,"%s:%d",(char *)next->data,th->total_size);
1963 for ( idx = 0; idx< th->num_subtiles; idx++ ){
1964 data= th_get_subtile( th, idx );
1965 fprintf(out,":%s", *data);
1971 index_submap_add(phase, th, &tiles_list);
1975 next=g_list_next(next);
1984 struct tile_head *th;
1985 char basetile[1024];
1987 GList *tiles_list_sorted,*last;
1988 int i,i_min,len,size_all,size[5],size_min,work_done;
1992 tiles_list_sorted=get_tiles_list();
1993 fprintf(stderr,"PROGRESS: sorting %d tiles\n", g_list_length(tiles_list_sorted));
1994 tiles_list_sorted=g_list_sort(tiles_list_sorted, (GCompareFunc)strcmp);
1995 fprintf(stderr,"PROGRESS: sorting %d tiles done\n", g_list_length(tiles_list_sorted));
1996 last=g_list_last(tiles_list_sorted);
1999 th=g_hash_table_lookup(tile_hash, last->data);
2000 zip_size+=th->total_size;
2001 last=g_list_previous(last);
2003 fprintf(stderr,"DEBUG: size=%Ld\n", zip_size);
2004 last=g_list_last(tiles_list_sorted);
2008 len=strlen(last->data);
2010 strcpy(basetile,last->data);
2011 basetile[len-1]='\0';
2012 strcpy(subtile,last->data);
2013 for (i = 0 ; i < 4 ; i++) {
2014 subtile[len-1]='a'+i;
2015 size[i]=tile_data_size(subtile);
2017 size[4]=tile_data_size(basetile);
2018 size_all=size[0]+size[1]+size[2]+size[3]+size[4];
2019 if (size_all < 65536 && size_all > 0 && size_all != size[4]) {
2020 for (i = 0 ; i < 4 ; i++) {
2021 subtile[len-1]='a'+i;
2022 work_done+=merge_tile(basetile, subtile);
2028 for (i = 0 ; i < 4 ; i++) {
2029 if (size[i] && size[i] < size_min) {
2036 if (size[4]+size_min >= 65536)
2038 subtile[len-1]='a'+i_min;
2039 work_done+=merge_tile(basetile, subtile);
2040 size[4]+=size[i_min];
2045 last=g_list_previous(last);
2047 g_list_free(tiles_list_sorted);
2048 fprintf(stderr,"PROGRESS: merged %d tiles\n", work_done);
2049 } while (work_done);
2052 struct country_index_item {
2053 struct item_bin item;
2054 struct attr_bin attr_country_id;
2056 struct attr_bin attr_zipfile_ref;
2061 index_country_add(int phase, int country_id, int zipnum)
2063 struct country_index_item ii;
2064 char *index_tile="";
2066 ii.item.len=sizeof(ii)/4-1;
2067 ii.item.type=type_countryindex;
2070 ii.attr_country_id.len=2;
2071 ii.attr_country_id.type=attr_country_id;
2072 ii.country_id=country_id;
2074 ii.attr_zipfile_ref.len=2;
2075 ii.attr_zipfile_ref.type=attr_zipfile_ref;
2076 ii.zipfile_ref=zipnum;
2079 tile_extend(index_tile, (struct item_bin *)&ii, NULL);
2081 write_item(index_tile, (struct item_bin *)&ii);
2084 #ifdef GENERATE_INDEX
2092 add_aux_tile(int phase, char *name, char *filename, int size)
2094 struct aux_tile *at;
2096 at=g_new0(struct aux_tile, 1);
2097 at->name=g_strdup(name);
2098 at->filename=g_strdup(filename);
2100 aux_tile_list=g_list_append(aux_tile_list, at);
2106 write_aux_tiles(FILE *out, FILE *dir_out, int compression_level, int namelen)
2108 GList *l=aux_tile_list;
2109 struct aux_tile *at;
2116 buffer=malloc(at->size);
2117 assert(buffer != NULL);
2118 f=fopen(at->filename,"r");
2120 fread(buffer, at->size, 1, f);
2122 write_zipmember(out, dir_out, at->name, namelen, buffer, at->size, compression_level);
2130 write_countrydir(int phase, int maxnamelen)
2135 char searchtile[32];
2137 struct country_table *co;
2138 for (i = 0 ; i < sizeof(country_table)/sizeof(struct country_table) ; i++) {
2139 co=&country_table[i];
2142 tile(&co->r, tilename, max);
2143 sprintf(searchtile,"%ss%d", tilename, 0);
2144 sprintf(filename,"country_%d.bin", co->countryid);
2145 zipnum=add_aux_tile(phase, searchtile, filename, co->size);
2146 index_country_add(phase,co->countryid,zipnum);
2152 remove_countryfiles(void)
2156 struct country_table *co;
2158 for (i = 0 ; i < sizeof(country_table)/sizeof(struct country_table) ; i++) {
2159 co=&country_table[i];
2161 sprintf(filename,"country_%d.bin", co->countryid);
2169 phase34(int phase, int maxnamelen, FILE *ways_in, FILE *nodes_in, FILE *tilesdir_out)
2172 processed_nodes=processed_nodes_out=processed_ways=processed_relations=processed_tiles=0;
2176 tile_hash=g_hash_table_new(g_str_hash, g_str_equal);
2178 phase34_process_file(phase, ways_in);
2180 phase34_process_file(phase, nodes_in);
2181 fprintf(stderr,"read %d bytes\n", bytes_read);
2186 write_tilesdir(phase, maxnamelen, tilesdir_out);
2193 phase3(FILE *ways_in, FILE *nodes_in, FILE *tilesdir_out)
2195 return phase34(3, 0, ways_in, nodes_in, tilesdir_out);
2198 static long long zipoffset;
2199 static int zipdir_size;
2202 compress2_int(Byte *dest, uLongf *destLen, const Bytef *source, uLong sourceLen, int level)
2207 stream.next_in = (Bytef*)source;
2208 stream.avail_in = (uInt)sourceLen;
2209 stream.next_out = dest;
2210 stream.avail_out = (uInt)*destLen;
2211 if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
2213 stream.zalloc = (alloc_func)0;
2214 stream.zfree = (free_func)0;
2215 stream.opaque = (voidpf)0;
2217 err = deflateInit2(&stream, level, Z_DEFLATED, -15, 9, Z_DEFAULT_STRATEGY);
2218 if (err != Z_OK) return err;
2220 err = deflate(&stream, Z_FINISH);
2221 if (err != Z_STREAM_END) {
2222 deflateEnd(&stream);
2223 return err == Z_OK ? Z_BUF_ERROR : err;
2225 *destLen = stream.total_out;
2227 err = deflateEnd(&stream);
2232 write_zipmember(FILE *out, FILE *dir_out, char *name, int filelen, char *data, int data_size, int compression_level)
2234 struct zip_lfh lfh = {
2247 struct zip_cd cd = {
2268 char filename[filelen+1];
2269 int error,crc,len,comp_size=data_size;
2270 uLongf destlen=data_size+data_size/500+12;
2271 char compbuffer[destlen];
2273 crc=crc32(0, NULL, 0);
2274 crc=crc32(crc, (unsigned char *)data, data_size);
2275 if (compression_level) {
2276 error=compress2_int((Byte *)compbuffer, &destlen, (Bytef *)data, data_size, compression_level);
2277 if (error == Z_OK) {
2278 if (destlen < data_size) {
2283 fprintf(stderr,"compress2 returned %d\n", error);
2287 lfh.zipsize=comp_size;
2288 lfh.zipuncmp=data_size;
2289 lfh.zipmthd=compression_level ? 8:0;
2291 cd.zipcsiz=comp_size;
2292 cd.zipcunc=data_size;
2293 cd.zipcmthd=compression_level ? 8:0;
2294 strcpy(filename, name);
2295 len=strlen(filename);
2296 while (len < filelen) {
2297 filename[len++]='_';
2299 filename[filelen]='\0';
2300 fwrite(&lfh, sizeof(lfh), 1, out);
2301 fwrite(filename, filelen, 1, out);
2302 fwrite(data, comp_size, 1, out);
2303 zipoffset+=sizeof(lfh)+filelen+comp_size;
2304 fwrite(&cd, sizeof(cd), 1, dir_out);
2305 fwrite(filename, filelen, 1, dir_out);
2306 zipdir_size+=sizeof(cd)+filelen;
2310 process_slice(FILE *ways_in, FILE *nodes_in, int size, int maxnamelen, FILE *out, FILE *dir_out, int compression_level)
2312 struct tile_head *th;
2313 char *slice_data,*zip_data;
2316 slice_data=malloc(size);
2317 assert(slice_data != NULL);
2318 zip_data=slice_data;
2322 th->zip_data=zip_data;
2323 zip_data+=th->total_size;
2328 fseek(ways_in, 0, SEEK_SET);
2330 fseek(nodes_in, 0, SEEK_SET);
2331 phase34(4, maxnamelen, ways_in, nodes_in, NULL);
2336 #ifdef GENERATE_INDEX
2337 if (! strlen(th->name))
2338 zipfiles+=write_aux_tiles(out, dir_out, compression_level, maxnamelen);
2340 if (th->total_size != th->total_size_used) {
2341 fprintf(stderr,"Size error '%s': %d vs %d\n", th->name, th->total_size, th->total_size_used);
2344 if (strlen(th->name))
2345 write_zipmember(out, dir_out, th->name, maxnamelen, th->zip_data, th->total_size, compression_level);
2347 write_zipmember(out, dir_out, "index", sizeof("index")-1, th->zip_data, th->total_size, compression_level);
2360 cat(FILE *in, FILE *out)
2364 while ((size=fread(buffer, 1, 4096, in)))
2365 fwrite(buffer, 1, size, out);
2369 phase4(FILE *ways_in, FILE *nodes_in, FILE *out, FILE *dir_out, int compression_level)
2371 int slice_size=1024*1024*1024;
2372 int maxnamelen,size,slices;
2374 struct tile_head *th,*th2;
2375 struct zip_eoc eoc = {
2386 maxnamelen=create_tile_hash();
2391 fprintf(stderr, "Maximum slice size %d\n", slice_size);
2393 if (size + th->total_size > slice_size) {
2394 fprintf(stderr,"Slice %d is of size %d\n", slices, size);
2398 size+=th->total_size;
2402 fprintf(stderr,"Slice %d is of size %d\n", slices, size);
2413 while (th && size+th->total_size < slice_size) {
2414 size+=th->total_size;
2418 zipfiles+=process_slice(ways_in, nodes_in, size, maxnamelen, out, dir_out, compression_level);
2421 fseek(dir_out, 0, SEEK_SET);
2423 eoc.zipenum=zipfiles;
2424 eoc.zipecenn=zipfiles;
2425 eoc.zipecsz=zipdir_size;
2426 eoc.zipeofst=zipoffset;
2427 fwrite(&eoc, sizeof(eoc), 1, out);
2437 fprintf(f,"osm2navit - parse osm textfile and converts to NavIt binfile format\n\n");
2438 fprintf(f,"Usage :\n");
2439 fprintf(f,"bzcat planet.osm.bz2 | osm2navit mymap.bin\n");
2440 fprintf(f,"Available switches:\n");
2441 fprintf(f,"-h (--help) : this screen\n");
2442 fprintf(f,"-N (--nodes-only) : process only nodes\n");
2443 fprintf(f,"-W (--ways-only) : process only ways\n");
2444 fprintf(f,"-a (--attr-debug-level) : control which data is included in the debug attribute\n");
2445 fprintf(f,"-c (--dump-coordinates) : dump coordinates after phase 1\n");
2446 #ifdef HAVE_POSTGRESQL
2447 fprintf(f,"-d (--db) : get osm data out of a postgresql database with osm simple scheme and given connect string\n");
2449 fprintf(f,"-e (--end) : end at specified phase\n");
2450 fprintf(f,"-k (--keep-tmpfiles) : do not delete tmp files after processing. useful to reuse them\n\n");
2451 fprintf(f,"-o (--coverage) : map every street to item overage\n");
2452 fprintf(f,"-s (--start) : start at specified phase\n");
2453 fprintf(f,"-i (--input-file) : specify the input file name (OSM), overrules default stdin\n");
2454 fprintf(f,"-w (--dedupe-ways) : ensure no duplicate ways or nodes. useful when using several input files\n");
2455 fprintf(f,"-z (--compression-level) : set the compression level\n");
2459 int main(int argc, char **argv)
2461 FILE *ways=NULL,*ways_split=NULL,*nodes=NULL,*tilesdir,*zipdir,*res;
2462 char *map=g_strdup(attrmap);
2463 int c,start=1,end=4,dump_coordinates=0;
2464 int keep_tmpfiles=0;
2465 int process_nodes=1, process_ways=1;
2466 int compression_level=9;
2467 char *result,*dbstr=NULL;
2468 FILE* input_file = stdin;
2473 int this_option_optind = optind ? optind : 1;
2475 int option_index = 0;
2476 static struct option long_options[] = {
2477 {"attr-debug-level", 1, 0, 'a'},
2478 {"compression-level", 1, 0, 'z'},
2479 {"coverage", 0, 0, 'o'},
2480 #ifdef HAVE_POSTGRESQL
2483 {"dedupe-ways", 0, 0, 'w'},
2485 {"help", 0, 0, 'h'},
2486 {"keep-tmpfiles", 0, 0, 'k'},
2487 {"nodes-only", 0, 0, 'N'},
2488 {"start", 1, 0, 's'},
2489 {"input-file", 1, 0, 'i'},
2490 {"ignore-unknown", 0, 0, 'n'},
2491 {"ways-only", 0, 0, 'W'},
2494 c = getopt_long (argc, argv, "Nni:Wa:c"
2495 #ifdef HAVE_POSTGRESQL
2498 "e:hks:w", long_options, &option_index);
2509 attr_debug_level=atoi(optarg);
2514 #ifdef HAVE_POSTGRESQL
2526 fprintf(stderr,"I will IGNORE unknown types\n");
2530 fprintf(stderr,"I will KEEP tmp files\n");
2540 dedupe_ways_hash=g_hash_table_new(NULL, NULL);
2543 input_file = fopen( optarg, "r" );
2544 if ( input_file == NULL )
2546 fprintf( stderr, "\nInput file (%s) not found\n", optarg );
2551 compression_level=atoi(optarg);
2557 fprintf(stderr,"c=%d\n", c);
2561 if (optind != argc-1)
2563 result=argv[optind];
2565 #ifdef GENERATE_INDEX
2566 build_countrytable();
2572 ways=fopen("ways.tmp","wb+");
2574 nodes=fopen("nodes.tmp","wb+");
2576 fprintf(stderr,"PROGRESS: Phase 1: collecting data\n");
2577 #ifdef HAVE_POSTGRESQL
2579 phase1_db(dbstr,ways,nodes);
2582 phase1(input_file,ways,nodes);
2587 #ifdef GENERATE_INDEX
2588 fprintf(stderr,"PROGRESS: Phase 1: sorting countries\n");
2592 if (end == 1 || dump_coordinates)
2593 save_buffer("coords.tmp",&node_buffer);
2597 load_buffer("coords.tmp",&node_buffer);
2600 ways=fopen("ways.tmp","rb");
2601 ways_split=fopen("ways_split.tmp","wb+");
2603 fprintf(stderr,"PROGRESS: Phase 2: finding intersections\n");
2604 phase2(ways,ways_split);
2610 fprintf(stderr,"PROGRESS: Skipping Phase 2\n");
2612 free(node_buffer.base);
2613 node_buffer.base=NULL;
2614 node_buffer.malloced=0;
2620 fprintf(stderr,"PROGRESS: Phase 3: generating tiles\n");
2622 ways_split=fopen("ways_split.tmp","rb");
2624 nodes=fopen("nodes.tmp","rb");
2625 tilesdir=fopen("tilesdir.tmp","wb+");
2626 phase3(ways_split,nodes,tilesdir);
2637 fprintf(stderr,"PROGRESS: Phase 4: assembling map\n");
2639 ways_split=fopen("ways_split.tmp","rb");
2641 nodes=fopen("nodes.tmp","rb");
2642 res=fopen(result,"wb+");
2643 zipdir=fopen("zipdir.tmp","wb+");
2644 phase4(ways_split,nodes,res,zipdir,compression_level);
2651 if(!keep_tmpfiles) {
2652 remove("nodes.tmp");
2653 remove("ways_split.tmp");
2654 remove("tilesdir.tmp");
2655 remove("zipdir.tmp");
2656 #ifdef GENERATE_INDEX
2657 remove_countryfiles();