/* * OSM-NAVI * OpenStreetMap navigation on the Linux framebuffer console. * Renders vector tiles from a local PMTiles planet file onto * /dev/fb0, geocodes with Nominatim and routes with the public * OSRM server. Runs in a tmux pane or directly on the VT console * with an embedded 8x16 Terminus font. Writes gated on the active * VT and clipped to the tmux pane. * Dependencies: libcurl, zlib, libzstd, stb_image.h (bundled). * GPS: connects to gpsd on localhost:2947, auto-follows position. * * TILES * OSM_PMTILES path to the planet file * default /var/lib/maps/world.pmtiles * Zoom 0-15 comes from the local file. If the file is missing * the classic raster tile cache and the OSM tile server are used. * * PLACES * Own places live in /etc/osmnavi/places.tsv, one line * LATLONNAME. Key a adds the map center. * * USAGE * osmnavi * osmnavi -p walking * osmnavi route LAT1 LON1 LAT2 LON2 * osmnavi sim LAT1 LON1 LAT2 LON2 * osmnavi find NAME [LAT LON] * osmnavi buildindex [ZOOM] * osmnavi offroute LAT1 LON1 LAT2 LON2 * osmnavi names Z X Y * osmnavi places * osmnavi place LAT LON NAME * osmnavi tile Z X Y OUT.ppm * arrows pan * +/- zoom in / out * g geocode a place (Nominatim) * s set start * d set destination * r route from start to destination (OSRM) * n/p next / previous route step * f auto-follow GPS position * a add place at center * i simulate route * , . slower / faster simulation * ? help * q quit * * AUTHOR * Written by osmnavi contributors. */ #define _GNU_SOURCE #include #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "fontdata.h" typedef unsigned char uchar; typedef unsigned int uint; typedef unsigned long ulong; #define TILE 256 #define MAXSTEPS 128 #define NPATH 4096 #define TILECAP 192 #define NHASH 4096 #define NWORK 4 #define MAXVIS 64 #define KEYUP 0x1e1 #define KEYDOWN 0x1e2 #define KEYLEFT 0x1e3 #define KEYRIGHT 0x1e4 #define LABMAX 24 typedef struct Lab Lab; struct Lab { char name[44]; int x, y; int kind; }; #define NAVBFMAX 24 typedef struct BFoot BFoot; struct BFoot { short n; short x[NAVBFMAX]; short y[NAVBFMAX]; unsigned char h; }; typedef struct Tile Tile; struct Tile { int x, y, z; uchar *px; int w, h; Tile *hnext; Tile *next, *prev; Lab lab[LABMAX]; int nlab; BFoot *bf; int nbf; }; static void panclamp(void); static ulong tkey(int x, int y, int z); static void drawplaces(void); static void navpaint(void); static int offlinefind(char *q, double *lat, double *lon, char *name, int max); static int offlineroute(double la0, double lo0, double la1, double lo1); static void roadlayer(uchar *d, ulong n, int tx, int ty); static int matchrank(char *hay, char *q); static int maxzoom(void); static void texttr(int x, int y, char *s, uint fg); static int paneactive(void); static void labbeg(void); static void drawlabels(Tile *t, int sx, int sy); static char *jstr(char *a, char *b, char *key, char *out, int max); typedef struct Req Req; struct Req { int x, y, z; Req *next; }; typedef struct Key Key; struct Key { ulong k; Key *next; }; typedef struct Step Step; struct Step { char instr[160]; char name[64]; double dist, dur; double lat, lon; }; static FB fb; static int vw, vh, cellh; static struct { double x, y; int z; } cam; static double slat, slon; static double dlat, dlon; static int hasstart, hasdst; static char startname[128], dstname[128]; static char msg[160]; static double plat[NPATH], plon[NPATH]; static int npath; static double dist, dur; static Step steps[MAXSTEPS]; static int ns, step; static char *profile; static char prompt[256]; static int inprompt; static volatile int running = 1; static int wake[2]; static struct termios origterm; static Tile *thash[NHASH]; static Key *pend[NHASH]; static Tile lruhead; static int ntile; static pthread_mutex_t tlok = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t tlcd = PTHREAD_COND_INITIALIZER; static Req *qhead, *qtail; static int nvis; static struct { int x, y, z; } vis[MAXVIS]; static int showhelp; static int navview; static double navtilt; static double gps_lat, gps_lon, gps_track, gps_speed; static int gps_valid; static int autofollow; #define MAXPLACES 256 typedef struct Place Place; struct Place { char name[64]; double lat, lon; }; static Place places[MAXPLACES]; static int nplaces; static int promptmode; static int simon; static double simdist; static double simspeed = 27.8; static double pcum[NPATH]; static double stepcum[MAXSTEPS]; static double lntopx(double lon, int z) { return (lon + 180) / 360 * (double)(1 << z) * TILE; } static double lattopy(double lat, int z) { double s; s = sin(lat * M_PI / 180); return (0.5 - log((1 + s) / (1 - s)) / (4 * M_PI)) * (double)(1 << z) * TILE; } static double pxtolon(double px, int z) { return px / ((double)(1 << z) * TILE) * 360 - 180; } static double pytolat(double py, int z) { double n; n = M_PI - 2 * M_PI * py / ((double)(1 << z) * TILE); return 180 / M_PI * atan(sinh(n)); } static void sproj(double px, double py, int *sx, int *sy) { *sx = fb.ox + (int)(px - cam.x) + vw / 2; *sy = fb.oy + (int)(py - cam.y) + vh / 2; } static void panesize(void) { fb_viewportpane(&fb); cellh = fb_cellh(&fb); vw = fb.vw; vh = fb.vh - 2 * cellh; if(vh < 2 * cellh) vh = 2 * cellh; fb.vh = vh; } static int vtactive(void) { return fb_vt_active(); } static void rawmode(void) { struct termios t; tcgetattr(0, &origterm); t = origterm; t.c_lflag &= ~(ECHO | ICANON | ISIG); t.c_cc[VMIN] = 0; t.c_cc[VTIME] = 0; tcsetattr(0, TCSAFLUSH, &t); } static void cleanup(void) { fb_hook_remove(); tcsetattr(0, TCSAFLUSH, &origterm); printf("\033[?25h"); fflush(stdout); fb_close(&fb); } static void sighandler(int sig) { (void)sig; running = 0; } static void pix(int x, int y, uint c) { fb_pixel(&fb, x, y, c); } static void fillrect(int x0, int y0, int x1, int y1, uint c) { fb_fill(&fb, x0, y0, x1, y1, c); } static void blittile(Tile *t, int dx, int dy) { fb_blit(&fb, dx, dy, t->w, t->h, t->px); } static void line(int x0, int y0, int x1, int y1, uint c) { int dx, dy, sx, sy, err, e2; dx = abs(x1 - x0); dy = -abs(y1 - y0); sx = x0 < x1 ? 1 : -1; sy = y0 < y1 ? 1 : -1; err = dx + dy; for(;;){ pix(x0, y0, c); if(x0 == x1 && y0 == y1) break; e2 = 2 * err; if(e2 >= dy){ err += dy; x0 += sx; } if(e2 <= dx){ err += dx; y0 += sy; } } } static void disc(int cx, int cy, int rad, uint c) { int x, y; for(y = -rad; y <= rad; y++) for(x = -rad; x <= rad; x++) if(x * x + y * y <= rad * rad) pix(cx + x, cy + y, c); } static void text(int x, int y, char *s, uint fg, uint bg) { int r, c, cp, gid; uchar bits, *p, *d; uint b, g, red; b = bg & 0xff; g = (bg >> 8) & 0xff; red = (bg >> 16) & 0xff; p = (uchar *)s; while(*p && x + 8 <= fb.ox + fb.w){ if(*p < 0x80){ cp = *p++; }else if(*p >= 0xc2 && *p <= 0xdf && p[1]){ cp = ((*p & 0x1f) << 6) | (p[1] & 0x3f); p += 2; }else if(*p >= 0xe0 && *p <= 0xef && p[1] && p[2]){ cp = ((*p & 0x0f) << 12) | ((p[1] & 0x3f) << 6) | (p[2] & 0x3f); p += 3; }else if(*p >= 0xf0 && *p <= 0xf4 && p[1] && p[2] && p[3]){ cp = ((*p & 0x07) << 18) | ((p[1] & 0x3f) << 12) | ((p[2] & 0x3f) << 6) | (p[3] & 0x3f); p += 4; }else{ cp = '?'; p++; } gid = glyphof(cp); if(gid < 0) gid = '?'; for(r = 0; r < 16; r++){ bits = fontdata[gid][r]; if(y + r < fb.oy || y + r >= fb.oy + vh) continue; for(c = 0; c < 8; c++){ int px; px = x + c; if(px < fb.ox || px >= fb.ox + fb.w) continue; d = fb.map + (ulong)(y + r) * fb.line + (ulong)px * 4; if(bits & (0x80 >> c)){ d[0] = fg & 0xff; d[1] = (fg >> 8) & 0xff; d[2] = (fg >> 16) & 0xff; d[3] = 0xff; }else{ d[0] = b; d[1] = g; d[2] = red; d[3] = 0xff; } } } x += 8; } } static void drawpath(void) { int i, x0, y0, x1, y1, sx, sy; if(npath < 2) return; sproj(lntopx(plon[0], cam.z), lattopy(plat[0], cam.z), &x0, &y0); for(i = 1; i < npath; i++){ sproj(lntopx(plon[i], cam.z), lattopy(plat[i], cam.z), &x1, &y1); line(x0 - 1, y0, x1 - 1, y1, 0x00ff6600); line(x0, y0, x1, y1, 0x00ff6600); line(x0 + 1, y0, x1 + 1, y1, 0x00ff6600); x0 = x1; y0 = y1; } for(i = 0; i < ns; i++){ if(steps[i].lat == 0 && steps[i].lon == 0) continue; sproj(lntopx(steps[i].lon, cam.z), lattopy(steps[i].lat, cam.z), &sx, &sy); if(i == step) disc(sx, sy, 6, 0x0000ffff); else disc(sx, sy, 4, 0x0000aaff); } } static void drawpos(void) { int x, y; double px, py; if(!gps_valid) return; px = lntopx(gps_lon, cam.z); py = lattopy(gps_lat, cam.z); sproj(px, py, &x, &y); disc(x, y, 6, 0x000040ff); disc(x, y, 3, 0x000080ff); } static void drawmarks(void) { int x, y; if(hasstart){ sproj(lntopx(slon, cam.z), lattopy(slat, cam.z), &x, &y); disc(x, y, 5, 0x00008000); } if(hasdst){ sproj(lntopx(dlon, cam.z), lattopy(dlat, cam.z), &x, &y); disc(x, y, 5, 0x000000ff); } } static void drawplaces(void) { int i, x, y; for(i = 0; i < nplaces; i++){ sproj(lntopx(places[i].lon, cam.z), lattopy(places[i].lat, cam.z), &x, &y); if(x < fb.ox - 8 || y < fb.oy - 8 || x > fb.ox + vw + 8 || y > fb.oy + vh + 8) continue; disc(x, y, 5, 0x000060ff); disc(x, y, 2, 0x00ffffff); if(cam.z >= 11) texttr(x + 7, y - 8, places[i].name, 0x00204080); } } static void drawstatus(void) { char l1[320], l2[320]; int y0; double clat, clon; if(vh < 3 * cellh) return; y0 = fb.oy + vh - 2 * cellh; fillrect(fb.ox, y0, fb.ox + fb.w, y0 + 2 * cellh, 0x00303030); clat = pytolat(cam.y, cam.z); clon = pxtolon(cam.x, cam.z); if(inprompt){ snprintf(l1, sizeof l1, "%s: %s_", promptmode ? "place" : "search", prompt); l2[0] = 0; }else{ snprintf(l1, sizeof l1, "osmnavi z=%d %0.5f %0.5f %s%s%s", cam.z, clat, clon, msg, autofollow ? " [follow]" : "", simon ? " [SIM]" : ""); if(gps_valid) snprintf(l1 + strlen(l1), sizeof l1 - strlen(l1), " GPS: %.5f %.5f", gps_lat, gps_lon); if(hasstart && hasdst) snprintf(l2, sizeof l2, "%s -> %s", startname, dstname); else if(hasstart) snprintf(l2, sizeof l2, "start: %s", startname); else if(hasdst) snprintf(l2, sizeof l2, "dest: %s", dstname); else snprintf(l2, sizeof l2, "Enter/ g search s start r route i drive"); if(ns > 0 && step >= 0 && step < ns) snprintf(l2 + strlen(l2), sizeof l2 - strlen(l2), " %d/%d %s (%s) %.0fm", step + 1, ns, steps[step].instr, steps[step].name, steps[step].dist); else if(npath > 1) snprintf(l2 + strlen(l2), sizeof l2 - strlen(l2), " %.1f km, %d min", dist / 1000.0, (int)(dur / 60)); } text(fb.ox + 4, y0 + 1, l1, 0x00dddddd, 0x00303030); text(fb.ox + 4, y0 + cellh + 1, l2, 0x00bbbbbb, 0x00303030); } static void setvis(void) { double px0, py0; int i0, i1, j0, j1, i, j, n, c; px0 = cam.x - vw / 2.0; py0 = cam.y - vh / 2.0; i0 = (int)floor(px0 / TILE); i1 = (int)floor((px0 + vw - 1) / TILE); j0 = (int)floor(py0 / TILE); j1 = (int)floor((py0 + vh - 1) / TILE); n = 1 << cam.z; if(i0 < 0) i0 = 0; if(j0 < 0) j0 = 0; if(i1 > n - 1) i1 = n - 1; if(j1 > n - 1) j1 = n - 1; c = 0; for(j = j0; j <= j1; j++) for(i = i0; i <= i1; i++) if(c < MAXVIS){ vis[c].x = i; vis[c].y = j; vis[c].z = cam.z; c++; } nvis = c; } static Tile * tfindlocked(int x, int y, int z) { ulong k; Tile *t; k = tkey(x, y, z); for(t = thash[k % NHASH]; t; t = t->hnext) if(tkey(t->x, t->y, t->z) == k) return t; return NULL; } static void drawhelp(void) { static char *lines[] = { "keys:", " arrows pan map", " + - zoom in/out", " g search place (Nominatim)", " a add place at center", " i simulate route", " , . sim slower / faster", " s set start at center", " d set dest at center", " r route start -> dest", " n p next / prev step", " f toggle auto-follow GPS", " ? this help", " q quit", }; int nlines, pw, ph, px, py, i, y; nlines = sizeof lines / sizeof lines[0]; pw = 40 * 8; ph = (nlines + 2) * 16; px = fb.ox + (vw - pw) / 2; py = fb.oy + (vh - ph) / 2; if(px < fb.ox) px = fb.ox; if(py < fb.oy) py = fb.oy; fillrect(px, py, px + pw, py + ph, 0x00101010); line(px, py, px + pw, py, 0x00606060); line(px, py + ph - 1, px + pw, py + ph - 1, 0x00606060); line(px, py, px, py + ph, 0x00606060); line(px + pw - 1, py, px + pw - 1, py + ph, 0x00606060); y = py + 16; for(i = 0; i < nlines; i++){ text(px + 8, y, lines[i], 0x00cccccc, 0x00101010); y += 16; } } static void renderframe(void) { int i, sx, sy; Tile *t; if(!vtactive()) return; if(navview){ navpaint(); fb_snapshot(&fb); return; } if(autofollow && gps_valid){ cam.x = lntopx(gps_lon, cam.z); cam.y = lattopy(gps_lat, cam.z); panclamp(); setvis(); } pthread_mutex_lock(&tlok); labbeg(); for(i = 0; i < nvis; i++){ t = tfindlocked(vis[i].x, vis[i].y, vis[i].z); sx = fb.ox + vis[i].x * TILE - (int)cam.x + vw / 2; sy = fb.oy + vis[i].y * TILE - (int)cam.y + vh / 2; if(t){ blittile(t, sx, sy); drawlabels(t, sx, sy); }else fillrect(sx, sy, sx + TILE, sy + TILE, 0x00d0d0d0); } pthread_mutex_unlock(&tlok); drawpath(); drawmarks(); drawplaces(); drawpos(); drawstatus(); if(showhelp) drawhelp(); fb_snapshot(&fb); } static int pendhas(ulong k) { Key *p; for(p = pend[k % NHASH]; p; p = p->next) if(p->k == k) return 1; return 0; } static void pendadd(ulong k) { Key *p; p = malloc(sizeof *p); if(p == NULL) return; p->k = k; p->next = pend[k % NHASH]; pend[k % NHASH] = p; } static void penddel(ulong k) { Key **pp = &pend[k % NHASH]; while(*pp){ if((*pp)->k == k){ Key *q = *pp; *pp = q->next; free(q); return; } pp = &(*pp)->next; } } static void lrurem(Tile *t) { t->next->prev = t->prev; t->prev->next = t->next; t->next = t->prev = NULL; } static void lruput(Tile *t) { t->prev = &lruhead; t->next = lruhead.next; lruhead.next->prev = t; lruhead.next = t; } static Tile * ehdel(Tile *h, ulong k) { Tile **pp = &h; while(*pp){ if(tkey((*pp)->x, (*pp)->y, (*pp)->z) == k){ *pp = (*pp)->hnext; break; } pp = &(*pp)->next; } return h; } static void tinsert(Tile *t) { Tile *e; ulong k; k = tkey(t->x, t->y, t->z); t->hnext = thash[k % NHASH]; thash[k % NHASH] = t; lruput(t); ntile++; while(ntile > TILECAP){ e = lruhead.prev; if(e == &lruhead) break; lrurem(e); k = tkey(e->x, e->y, e->z); thash[k % NHASH] = ehdel(thash[k % NHASH], k); free(e->px); free(e->bf); free(e); ntile--; } } static void tilewant(int x, int y, int z) { ulong k; Req *r; k = tkey(x, y, z); pthread_mutex_lock(&tlok); if(tfindlocked(x, y, z) != NULL || pendhas(k)) goto out; pendadd(k); r = malloc(sizeof *r); if(r == NULL){ penddel(k); goto out; } r->x = x; r->y = y; r->z = z; r->next = NULL; if(qtail) qtail->next = r; else qhead = r; qtail = r; pthread_cond_signal(&tlcd); out: pthread_mutex_unlock(&tlok); } static void wanttiles(void) { int i; for(i = 0; i < nvis; i++) tilewant(vis[i].x, vis[i].y, vis[i].z); } static double distm(double la1, double lo1, double la2, double lo2) { double p, dp, dl, a; p = M_PI / 180; dp = (la2 - la1) * p; dl = (lo2 - lo1) * p; a = sin(dp / 2) * sin(dp / 2) + cos(la1 * p) * cos(la2 * p) * sin(dl / 2) * sin(dl / 2); return 6371000.0 * 2 * atan2(sqrt(a), sqrt(1 - a)); } static void placepath(void) { int i; pcum[0] = 0; for(i = 1; i < npath; i++) pcum[i] = pcum[i - 1] + distm(plat[i - 1], plon[i - 1], plat[i], plon[i]); for(i = 0; i < ns; i++){ int j, best; double bd, d; best = 0; bd = 1e18; for(j = 0; j < npath; j++){ d = distm(steps[i].lat, steps[i].lon, plat[j], plon[j]); if(d < bd){ bd = d; best = j; } } stepcum[i] = pcum[best]; } } static char * placefile(void) { return "/etc/osmnavi/places.tsv"; } static void placeload(void) { FILE *f; char line[256]; nplaces = 0; f = fopen(placefile(), "r"); if(f == NULL) return; while(fgets(line, sizeof line, f) != NULL && nplaces < MAXPLACES){ char *t1, *t2; line[strcspn(line, "\n")] = 0; t1 = strchr(line, '\t'); if(t1 == NULL) continue; *t1++ = 0; t2 = strchr(t1, '\t'); if(t2 == NULL) continue; *t2++ = 0; places[nplaces].lat = strtod(line, NULL); places[nplaces].lon = strtod(t1, NULL); snprintf(places[nplaces].name, sizeof places[nplaces].name, "%s", t2); if(places[nplaces].name[0]) nplaces++; } fclose(f); } static int placesave(char *name, double lat, double lon) { FILE *f; mkdir("/etc/osmnavi", 0755); f = fopen(placefile(), "a"); if(f == NULL) return -1; fprintf(f, "%0.6f\t%0.6f\t%s\n", lat, lon, name); fclose(f); placeload(); return 0; } static int placefind(char *q, double *lat, double *lon, char *name, int max) { int i; for(i = 0; i < nplaces; i++){ if(strcasecmp(places[i].name, q) == 0){ *lat = places[i].lat; *lon = places[i].lon; snprintf(name, max, "%.63s", places[i].name); return 0; } } return -1; } static void addplace(char *name) { double lat, lon; lat = pytolat(cam.y, cam.z); lon = pxtolon(cam.x, cam.z); if(placesave(name, lat, lon) != 0){ snprintf(msg, sizeof msg, "cannot write place"); return; } snprintf(msg, sizeof msg, "place %s added", name); } static void simtick(void) { int i; double f, seg; if(!simon) return; simdist += simspeed * 0.1; if(simdist >= pcum[npath - 1]){ simdist = pcum[npath - 1]; simon = 0; snprintf(msg, sizeof msg, "sim end"); } for(i = 1; i < npath; i++){ if(pcum[i] >= simdist){ seg = pcum[i] - pcum[i - 1]; f = seg > 0 ? (simdist - pcum[i - 1]) / seg : 0; gps_lat = plat[i - 1] + f * (plat[i] - plat[i - 1]); gps_lon = plon[i - 1] + f * (plon[i] - plon[i - 1]); gps_track = atan2(lntopx(plon[i], 15) - lntopx(plon[i - 1], 15), lattopy(plat[i - 1], 15) - lattopy(plat[i], 15)) * 180 / M_PI; if(gps_track < 0) gps_track += 360; break; } } gps_valid = 1; while(step < ns - 1 && simdist >= stepcum[step + 1]) step++; if(autofollow){ cam.x = lntopx(gps_lon, cam.z); cam.y = lattopy(gps_lat, cam.z); panclamp(); setvis(); wanttiles(); } } static void simstart(void) { if(npath < 2){ snprintf(msg, sizeof msg, "route first (r)"); return; } placepath(); simdist = 0; step = 0; simon = 1; autofollow = 1; navview = 1; cam.z = maxzoom(); simtick(); snprintf(msg, sizeof msg, "sim %.0f km/h", simspeed * 3.6); } static int paneactive(void) { return fb_pane_active(); } static ulong tkey(int x, int y, int z) { return ((ulong)z << 38) | ((ulong)x << 19) | (ulong)y; } typedef struct Mem Mem; struct Mem { uchar *data; ulong size; }; static size_t memcb(void *ptr, size_t sz, size_t nm, void *user) { size_t total = sz * nm; Mem *m = user; uchar *p; p = realloc(m->data, m->size + total + 1); if(p == NULL) return 0; memcpy(p + m->size, ptr, total); m->size += total; p[m->size] = 0; m->data = p; return total; } static uchar * httpget(char *url, long timeout, ulong *n) { CURL *c; Mem m; CURLcode r; memset(&m, 0, sizeof m); c = curl_easy_init(); if(c == NULL) return NULL; curl_easy_setopt(c, CURLOPT_URL, url); curl_easy_setopt(c, CURLOPT_WRITEFUNCTION, memcb); curl_easy_setopt(c, CURLOPT_WRITEDATA, &m); curl_easy_setopt(c, CURLOPT_USERAGENT, "osmnavi/0.1"); curl_easy_setopt(c, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt(c, CURLOPT_CONNECTTIMEOUT, timeout / 2); curl_easy_setopt(c, CURLOPT_TIMEOUT, timeout); r = curl_easy_perform(c); curl_easy_cleanup(c); if(r != CURLE_OK){ free(m.data); return NULL; } *n = m.size; return m.data; } static int tileurl(char *buf, int max, int x, int y, int z) { return snprintf(buf, max, "https://tile.openstreetmap.org/%d/%d/%d.png", z, x, y); } static void cachedir(char *buf, int max) { char *h; h = getenv("HOME"); if(h == NULL || h[0] == 0) h = "/root"; snprintf(buf, max, "%s/.cache/osm-navi", h); } static void mkcachedirs(int x, int y, int z) { char dir[256]; (void)y; cachedir(dir, sizeof dir); mkdir(dir, 0755); snprintf(dir + strlen(dir), sizeof dir - strlen(dir), "/%d", z); mkdir(dir, 0755); snprintf(dir + strlen(dir), sizeof dir - strlen(dir), "/%d", x); mkdir(dir, 0755); } static void diskpath(char *buf, int max, int x, int y, int z) { char dir[256]; cachedir(dir, sizeof dir); snprintf(buf, max, "%s/%d/%d/%d.png", dir, z, x, y); } static int savefile(char *path, uchar *data, ulong n) { int fd, w; fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644); if(fd < 0) return -1; w = write(fd, data, n); close(fd); return w == (int)n ? 0 : -1; } typedef struct Ent Ent; struct Ent { ulong id; ulong run; ulong len; ulong off; }; typedef struct Pmt Pmt; struct Pmt { int fd; ulong size; ulong rootoff, rootlen; ulong leafoff, leaflen; ulong tileoff, tilelen; int minz, maxz; Ent *root; int nroot; }; static Pmt pmt; static pthread_mutex_t pmtok = PTHREAD_MUTEX_INITIALIZER; static int pmtready; static int isgz(uchar *b, ulong n) { return n >= 2 && b[0] == 0x1f && b[1] == 0x8b; } static int iszs(uchar *b, ulong n) { return n >= 4 && b[0] == 0x28 && b[1] == 0xb5 && b[2] == 0x2f && b[3] == 0xfd; } static uchar * unpack(uchar *in, ulong n, ulong *outn) { z_stream z; uchar *out; ulong cap; unsigned long long sz; if(n == 0 || (!isgz(in, n) && !iszs(in, n))){ out = malloc(n + 1); if(out == NULL) return NULL; memcpy(out, in, n); out[n] = 0; *outn = n; return out; } if(iszs(in, n)){ sz = ZSTD_getFrameContentSize(in, n); if(sz == ZSTD_CONTENTSIZE_UNKNOWN || sz == ZSTD_CONTENTSIZE_ERROR) return NULL; out = malloc(sz + 1); if(out == NULL) return NULL; sz = ZSTD_decompress(out, sz, in, n); if(ZSTD_isError(sz)){ free(out); return NULL; } out[sz] = 0; *outn = sz; return out; } cap = n * 6 + 4096; out = malloc(cap + 1); if(out == NULL) return NULL; memset(&z, 0, sizeof z); if(inflateInit2(&z, 15 + 16) != Z_OK){ free(out); return NULL; } z.next_in = in; z.avail_in = n; for(;;){ z.next_out = out + z.total_out; z.avail_out = cap - z.total_out; if(inflate(&z, Z_NO_FLUSH) == Z_STREAM_END) break; if(z.avail_out == 0){ cap *= 2; out = realloc(out, cap + 1); if(out == NULL){ inflateEnd(&z); return NULL; } }else if(z.avail_in == 0) break; } *outn = z.total_out; out[*outn] = 0; inflateEnd(&z); return out; } static int preadall(int fd, void *buf, ulong n, ulong off) { uchar *p; ssize_t r; p = buf; while(n > 0){ r = pread(fd, p, n, off); if(r <= 0) return -1; p += r; off += r; n -= r; } return 0; } static uchar * slurp(Pmt *p, ulong off, ulong len, ulong *outn) { uchar *raw, *out; if(len == 0 || len > 64UL * 1024 * 1024) return NULL; raw = malloc(len); if(raw == NULL) return NULL; if(preadall(p->fd, raw, len, off) != 0){ free(raw); return NULL; } out = unpack(raw, len, outn); free(raw); return out; } static ulong getvar(uchar *b, ulong n, ulong *i) { ulong v, s; uchar c; v = 0; s = 0; while(*i < n){ c = b[(*i)++]; v |= (ulong)(c & 0x7f) << s; if((c & 0x80) == 0) break; s += 7; } return v; } static Ent * readdir(Pmt *p, ulong off, ulong len, int *count) { uchar *d; ulong n, i, k, j, last, val; Ent *e; d = slurp(p, off, len, &n); if(d == NULL) return NULL; i = 0; k = getvar(d, n, &i); if(k == 0 || k > 2000000){ free(d); return NULL; } e = malloc(sizeof(Ent) * k); if(e == NULL){ free(d); return NULL; } last = 0; for(j = 0; j < k; j++){ last += getvar(d, n, &i); e[j].id = last; } for(j = 0; j < k; j++) e[j].run = getvar(d, n, &i); for(j = 0; j < k; j++) e[j].len = getvar(d, n, &i); for(j = 0; j < k; j++){ val = getvar(d, n, &i); if(val == 0 && j > 0) e[j].off = e[j - 1].off + e[j - 1].len; else e[j].off = val - 1; } *count = k; free(d); return e; } static void rotrc(ulong n, ulong *x, ulong *y, ulong rx, ulong ry) { ulong t; if(ry == 0){ if(rx == 1){ *x = n - 1 - *x; *y = n - 1 - *y; } t = *x; *x = *y; *y = t; } } static ulong hilbert(ulong n, ulong x, ulong y) { ulong d, s, rx, ry; d = 0; for(s = n / 2; s > 0; s /= 2){ rx = (x & s) ? 1 : 0; ry = (y & s) ? 1 : 0; d += s * s * ((3 * rx) ^ ry); rotrc(s, &x, &y, rx, ry); } return d; } static ulong tileid(int z, int x, int y) { ulong acc; int k; acc = 0; for(k = 0; k < z; k++) acc += 1UL << (2 * k); return acc + hilbert(1UL << z, (ulong)x, (ulong)y); } static Ent * efind(Ent *e, int n, ulong id) { int lo, hi, mid; Ent *best; best = NULL; lo = 0; hi = n - 1; while(lo <= hi){ mid = (lo + hi) / 2; if(e[mid].id <= id){ best = &e[mid]; lo = mid + 1; }else hi = mid - 1; } return best; } static uchar * ptile(Pmt *p, int z, int x, int y, ulong *len) { ulong id, n, dlen; Ent *e, *leaf, cur; int nl; if(z < p->minz || z > p->maxz) return NULL; id = tileid(z, x, y); e = efind(p->root, p->nroot, id); for(n = 0; e != NULL && e->run == 0 && n < 8; n++){ leaf = readdir(p, p->leafoff + e->off, e->len, &nl); if(leaf == NULL) return NULL; Ent *ne = efind(leaf, nl, id); if(ne != NULL) cur = *ne; free(leaf); e = ne == NULL ? NULL : &cur; } if(e == NULL || e->run == 0) return NULL; dlen = e->len; return slurp(p, p->tileoff + e->off, dlen, len); } static int pmtopen(Pmt *p, char *path) { uchar h[127]; ulong a, b; memset(p, 0, sizeof *p); p->fd = open(path, O_RDONLY); if(p->fd < 0) return -1; p->size = lseek(p->fd, 0, SEEK_END); if(preadall(p->fd, h, sizeof h, 0) != 0) return -1; if(memcmp(h, "PMTiles", 7) != 0 || h[7] != 3) return -1; memcpy(&a, h + 8, 8); memcpy(&b, h + 16, 8); p->rootoff = a; p->rootlen = b; memcpy(&a, h + 40, 8); memcpy(&b, h + 48, 8); p->leafoff = a; p->leaflen = b; memcpy(&a, h + 56, 8); memcpy(&b, h + 64, 8); p->tileoff = a; p->tilelen = b; p->minz = h[100]; p->maxz = h[101]; p->root = readdir(p, p->rootoff, p->rootlen, &p->nroot); return p->root == NULL ? -1 : 0; } static void pmtinit(void) { char *p; if(pmtready) return; p = getenv("OSM_PMTILES"); if(p == NULL || p[0] == 0) p = "/var/lib/maps/world.pmtiles"; pthread_mutex_lock(&pmtok); if(!pmtready && pmtopen(&pmt, p) == 0) pmtready = 1; pthread_mutex_unlock(&pmtok); } #define MVMAX 32768 #define MVRMAX 1024 #define MVKL 512 #define MVVL 512 static int mvx[MVMAX], mvy[MVMAX]; static int mvrs[MVRMAX]; static int mvn, mvr; static int mvxs[MVMAX]; typedef struct MVal MVal; struct MVal { uchar *p; ulong l; long num; }; static int pbnext(uchar *d, ulong n, ulong *i, int *f, int *w, ulong *v, uchar **p, ulong *l) { ulong k; if(*i >= n) return 0; k = getvar(d, n, i); *f = k >> 3; *w = k & 7; *v = 0; *p = NULL; *l = 0; if(*f == 0) return 0; if(*w == 0){ *v = getvar(d, n, i); }else if(*w == 2){ *l = getvar(d, n, i); if(*i + *l > n) return 0; *p = d + *i; *i += *l; }else if(*w == 5){ if(*i + 4 > n) return 0; *i += 4; }else if(*w == 1){ if(*i + 8 > n) return 0; *i += 8; }else{ return 0; } return 1; } static int eqp(uchar *p, ulong n, char *s) { ulong i; if(p == NULL || n != strlen(s)) return 0; for(i = 0; i < n; i++) if(p[i] != (uchar)s[i]) return 0; return 1; } static void tput(uchar *b, int x, int y, uchar r, uchar g, uchar bl) { uchar *q; if(x < 0 || y < 0 || x >= TILE || y >= TILE) return; q = b + ((ulong)y * TILE + x) * 4; q[0] = r; q[1] = g; q[2] = bl; q[3] = 255; } static void tfill(uchar *b, int x0, int y0, int x1, int y1, uchar r, uchar g, uchar bl) { int x, y; if(x0 < 0) x0 = 0; if(y0 < 0) y0 = 0; if(x1 > TILE) x1 = TILE; if(y1 > TILE) y1 = TILE; for(y = y0; y < y1; y++) for(x = x0; x < x1; x++) tput(b, x, y, r, g, bl); } static void fillrings(uchar *b, int x0, int y0, int x1, int y1, uchar r, uchar g, uchar bl) { int y, k, a, c, xs, xa, xb; double yc, t, x; (void)x0; (void)x1; if(mvr == 0) return; for(y = y0; y <= y1; y++){ yc = y + 0.5; xs = 0; for(k = 0; k < mvr; k++){ a = mvrs[k]; c = k + 1 < mvr ? mvrs[k + 1] : mvn; for(; a < c; a++){ int j = a + 1 < c ? a + 1 : mvrs[k]; double ya = mvy[a], yb = mvy[j]; if((ya <= yc && yb > yc) || (yb <= yc && ya > yc)){ t = (yc - ya) / (yb - ya); x = mvx[a] + t * (mvx[j] - mvx[a]); if(xs < MVMAX) mvxs[xs++] = (int)(x * 16); } } } if(xs < 2) continue; for(a = 1; a < xs; a++){ int v = mvxs[a]; for(c = a - 1; c >= 0 && mvxs[c] > v; c--) mvxs[c + 1] = mvxs[c]; mvxs[c + 1] = v; } for(a = 0; a + 1 < xs; a += 2){ xa = mvxs[a] / 16; xb = (mvxs[a + 1] + 15) / 16; if(xb <= xa) continue; for(c = xa; c < xb; c++) tput(b, c, y, r, g, bl); } } } static void thick(uchar *b, int x0, int y0, int x1, int y1, double rad, uchar r, uchar g, uchar bl) { int x, y, ax, ay, bx, by; double dx, dy, l2, t, px, py, d2, rr; rr = rad * rad; ax = x0 < x1 ? x0 : x1; ay = y0 < y1 ? y0 : y1; bx = x0 > x1 ? x0 : x1; by = y0 > y1 ? y0 : y1; ax -= (int)rad + 1; ay -= (int)rad + 1; bx += (int)rad + 1; by += (int)rad + 1; dx = x1 - x0; dy = y1 - y0; l2 = dx * dx + dy * dy; for(y = ay; y <= by; y++) for(x = ax; x <= bx; x++){ px = x - x0; py = y - y0; if(l2 > 0){ t = (px * dx + py * dy) / l2; if(t < 0) t = 0; if(t > 1) t = 1; px -= t * dx; py -= t * dy; } d2 = px * px + py * py; if(d2 <= rr) tput(b, x, y, r, g, bl); } } static void polyline(uchar *b, int a, int c, double rad, uchar r, uchar g, uchar bl) { int i; for(i = a; i + 1 < c; i++) thick(b, mvx[i], mvy[i], mvx[i + 1], mvy[i + 1], rad, r, g, bl); } typedef struct Lay Lay; struct Lay { char name[24]; uchar *d; ulong n; }; typedef struct RSty RSty; struct RSty { double w; uchar r, g, b; uchar cr, cg, cb; }; static void roadsty(uchar *k, ulong kl, int z, RSty *s) { s->w = 1.4; s->r = 255; s->g = 255; s->b = 255; s->cr = 206; s->cg = 201; s->cb = 195; if(k == NULL) return; if(kl >= 8 && memcmp(k, "motorway", 8) == 0){ s->w = 5.0; s->r = 247; s->g = 183; s->b = 110; s->cr = 222; s->cg = 160; s->cb = 96; }else if(kl >= 5 && memcmp(k, "trunk", 5) == 0){ s->w = 4.2; s->r = 249; s->g = 198; s->b = 126; s->cr = 224; s->cg = 172; s->cb = 108; }else if(kl >= 7 && memcmp(k, "primary", 7) == 0){ s->w = 3.6; s->r = 250; s->g = 214; s->b = 152; s->cr = 226; s->cg = 190; s->cb = 132; }else if(kl >= 9 && memcmp(k, "secondary", 9) == 0){ s->w = 3.0; s->r = 251; s->g = 233; s->b = 186; s->cr = 228; s->cg = 210; s->cb = 168; }else if(kl >= 8 && memcmp(k, "tertiary", 8) == 0){ s->w = 2.6; s->r = 255; s->g = 255; s->b = 255; }else if(kl >= 5 && memcmp(k, "minor", 5) == 0){ s->w = 2.0; }else if(eqp(k, kl, "residential") || eqp(k, kl, "unclassified") || eqp(k, kl, "street") || eqp(k, kl, "major_road")){ s->w = 2.0; }else if(eqp(k, kl, "service")){ s->w = 1.2; s->r = 246; s->g = 244; s->b = 240; }else if(kl >= 4 && (memcmp(k, "path", 4) == 0 || eqp(k, kl, "track") || eqp(k, kl, "footway") || eqp(k, kl, "cycleway") || eqp(k, kl, "pedestrian") || eqp(k, kl, "steps") || eqp(k, kl, "bridleway"))){ s->w = 0.8; s->cr = 206; s->cg = 196; s->cb = 176; s->r = 214; s->g = 204; s->b = 184; }else if(kl >= 3 && memcmp(k, "rail", 4) == 0){ s->w = 1.0; s->cr = 180; s->cg = 178; s->cb = 176; s->r = 190; s->g = 188; s->b = 186; } if(z >= 14) s->w += 0.8; else if(z <= 7) s->w *= 0.7; if(s->w < 0.8) s->w = 0.8; } static void landsty(uchar *k, ulong kl, uchar *r, uchar *g, uchar *b) { *r = 231; *g = 228; *b = 219; if(k == NULL) return; if(eqp(k, kl, "park") || eqp(k, kl, "forest") || eqp(k, kl, "wood") || eqp(k, kl, "grass") || eqp(k, kl, "meadow") || eqp(k, kl, "nature_reserve") || eqp(k, kl, "scrub") || eqp(k, kl, "heath") || eqp(k, kl, "fell") || eqp(k, kl, "moor") || eqp(k, kl, "orchard") || eqp(k, kl, "vineyard") || eqp(k, kl, "farmland") || eqp(k, kl, "grassland")){ *r = 201; *g = 226; *b = 189; }else if(eqp(k, kl, "residential") || eqp(k, kl, "neighbourhood")){ *r = 234; *g = 231; *b = 225; }else if(eqp(k, kl, "industrial") || eqp(k, kl, "railway") || eqp(k, kl, "military") || eqp(k, kl, "aerodrome")){ *r = 230; *g = 226; *b = 222; }else if(eqp(k, kl, "commercial") || eqp(k, kl, "retail")){ *r = 236; *g = 229; *b = 233; }else if(eqp(k, kl, "cemetery")){ *r = 214; *g = 226; *b = 209; }else if(eqp(k, kl, "pitch") || eqp(k, kl, "stadium") || eqp(k, kl, "playground") || eqp(k, kl, "garden")){ *r = 208; *g = 229; *b = 194; }else if(eqp(k, kl, "allotments")){ *r = 208; *g = 229; *b = 195; }else if(eqp(k, kl, "school") || eqp(k, kl, "hospital") || eqp(k, kl, "university") || eqp(k, kl, "college")){ *r = 236; *g = 233; *b = 222; }else if(eqp(k, kl, "parking") || eqp(k, kl, "pedestrian")){ *r = 231; *g = 228; *b = 223; }else if(eqp(k, kl, "beach") || eqp(k, kl, "sand")){ *r = 240; *g = 233; *b = 206; }else if(eqp(k, kl, "wetland") || eqp(k, kl, "glacier")){ *r = 219; *g = 229; *b = 231; } } static int pkind(uchar *k, ulong kl) { if(k == NULL) return 0; if(eqp(k, kl, "city")) return 1; if(eqp(k, kl, "town")) return 2; if(eqp(k, kl, "village") || eqp(k, kl, "hamlet")) return 3; if(eqp(k, kl, "suburb") || eqp(k, kl, "quarter")) return 4; if(eqp(k, kl, "neighbourhood") || eqp(k, kl, "borough")) return 5; if(eqp(k, kl, "locality") || eqp(k, kl, "isolated_dwelling")) return 6; return 7; } static int labvis(int kind, int z) { if(kind == 1) return z >= 2; if(kind == 2) return z >= 6; if(kind == 3) return z >= 9; if(kind == 4) return z >= 11; if(kind == 5) return z >= 12; if(kind == 6) return z >= 9; return z >= 12; } static void featgeom(uchar *g, ulong gn, int ext) { ulong i, v; int cmd, cnt, k; long ux, uy; int dx, dy, s; mvn = 0; mvr = 0; ux = 0; uy = 0; i = 0; while(i < gn){ v = getvar(g, gn, &i); cmd = v & 7; cnt = v >> 3; if(cmd == 7) continue; if(cmd != 1 && cmd != 2) break; for(k = 0; k < cnt && i < gn; k++){ v = getvar(g, gn, &i); dx = (int)(v >> 1) ^ -(int)(v & 1); v = getvar(g, gn, &i); dy = (int)(v >> 1) ^ -(int)(v & 1); ux += dx; uy += dy; if(cmd == 1 && mvr < MVRMAX) mvrs[mvr++] = mvn; if(mvn >= MVMAX) break; s = (int)((ux * TILE + ext / 2) / ext); mvx[mvn] = s; s = (int)((uy * TILE + ext / 2) / ext); mvy[mvn] = s; mvn++; } } } static void bboxof(int *x0, int *y0, int *x1, int *y1) { int i; *x0 = *x1 = mvx[0]; *y0 = *y1 = mvy[0]; for(i = 1; i < mvn; i++){ if(mvx[i] < *x0) *x0 = mvx[i]; if(mvx[i] > *x1) *x1 = mvx[i]; if(mvy[i] < *y0) *y0 = mvy[i]; if(mvy[i] > *y1) *y1 = mvy[i]; } } static void featdraw(uchar *b, int type, int z, int mode, uchar *k, ulong kl) { int i, x0, y0, x1, y1; uchar r, g, bl; RSty s; if(mvn == 0) return; if(mode == 0){ if(type == 3){ bboxof(&x0, &y0, &x1, &y1); fillrings(b, x0, y0, x1, y1, 166, 199, 222); return; } if(type == 2){ double w; w = 1.5; if(k != NULL && eqp(k, kl, "river")) w = 2.5; else if(k != NULL && eqp(k, kl, "canal")) w = 1.4; else if(k != NULL && (eqp(k, kl, "stream") || eqp(k, kl, "ditch") || eqp(k, kl, "drain"))) w = 0.8; for(i = 0; i < mvr; i++){ int a = mvrs[i]; int c = i + 1 < mvr ? mvrs[i + 1] : mvn; polyline(b, a, c, w / 2, 150, 186, 214); } } return; } if(mode == 1){ if(type != 3) return; landsty(k, kl, &r, &g, &bl); bboxof(&x0, &y0, &x1, &y1); fillrings(b, x0, y0, x1, y1, r, g, bl); return; } if(mode == 4){ if(type != 3) return; bboxof(&x0, &y0, &x1, &y1); fillrings(b, x0, y0, x1, y1, 214, 206, 199); for(i = 0; i < mvr; i++){ int a = mvrs[i]; int c = i + 1 < mvr ? mvrs[i + 1] : mvn; int j; for(j = a; j < c; j++){ int n = j + 1 < c ? j + 1 : a; thick(b, mvx[j], mvy[j], mvx[n], mvy[n], 0.5, 198, 190, 183); } } return; } if(mode == 2 || mode == 3){ if(type != 2) return; roadsty(k, kl, z, &s); for(i = 0; i < mvr; i++){ int a = mvrs[i]; int c = i + 1 < mvr ? mvrs[i + 1] : mvn; if(mode == 2) polyline(b, a, c, s.w / 2 + 0.7, s.cr, s.cg, s.cb); else polyline(b, a, c, s.w / 2, s.r, s.g, s.b); } return; } } static void labstore(Lab *lab, int *nlab, uchar *name, ulong nl, int kind) { Lab *l; ulong i, cut; if(name == NULL || nl == 0 || *nlab >= LABMAX) return; l = &lab[*nlab]; cut = nl; if(cut > sizeof l->name - 1) cut = sizeof l->name - 1; for(i = cut; i > 0 && (name[i] & 0xc0) == 0x80; i--) ; if(i > 0) cut = i; memcpy(l->name, name, cut); l->name[cut] = 0; l->kind = kind; l->x = mvx[0]; l->y = mvy[0]; (*nlab)++; } static void rendlay(Lay *ly, uchar *b, int z, int mode, Lab *lab, int *nlab) { uchar *d, *kp[MVKL], *vp[MVVL]; ulong n, i, kl[MVKL], vl[MVVL]; long vn[MVVL]; int nk, nv, f, w, ext; ulong v; uchar *p; ulong l; d = ly->d; n = ly->n; nk = 0; nv = 0; ext = 4096; i = 0; while(pbnext(d, n, &i, &f, &w, &v, &p, &l)){ if(f == 3 && w == 2){ if(nk < MVKL){ kp[nk] = p; kl[nk] = l; nk++; } }else if(f == 4 && w == 2){ if(nv < MVVL){ MVal mv; ulong j; int ff, ww; ulong vv; uchar *pp; ulong ll; memset(&mv, 0, sizeof mv); j = 0; while(pbnext(p, l, &j, &ff, &ww, &vv, &pp, &ll)){ if(ff == 1 && ww == 2){ mv.p = pp; mv.l = ll; }else if(ff == 5 && ww == 0){ mv.num = (long)vv; }else if(ff == 6 && ww == 0){ mv.num = (long)(vv >> 1) ^ -(long)(vv & 1); }else if(ff == 4 && ww == 0){ mv.num = (long)(int)vv; }else if(ff == 7 && ww == 0){ mv.num = (long)vv; } } vp[nv] = mv.p; vl[nv] = mv.l; vn[nv] = mv.num; nv++; } }else if(f == 5 && w == 0 && v > 0){ ext = (int)v; } } i = 0; while(pbnext(d, n, &i, &f, &w, &v, &p, &l)){ uchar *gd, *tg, *name, *kind, *kd; ulong gn, tgn, nml, kindl, kdl, ti; int type; ulong j; int ff, ww; ulong vv; uchar *pp; ulong ll; if(f != 2 || w != 2) continue; gd = NULL; tg = NULL; gn = 0; tgn = 0; type = 0; kind = NULL; kindl = 0; kd = NULL; kdl = 0; name = NULL; nml = 0; j = 0; while(pbnext(p, l, &j, &ff, &ww, &vv, &pp, &ll)){ if(ff == 3 && ww == 0) type = (int)vv; else if(ff == 4 && ww == 2){ gd = pp; gn = ll; }else if(ff == 2 && ww == 2){ tg = pp; tgn = ll; } } if(gd == NULL || type == 0) continue; featgeom(gd, gn, ext); if(mvn == 0) continue; ti = 0; while(ti < tgn){ ulong ki, vi; ki = getvar(tg, tgn, &ti); if(ti >= tgn) break; vi = getvar(tg, tgn, &ti); if(ki >= (ulong)nk || vi >= (ulong)nv) continue; if(vp[vi] == NULL) continue; if(eqp(kp[ki], kl[ki], "kind") || eqp(kp[ki], kl[ki], "class") || eqp(kp[ki], kl[ki], "pmap:kind")){ kind = vp[vi]; kindl = vl[vi]; }else if(eqp(kp[ki], kl[ki], "kind_detail")){ kd = vp[vi]; kdl = vl[vi]; }else if(eqp(kp[ki], kl[ki], "name")){ name = vp[vi]; nml = vl[vi]; } } if(mode == 5){ if(type == 1 && name != NULL) labstore(lab, nlab, name, nml, pkind(kind, kindl)); continue; } featdraw(b, type, z, mode, kd != NULL ? kd : kind, kd != NULL ? kdl : kindl); } (void)vn; } static int numtag(uchar *v, ulong vl) { double d; if(v == NULL || vl == 0) return -1; d = atof((char *)v); if(d < 1 || d > 400) return -1; return (int)d; } static BFoot * buildlay(uchar *d, ulong n, int *nout) { uchar *kp[MVKL], *vp[MVVL]; ulong kl[MVKL], vl[MVVL]; BFoot *out; int nk, nv, f, w, cnt, r; ulong v, k; uchar *p; ulong l; *nout = 0; nk = nv = 0; cnt = 0; k = 0; while(pbnext(d, n, &k, &f, &w, &v, &p, &l)){ if(f == 2 && w == 2){ if(cnt < 4096) cnt++; }else if(f == 3 && w == 2 && nk < MVKL){ kp[nk] = p; kl[nk] = l; nk++; }else if(f == 4 && w == 2 && nv < MVVL){ ulong j; int ff, ww; ulong vv; uchar *pp; ulong ll; j = 0; vp[nv] = NULL; vl[nv] = 0; while(pbnext(p, l, &j, &ff, &ww, &vv, &pp, &ll)) if(ff == 1 && ww == 2){ vp[nv] = pp; vl[nv] = ll; } nv++; } } if(cnt == 0) return NULL; out = malloc(sizeof *out * 400); if(out == NULL) return NULL; k = 0; while(pbnext(d, n, &k, &f, &w, &v, &p, &l)){ uchar *gd, *tg; ulong gn, tgn, ti, j; int type, ff, ww, h, lv; ulong vv; uchar *pp; ulong ll; if(f != 2 || w != 2) continue; if(*nout >= 400) break; gd = tg = NULL; gn = tgn = 0; type = 0; j = 0; while(pbnext(p, l, &j, &ff, &ww, &vv, &pp, &ll)){ if(ff == 3 && ww == 0) type = (int)vv; else if(ff == 4 && ww == 2){ gd = pp; gn = ll; }else if(ff == 2 && ww == 2){ tg = pp; tgn = ll; } } if(type != 3 || gd == NULL) continue; h = -1; lv = -1; ti = 0; while(ti < tgn){ ulong ki, vi; ki = getvar(tg, tgn, &ti); if(ti >= tgn) break; vi = getvar(tg, tgn, &ti); if(ki >= (ulong)nk || vi >= (ulong)nv || vp[vi] == NULL) continue; if(eqp(kp[ki], kl[ki], "height")) h = numtag(vp[vi], vl[vi]); else if(eqp(kp[ki], kl[ki], "building:levels")) lv = numtag(vp[vi], vl[vi]); } if(h < 1 && lv > 0) h = lv * 3; if(h < 1) h = 8 + (int)(v % 9); if(h > 120) h = 120; featgeom(gd, gn, 4096); for(r = 0; r < mvr && *nout < 400; r++){ BFoot *bf; int st, en, cn, stride, q, minx, miny, maxx, maxy; st = mvrs[r]; en = r + 1 < mvr ? mvrs[r + 1] : mvn; cn = en - st; if(cn < 3) continue; stride = (cn + NAVBFMAX - 1) / NAVBFMAX; if(stride < 1) stride = 1; bf = &out[*nout]; bf->n = 0; for(q = 0; q < cn; q += stride){ bf->x[bf->n] = mvx[st + q]; bf->y[bf->n] = mvy[st + q]; bf->n++; } if(bf->n < 3) continue; minx = maxx = bf->x[0]; miny = maxy = bf->y[0]; for(q = 1; q < bf->n; q++){ if(bf->x[q] < minx) minx = bf->x[q]; if(bf->x[q] > maxx) maxx = bf->x[q]; if(bf->y[q] < miny) miny = bf->y[q]; if(bf->y[q] > maxy) maxy = bf->y[q]; } if((maxx - minx) * (maxy - miny) < 3) continue; bf->h = h; (*nout)++; } } if(*nout == 0){ free(out); return NULL; } return out; } static pthread_mutex_t geolok = PTHREAD_MUTEX_INITIALIZER; static uchar * rastertile1(int z, int x, int y, Lab *lab, int *nlab, BFoot **bfp, int *nbfp) { Lay lays[24]; Lay *rd; int nl, i, f, w; ulong v, k; uchar *p, *mvt, *b; ulong l, mn; *nlab = 0; *bfp = NULL; *nbfp = 0; if(!pmtready) return NULL; mvt = ptile(&pmt, z, x, y, &mn); if(mvt == NULL) return NULL; b = malloc((ulong)TILE * TILE * 4); if(b == NULL){ free(mvt); return NULL; } tfill(b, 0, 0, TILE, TILE, 242, 239, 233); nl = 0; k = 0; while(pbnext(mvt, mn, &k, &f, &w, &v, &p, &l)){ uchar *namep, *pp; ulong nlen, j, ll, vv; int ff, ww; Lay *ly; if(f != 3 || w != 2 || nl >= 24) continue; namep = NULL; nlen = 0; j = 0; while(pbnext(p, l, &j, &ff, &ww, &vv, &pp, &ll)){ if(ff == 1 && ww == 2){ namep = pp; nlen = ll; } } if(namep == NULL) continue; ly = &lays[nl++]; memset(ly, 0, sizeof *ly); if(nlen > sizeof ly->name - 1) nlen = sizeof ly->name - 1; memcpy(ly->name, namep, nlen); ly->d = p; ly->n = l; } for(i = 0; i < nl; i++) if(strcmp(lays[i].name, "water") == 0) rendlay(&lays[i], b, z, 0, lab, nlab); for(i = 0; i < nl; i++) if(strcmp(lays[i].name, "landuse") == 0) rendlay(&lays[i], b, z, 1, lab, nlab); for(i = 0; i < nl; i++) if(strcmp(lays[i].name, "buildings") == 0) rendlay(&lays[i], b, z, 4, lab, nlab); rd = NULL; for(i = 0; i < nl; i++) if(strcmp(lays[i].name, "roads") == 0) rd = &lays[i]; if(rd != NULL){ rendlay(rd, b, z, 2, lab, nlab); rendlay(rd, b, z, 3, lab, nlab); } for(i = 0; i < nl; i++) if(strcmp(lays[i].name, "places") == 0) rendlay(&lays[i], b, z, 5, lab, nlab); if(z >= 14) for(i = 0; i < nl; i++) if(strcmp(lays[i].name, "buildings") == 0){ *bfp = buildlay(lays[i].d, lays[i].n, nbfp); break; } free(mvt); return b; } static uchar * rastertile(int z, int x, int y, Lab *lab, int *nlab, BFoot **bfp, int *nbfp) { uchar *b; pthread_mutex_lock(&geolok); b = rastertile1(z, x, y, lab, nlab, bfp, nbfp); pthread_mutex_unlock(&geolok); return b; } static int labhx[128], labhy[128], labhn; static void labbeg(void) { labhn = 0; } static void texttr(int x, int y, char *s, uint fg) { int r, c, cp, gid; uchar bits, *p, *d; p = (uchar *)s; while(*p && x + 8 <= fb.ox + fb.w){ if(*p < 0x80){ cp = *p++; }else if(*p >= 0xc2 && *p <= 0xdf && p[1]){ cp = ((*p & 0x1f) << 6) | (p[1] & 0x3f); p += 2; }else if(*p >= 0xe0 && *p <= 0xef && p[1] && p[2]){ cp = ((*p & 0x0f) << 12) | ((p[1] & 0x3f) << 6) | (p[2] & 0x3f); p += 3; }else if(*p >= 0xf0 && *p <= 0xf4 && p[1] && p[2] && p[3]){ cp = ((*p & 0x07) << 18) | ((p[1] & 0x3f) << 12) | ((p[2] & 0x3f) << 6) | (p[3] & 0x3f); p += 4; }else{ cp = '?'; p++; } gid = glyphof(cp); if(gid < 0) gid = '?'; for(r = 0; r < 16; r++){ bits = fontdata[gid][r]; for(c = 0; c < 8; c++){ int px, py; px = x + c; py = y + r; if(px < fb.ox || px >= fb.ox + fb.w) continue; if(py < fb.oy || py >= fb.oy + vh) continue; d = fb.map + (ulong)py * fb.line + (ulong)px * 4; if(bits & (0x80 >> c)){ d[0] = fg & 0xff; d[1] = (fg >> 8) & 0xff; d[2] = (fg >> 16) & 0xff; d[3] = 0xff; } } } x += 8; } } static void drawlabels(Tile *t, int sx, int sy) { int i, j, x, y, len, ok; if(t->nlab <= 0) return; for(i = 0; i < t->nlab; i++){ if(!labvis(t->lab[i].kind, cam.z)) continue; len = (int)strlen(t->lab[i].name); x = sx + t->lab[i].x - len * 4; y = sy + t->lab[i].y - 8; if(x < fb.ox || y < fb.oy || x + len * 8 > fb.ox + vw || y + 16 > fb.oy + vh) continue; ok = 1; for(j = 0; j < labhn; j++){ int dx = labhx[j] - x; int dy = labhy[j] - y; if(dx > -40 && dx < 40 && dy > -12 && dy < 12){ ok = 0; break; } } if(!ok) continue; if(labhn < 128){ labhx[labhn] = x; labhy[labhn] = y; labhn++; } texttr(x - 1, y, t->lab[i].name, 0x00ffffff); texttr(x + 1, y, t->lab[i].name, 0x00ffffff); texttr(x, y - 1, t->lab[i].name, 0x00ffffff); texttr(x, y + 1, t->lab[i].name, 0x00ffffff); texttr(x, y, t->lab[i].name, 0x00302010); } } static Tile * tilefetch(int x, int y, int z) { Tile *t; uchar *png; ulong n; char path[1024], url[256]; t = malloc(sizeof *t); if(t == NULL) return NULL; memset(t, 0, sizeof *t); t->x = x; t->y = y; t->z = z; pmtinit(); if(pmtready){ t->px = rastertile(z, x, y, t->lab, &t->nlab, &t->bf, &t->nbf); if(t->px == NULL){ t->px = malloc((ulong)TILE * TILE * 4); if(t->px != NULL) tfill(t->px, 0, 0, TILE, TILE, 242, 239, 233); } if(t->px != NULL){ t->w = TILE; t->h = TILE; return t; } free(t); return NULL; } diskpath(path, sizeof path, x, y, z); t->px = stbi_load(path, &t->w, &t->h, NULL, 4); if(t->px) return t; if(tileurl(url, sizeof url, x, y, z) < 0){ free(t); return NULL; } png = httpget(url, 15, &n); if(png == NULL){ free(t); return NULL; } mkcachedirs(x, y, z); savefile(path, png, n); t->px = stbi_load_from_memory(png, n, &t->w, &t->h, NULL, 4); free(png); if(t->px == NULL){ free(t); return NULL; } return t; } static void * worker(void *arg) { (void)arg; Req *r; Tile *t; for(;;){ pthread_mutex_lock(&tlok); while(qhead == NULL && running) pthread_cond_wait(&tlcd, &tlok); if(!running){ pthread_mutex_unlock(&tlok); break; } r = qhead; qhead = r->next; if(qhead == NULL) qtail = NULL; pthread_mutex_unlock(&tlok); t = tilefetch(r->x, r->y, r->z); if(t){ pthread_mutex_lock(&tlok); penddel(tkey(r->x, r->y, r->z)); tinsert(t); pthread_mutex_unlock(&tlok); (void)write(wake[1], "w", 1); }else{ pthread_mutex_lock(&tlok); penddel(tkey(r->x, r->y, r->z)); pthread_mutex_unlock(&tlok); } free(r); } return NULL; } static int tcpsend(int fd, char *s) { return (int)write(fd, s, strlen(s)); } static void * gpsdthread(void *arg) { (void)arg; struct addrinfo hints, *res, *rp; int fd, n; char buf[4096], *p, *nl; for(;;){ memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if(getaddrinfo("127.0.0.1", "2947", &hints, &res) != 0) goto sleep; fd = -1; for(rp = res; rp; rp = rp->ai_next){ fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); if(fd < 0) continue; if(connect(fd, rp->ai_addr, rp->ai_addrlen) == 0) break; close(fd); fd = -1; } freeaddrinfo(res); if(fd < 0) goto sleep; tcpsend(fd, "?WATCH={\"enable\":true,\"json\":true}\n"); n = 0; for(;;){ struct pollfd pf; pf.fd = fd; pf.events = POLLIN; if(poll(&pf, 1, 5000) <= 0) continue; if(pf.revents & (POLLHUP | POLLERR)) break; if(n < (int)sizeof buf - 1){ int got; got = (int)read(fd, buf + n, sizeof buf - 1 - n); if(got <= 0) break; n += got; buf[n] = 0; } p = buf; while((nl = strchr(p, '\n')) != NULL){ *nl = 0; if(strstr(p, "\"class\":\"TPV\"")){ double lat, lon, track, speed; char latbuf[32], lonbuf[32]; latbuf[0] = 0; lonbuf[0] = 0; if(jstr(p, nl, "lat", latbuf, sizeof latbuf) != NULL && jstr(p, nl, "lon", lonbuf, sizeof lonbuf) != NULL){ lat = strtod(latbuf, NULL); lon = strtod(lonbuf, NULL); if((lat != 0.0 || lon != 0.0) && !simon){ gps_lat = lat; gps_lon = lon; gps_valid = 1; track = 0; speed = 0; { char tbuf[32], sbuf[32]; tbuf[0] = 0; sbuf[0] = 0; if(jstr(p, nl, "track", tbuf, sizeof tbuf) != NULL) track = strtod(tbuf, NULL); if(jstr(p, nl, "speed", sbuf, sizeof sbuf) != NULL) speed = strtod(sbuf, NULL); } gps_track = track; gps_speed = speed; (void)write(wake[1], "w", 1); } } } p = nl + 1; } n = (int)(p - buf); if(n > 0) memmove(buf, p, n); } close(fd); sleep: sleep(5); } return NULL; } static char * skipws(char *p) { while(*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r') p++; return p; } static char * jstr(char *a, char *b, char *key, char *out, int max) { char *p, *s, *e; int i, kl; kl = strlen(key); p = a; while(p < b){ s = strchr(p, '"'); if(s == NULL || s >= b) return NULL; e = strchr(s + 1, '"'); if(e == NULL || e > b) return NULL; if(e == s + 1 + kl && strncmp(s + 1, key, kl) == 0){ p = skipws(e + 1); if(p >= b || *p != ':') return NULL; p = skipws(p + 1); if(p >= b || *p != '"') return NULL; s = p + 1; i = 0; while(s < b && *s != '"'){ if(*s == '\\'){ if(s + 1 >= b) break; if(s[1] == 'n'){ if(i < max - 1) out[i++] = '\n'; }else if(s[1] == 't'){ if(i < max - 1) out[i++] = '\t'; }else if(i < max - 1) out[i++] = s[1]; s += 2; }else{ if(i < max - 1) out[i++] = *s; s++; } } out[i] = 0; return s; } p = e + 1; } return NULL; } static int jnum(char *a, char *b, char *key, double *out) { char *p, *s, *e; char buf[64]; int i, kl; kl = strlen(key); p = a; while(p < b){ s = strchr(p, '"'); if(s == NULL || s >= b) return -1; e = strchr(s + 1, '"'); if(e == NULL || e > b) return -1; if(e == s + 1 + kl && strncmp(s + 1, key, kl) == 0){ p = skipws(e + 1); if(p >= b || *p != ':') return -1; p = skipws(p + 1); i = 0; while(p < b && *p != ',' && *p != '}' && *p != ' ' && *p != '\t' && *p != '\n' && i < 63){ buf[i++] = *p++; } buf[i] = 0; if(i == 0) return -1; *out = strtod(buf, NULL); return 0; } p = e + 1; } return -1; } static char * jobj(char *p, char **st, char **en) { int depth = 0, instr = 0; p = strchr(p, '{'); if(p == NULL) return NULL; *st = p; while(*p){ if(instr){ if(*p == '\\') p++; else if(*p == '"') instr = 0; }else if(*p == '"'){ instr = 1; }else if(*p == '{'){ depth++; }else if(*p == '}'){ depth--; if(depth == 0){ *en = p; return p + 1; } } p++; } return NULL; } static int decodepoly(char *s, double *lat, double *lon, int max) { int shift, b, res, plat, plon, n; plat = 0; plon = 0; n = 0; while(*s){ shift = 0; res = 0; do{ b = (*s++) - 63; res |= (b & 0x1f) << shift; shift += 5; }while(b >= 0x20); plat += (res & 1) ? ~(res >> 1) : (res >> 1); shift = 0; res = 0; do{ b = (*s++) - 63; res |= (b & 0x1f) << shift; shift += 5; }while(b >= 0x20); plon += (res & 1) ? ~(res >> 1) : (res >> 1); if(n < max){ lat[n] = plat / 1e6; lon[n] = plon / 1e6; n++; } } return n; } static char * cardinal(double bear) { static char *d[] = { "North", "Northeast", "East", "Southeast", "South", "Southwest", "West", "Northwest" }; int i; i = (int)((bear + 22.5) / 45) % 8; return d[i]; } static void mkstepinstr(char *out, int max, char *type, char *mod, char *name, char *ref, double bear) { char on[128]; char md[16]; if(name[0] == 0 && ref[0]) snprintf(on, sizeof on, "%s", ref); else if(ref[0]) snprintf(on, sizeof on, "%s (%s)", name, ref); else snprintf(on, sizeof on, "%s", name); if(strcmp(mod, "left") == 0) strcpy(md, "left"); else if(strcmp(mod, "right") == 0) strcpy(md, "right"); else if(strcmp(mod, "slight left") == 0) strcpy(md, "slight left"); else if(strcmp(mod, "slight right") == 0) strcpy(md, "slight right"); else if(strcmp(mod, "sharp left") == 0) strcpy(md, "sharp left"); else if(strcmp(mod, "sharp right") == 0) strcpy(md, "sharp right"); else if(strcmp(mod, "straight") == 0) strcpy(md, "straight"); else if(strcmp(mod, "uturn") == 0) strcpy(md, "u-turn"); else strcpy(md, mod); if(strcmp(type, "depart") == 0) snprintf(out, max, "Head %s on %s", cardinal(bear), on); else if(strcmp(type, "arrive") == 0) snprintf(out, max, "Arrive: %s", on); else if(strcmp(type, "turn") == 0 || strcmp(type, "roundabout turn") == 0) snprintf(out, max, "Turn %s onto %s", md, on); else if(strcmp(type, "new name") == 0) snprintf(out, max, "Continue on %s", on); else if(strcmp(type, "continue") == 0){ if(strcmp(mod, "uturn") == 0) snprintf(out, max, "U-turn on %s", on); else snprintf(out, max, "Continue %s on %s", md, on); } else if(strcmp(type, "merge") == 0) snprintf(out, max, "Merge %s onto %s", md, on); else if(strcmp(type, "on ramp") == 0) snprintf(out, max, "On-ramp %s onto %s", md, on); else if(strcmp(type, "off ramp") == 0) snprintf(out, max, "Off-ramp %s onto %s", md, on); else if(strcmp(type, "fork") == 0) snprintf(out, max, "Keep %s, then onto %s", md, on); else if(strcmp(type, "end of road") == 0) snprintf(out, max, "At end of road %s onto %s", md, on); else if(strcmp(type, "roundabout") == 0 || strcmp(type, "rotary") == 0) snprintf(out, max, "Roundabout"); else if(strcmp(type, "exit roundabout") == 0 || strcmp(type, "exit rotary") == 0) snprintf(out, max, "Exit roundabout onto %s", on); else snprintf(out, max, "%s auf %s", type, on); } static char * jskiparr(char *p) { int depth = 0, instr = 0; p = strchr(p, '['); if(p == NULL) return NULL; while(*p){ if(instr){ if(*p == '\\') p++; else if(*p == '"') instr = 0; }else if(*p == '"'){ instr = 1; }else if(*p == '['){ depth++; }else if(*p == ']'){ depth--; if(depth == 0) return p + 1; } p++; } return NULL; } static int parseroute(char *h, ulong n) { char *s, *tmp, *rs, *rst, *ren, *lg, *after; char code[16]; int len, i; if(jstr(h, h + n, "code", code, sizeof code) == NULL || strcmp(code, "Ok") != 0) return -1; dist = 0; dur = 0; npath = 0; rs = strstr(h, "\"routes\":"); if(rs != NULL){ rs = skipws(rs + 9); if(jobj(rs, &rst, &ren) != NULL){ after = rst; lg = strstr(rst, "\"legs\":"); if(lg != NULL && lg < ren){ lg = skipws(lg + 7); after = jskiparr(lg); if(after == NULL) after = ren; } jnum(after, ren, "duration", &dur); jnum(after, ren, "distance", &dist); s = strstr(after, "\"geometry\":"); if(s != NULL && s < ren){ s = skipws(s + 11); if(*s == '"'){ s++; tmp = strchr(s, '"'); if(tmp != NULL){ len = tmp - s; if(len > 0 && len < NPATH * 16){ char *g; g = malloc(len + 1); if(g){ memcpy(g, s, len); g[len] = 0; npath = decodepoly(g, plat, plon, NPATH); free(g); } } } } } } } ns = 0; step = 0; s = strstr(h, "\"steps\":"); if(s != NULL){ s = skipws(s + 8); if(*s == '['){ char *arrend; arrend = jskiparr(s); s++; for(i = 0; i < MAXSTEPS; i++){ char *st, *en, *o, *mv, *mst, *men, *o2; char type[32], mod[32], ref[96]; double bear; type[0] = 0; mod[0] = 0; ref[0] = 0; if(arrend != NULL && s >= arrend) break; o = jobj(s, &st, &en); if(o == NULL) break; if(arrend != NULL && en >= arrend) break; steps[i].dist = 0; steps[i].dur = 0; jstr(st, en, "name", steps[i].name, sizeof steps[i].name); jstr(st, en, "ref", ref, sizeof ref); jnum(st, en, "distance", &steps[i].dist); jnum(st, en, "duration", &steps[i].dur); type[0] = 0; mod[0] = 0; bear = 0; mv = strstr(st, "\"maneuver\":"); if(mv != NULL && mv < en){ mv = skipws(mv + 11); o2 = jobj(mv, &mst, &men); if(o2 != NULL){ jstr(mst, men, "type", type, sizeof type); jstr(mst, men, "modifier", mod, sizeof mod); jnum(mst, men, "bearing_before", &bear); { char *loc; loc = strstr(mst, "\"location\":"); if(loc != NULL && loc < men){ char *la, *lb; la = strchr(loc, '['); if(la){ lb = strchr(la, ']'); if(lb){ char abuf[64]; int al; al = lb - la - 1; if(al > 0 && al < (int)sizeof abuf){ char *cm; memcpy(abuf, la+1, al); abuf[al] = 0; cm = strchr(abuf, ','); if(cm){ *cm = 0; steps[i].lon = strtod(abuf, NULL); steps[i].lat = strtod(cm+1, NULL); } } } } } } } } mkstepinstr(steps[i].instr, sizeof steps[i].instr, type, mod, steps[i].name, ref, bear); ns++; s = o; } } } return 0; } static int routefetch(void) { char url[512]; char *h; ulong n; int r; snprintf(url, sizeof url, "https://router.project-osrm.org/route/v1/%s/%0.6f,%0.6f;" "%0.6f,%0.6f?steps=true&overview=full&geometries=polyline6", profile, slon, slat, dlon, dlat); h = (char *)httpget(url, 30, &n); if(h != NULL){ r = parseroute(h, n); free(h); if(r == 0) return 0; } if(pmtready && offlineroute(slat, slon, dlat, dlon) == 0) return 0; return -1; } static void urlenc(char *s, char *d, int max) { static char hex[] = "0123456789ABCDEF"; int i = 0; while(*s && i < max - 4){ if((*s >= 'a' && *s <= 'z') || (*s >= 'A' && *s <= 'Z') || (*s >= '0' && *s <= '9') || *s == '-' || *s == '.' || *s == '_' || *s == '~'){ d[i++] = *s; }else{ d[i++] = '%'; d[i++] = hex[((uchar)*s >> 4) & 0xf]; d[i++] = hex[(uchar)*s & 0xf]; } s++; } d[i] = 0; } static int geoquery(char *q, double *lat, double *lon, char *name, int namelen) { char *h, *url, *enc; ulong n; char *st, *en, *o; char lb[32], lo[32]; int r = -1; enc = malloc(strlen(q) * 3 + 1); if(enc == NULL) return -1; urlenc(q, enc, strlen(q) * 3 + 1); url = malloc(strlen(enc) + 256); if(url == NULL){ free(enc); return -1; } sprintf(url, "https://nominatim.openstreetmap.org/search?q=%s" "&format=json&limit=1", enc); free(enc); h = (char *)httpget(url, 30, &n); free(url); if(h == NULL) return -1; o = jobj(h, &st, &en); if(o != NULL && jstr(st, en, "lat", lb, sizeof lb) != NULL && jstr(st, en, "lon", lo, sizeof lo) != NULL && jstr(st, en, "display_name", name, namelen) != NULL){ *lat = strtod(lb, NULL); *lon = strtod(lo, NULL); r = 0; } free(h); return r; } static void panclamp(void) { double ws = (double)(1 << cam.z) * TILE; if(cam.x < 0) cam.x = 0; if(cam.y < 0) cam.y = 0; if(cam.x > ws) cam.x = ws; if(cam.y > ws) cam.y = ws; } static void pan(int dx, int dy) { cam.x += dx; cam.y += dy; panclamp(); setvis(); wanttiles(); renderframe(); } static int maxzoom(void) { if(pmtready && pmt.maxz > 0) return pmt.maxz; return 19; } static void zoom(int dir) { double lat, lon; int maxz; lat = pytolat(cam.y, cam.z); lon = pxtolon(cam.x, cam.z); maxz = maxzoom(); if(dir > 0 && cam.z < maxz) cam.z++; else if(dir < 0 && cam.z > 0) cam.z--; else return; cam.x = lntopx(lon, cam.z); cam.y = lattopy(lat, cam.z); panclamp(); setvis(); wanttiles(); renderframe(); } static void setstart(void) { slat = pytolat(cam.y, cam.z); slon = pxtolon(cam.x, cam.z); hasstart = 1; snprintf(startname, sizeof startname, "%0.5f,%0.5f", slat, slon); snprintf(msg, sizeof msg, "start set"); renderframe(); } static void setdest(void) { dlat = pytolat(cam.y, cam.z); dlon = pxtolon(cam.x, cam.z); hasdst = 1; snprintf(dstname, sizeof dstname, "%0.5f,%0.5f", dlat, dlon); snprintf(msg, sizeof msg, "dest set"); renderframe(); } static void doroute(void) { if(!hasdst){ snprintf(msg, sizeof msg, "need dest (Enter/g)"); return; } if(!hasstart){ slat = pytolat(cam.y, cam.z); slon = pxtolon(cam.x, cam.z); snprintf(startname, sizeof startname, "Karte"); hasstart = 1; } snprintf(msg, sizeof msg, "routing..."); if(routefetch() != 0){ snprintf(msg, sizeof msg, "route failed"); }else{ if(!gps_valid && npath > 0){ gps_lat = plat[0]; gps_lon = plon[0]; gps_valid = 1; } navview = 1; autofollow = 1; cam.z = maxzoom(); if(gps_valid){ cam.x = lntopx(gps_lon, cam.z); cam.y = lattopy(gps_lat, cam.z); } setvis(); wanttiles(); snprintf(msg, sizeof msg, "route %.1f km, %d min, %d steps", dist / 1000.0, (int)(dur / 60), ns); } renderframe(); } static void dogeo(void) { double lat, lon; char name[160]; if(placefind(prompt, &lat, &lon, name, sizeof name) != 0 && offlinefind(prompt, &lat, &lon, name, sizeof name) != 0 && geoquery(prompt, &lat, &lon, name, sizeof name) != 0){ snprintf(msg, sizeof msg, "geocode failed: %s", prompt); return; } hasdst = 1; dlat = lat; dlon = lon; snprintf(dstname, sizeof dstname, "%.127s", name); cam.z = maxzoom(); cam.x = lntopx(lon, cam.z); cam.y = lattopy(lat, cam.z); panclamp(); setvis(); wanttiles(); renderframe(); if(hasstart) doroute(); } static void startprompt(int mode) { inprompt = 1; promptmode = mode; prompt[0] = 0; renderframe(); } static void promptchar(char c) { int n; n = strlen(prompt); if(c == '\n' || c == '\r'){ inprompt = 0; if(n > 0 && promptmode){ addplace(prompt); renderframe(); }else if(n > 0){ if(!hasstart){ slat = pytolat(cam.y, cam.z); slon = pxtolon(cam.x, cam.z); snprintf(startname, sizeof startname, "Karte"); hasstart = 1; } dogeo(); }else{ renderframe(); } return; } if(c == 0x1b){ inprompt = 0; renderframe(); return; } if(c == 0x7f || c == 0x08){ if(n > 0) prompt[--n] = 0; renderframe(); return; } if(c >= 0x20 && n < (int)sizeof prompt - 1){ prompt[n] = c; prompt[n + 1] = 0; } renderframe(); } static int getescape(char first) { uchar seq[4]; struct pollfd p; int n = 1; seq[0] = first; if(first == 0x1b){ p.fd = 0; p.events = POLLIN; if(poll(&p, 1, 30) > 0 && read(0, seq + n, 1) == 1){ n++; if(seq[1] == '[' && poll(&p, 1, 30) > 0 && read(0, seq + n, 1) == 1) n++; } } if(n == 3 && seq[0] == 0x1b && seq[1] == '['){ switch(seq[2]){ case 'A': return KEYUP; case 'B': return KEYDOWN; case 'C': return KEYRIGHT; case 'D': return KEYLEFT; } } return seq[0]; } static volatile sig_atomic_t redrawnow; static void usrsig(int sig) { (void)sig; redrawnow = 1; } #define RMAXN 300000 #define RMAXE 1200000 #define RHASH (1 << 19) static int rx[RMAXN], ry[RMAXN], rhead[RMAXN], rhnext[RMAXN]; static int rto[RMAXE], rnext[RMAXE]; static float rw[RMAXE]; static int rhash[RHASH]; static int rn, re; static double rmpp; static void rreset(void) { rn = 0; re = 0; memset(rhash, 0, sizeof rhash); } static int rnode(int x, int y) { int h, i; x >>= 1; y >>= 1; h = ((x * 73856093) ^ (y * 19349663)) & (RHASH - 1); for(i = rhash[h] - 1; i >= 0; i = rhnext[i]) if(rx[i] == x && ry[i] == y) return i; if(rn >= RMAXN) return -1; i = rn++; rx[i] = x; ry[i] = y; rhead[i] = -1; rhnext[i] = rhash[h] - 1; rhash[h] = i + 1; return i; } static void redge(int a, int b) { double dx, dy, w; if(a < 0 || b < 0 || a == b || re + 2 > RMAXE) return; dx = (rx[a] - rx[b]) * 2.0; dy = (ry[a] - ry[b]) * 2.0; w = sqrt(dx * dx + dy * dy) * rmpp; rto[re] = b; rw[re] = w; rnext[re] = rhead[a]; rhead[a] = re++; rto[re] = a; rw[re] = w; rnext[re] = rhead[b]; rhead[b] = re++; } static int roadok(uchar *k, ulong kl) { if(k == NULL) return 1; if(eqp(k, kl, "path") || eqp(k, kl, "track") || eqp(k, kl, "footway") || eqp(k, kl, "cycleway") || eqp(k, kl, "pedestrian") || eqp(k, kl, "steps") || eqp(k, kl, "rail") || eqp(k, kl, "ferry") || eqp(k, kl, "bridleway")) return 0; return 1; } static void roadtile(int z, int x, int y) { uchar *mvt; ulong mn, k; int f, w; ulong v; uchar *p; ulong l; mvt = ptile(&pmt, z, x, y, &mn); if(mvt == NULL) return; k = 0; while(pbnext(mvt, mn, &k, &f, &w, &v, &p, &l)){ uchar *np, *pp; ulong nl, j, ll, vv; int ff, ww; if(f != 3 || w != 2) continue; np = NULL; nl = 0; j = 0; while(pbnext(p, l, &j, &ff, &ww, &vv, &pp, &ll)) if(ff == 1 && ww == 2){ np = pp; nl = ll; } if(np == NULL || !eqp(np, nl, "roads")) continue; roadlayer(p, l, x, y); } free(mvt); } static void roadlayer(uchar *d, ulong n, int tx, int ty) { uchar *kp[MVKL], *vp[MVVL]; ulong kl[MVKL], vl[MVVL]; int nk, nv, f, w; ulong v, i; uchar *p; ulong l; nk = 0; nv = 0; i = 0; while(pbnext(d, n, &i, &f, &w, &v, &p, &l)){ if(f == 3 && w == 2 && nk < MVKL){ kp[nk] = p; kl[nk] = l; nk++; }else if(f == 4 && w == 2 && nv < MVVL){ ulong j = 0; int ff, ww; ulong vv; uchar *pp; ulong ll; vp[nv] = NULL; vl[nv] = 0; while(pbnext(p, l, &j, &ff, &ww, &vv, &pp, &ll)) if(ff == 1 && ww == 2){ vp[nv] = pp; vl[nv] = ll; } nv++; } } i = 0; while(pbnext(d, n, &i, &f, &w, &v, &p, &l)){ uchar *gd, *tg, *kind; ulong gn, tgn, kindl, ti, j; int type, ff, ww, a, b; ulong vv; uchar *pp; ulong ll; if(f != 2 || w != 2) continue; gd = tg = kind = NULL; gn = tgn = kindl = 0; type = 0; j = 0; while(pbnext(p, l, &j, &ff, &ww, &vv, &pp, &ll)){ if(ff == 3 && ww == 0) type = (int)vv; else if(ff == 4 && ww == 2){ gd = pp; gn = ll; }else if(ff == 2 && ww == 2){ tg = pp; tgn = ll; } } if(type != 2 || gd == NULL || tg == NULL) continue; ti = 0; while(ti < tgn){ ulong ki, vi; ki = getvar(tg, tgn, &ti); if(ti >= tgn) break; vi = getvar(tg, tgn, &ti); if(ki < (ulong)nk && vi < (ulong)nv && vp[vi] != NULL && (eqp(kp[ki], kl[ki], "kind_detail") || eqp(kp[ki], kl[ki], "kind"))){ kind = vp[vi]; kindl = vl[vi]; } } if(!roadok(kind, kindl)) continue; featgeom(gd, gn, 4096); a = -1; for(j = 0; j < (ulong)mvn; j++){ b = rnode(tx * TILE + mvx[j], ty * TILE + mvy[j]); if(a >= 0) redge(a, b); a = b; if(j + 1 < (ulong)mvn && mvx[j + 1] == 0 && mvy[j + 1] == 0) break; } } } static int rheap[RMAXN]; static int rhn; static double rcost[RMAXN]; static int rpar[RMAXN], rpe[RMAXN], rseen[RMAXN]; static void hpush(int v) { int i, p, t; if(rhn >= RMAXN) return; i = rhn++; rheap[i] = v; while(i > 0){ p = (i - 1) / 2; if(rcost[rheap[p]] <= rcost[rheap[i]]) break; t = rheap[p]; rheap[p] = rheap[i]; rheap[i] = t; i = p; } } static int hpop(void) { int top, i, l, r, m, t; top = rheap[0]; rhn--; if(rhn <= 0) return top; rheap[0] = rheap[rhn]; i = 0; for(;;){ l = 2 * i + 1; r = l + 1; m = i; if(l < rhn && rcost[rheap[l]] < rcost[rheap[m]]) m = l; if(r < rhn && rcost[rheap[r]] < rcost[rheap[m]]) m = r; if(m == i) break; t = rheap[i]; rheap[i] = rheap[m]; rheap[m] = t; i = m; } return top; } static int rnearest(double px, double py) { int i, best; double d, bd; best = -1; bd = 1e18; for(i = 0; i < rn; i++){ d = (rx[i] * 2.0 - px) * (rx[i] * 2.0 - px) + (ry[i] * 2.0 - py) * (ry[i] * 2.0 - py); if(d < bd){ bd = d; best = i; } } return best; } static int rpath(int src, int dst) { int i, n, u, e; double nc; if(src < 0 || dst < 0) return -1; for(i = 0; i < rn; i++){ rcost[i] = 1e18; rseen[i] = 0; rpar[i] = -1; } rcost[src] = 0; rhn = 0; hpush(src); while(rhn > 0){ u = hpop(); if(rseen[u]) continue; rseen[u] = 1; if(u == dst) break; for(e = rhead[u]; e >= 0; e = rnext[e]){ nc = rcost[u] + rw[e]; if(nc < rcost[rto[e]]){ rcost[rto[e]] = nc; rpar[rto[e]] = u; rpe[rto[e]] = e; hpush(rto[e]); } } } if(!rseen[dst]) return -1; n = 0; for(u = dst; u >= 0 && n < NPATH; u = rpar[u]) n++; if(n < 2 || n >= NPATH) return -1; i = n; for(u = dst; u >= 0 && i > 0; u = rpar[u]){ i--; plon[i] = (rx[u] * 2.0 / TILE + 0.0) / (1 << 15) * 360.0 - 180.0; plat[i] = atan(sinh(M_PI * (1.0 - 2.0 * (ry[u] * 2.0 / TILE) / (1 << 15)))) * 180.0 / M_PI; } npath = n; ns = 0; return 0; } static void routefinish(void) { int i; dist = 0; for(i = 1; i < npath; i++) dist += distm(plat[i - 1], plon[i - 1], plat[i], plon[i]); dur = dist / 8.33; ns = 0; step = 0; placepath(); } static int offlineroute(double la0, double lo0, double la1, double lo1) { int x0, x1, y0, y1, i, j, n, a, b, t; rmpp = 156543.03392 * cos((la0 + la1) / 2 * M_PI / 180) / (1 << 15); rreset(); n = 1 << 15; x0 = (int)(lntopx(lo0, 15) / TILE) - 3; x1 = (int)(lntopx(lo1, 15) / TILE) + 3; y0 = (int)(lattopy(la0, 15) / TILE) - 3; y1 = (int)(lattopy(la1, 15) / TILE) + 3; if(x0 > x1){ t = x0; x0 = x1; x1 = t; } if(y0 > y1){ t = y0; y0 = y1; y1 = t; } if(x0 < 0) x0 = 0; if(y0 < 0) y0 = 0; if(x1 > n - 1) x1 = n - 1; if(y1 > n - 1) y1 = n - 1; if((long)(x1 - x0 + 1) * (y1 - y0 + 1) > 4000) return -1; for(j = y0; j <= y1; j++) for(i = x0; i <= x1; i++) roadtile(15, i, j); a = rnearest(lntopx(lo0, 15), lattopy(la0, 15)); b = rnearest(lntopx(lo1, 15), lattopy(la1, 15)); if(rn < 2 || rpath(a, b) != 0) return -1; routefinish(); return 0; } typedef void (*NameCB)(void *arg, uchar *name, ulong nl, int px, int py); static void tiletime(int z, int x, int y, double px, double py, double *lat, double *lon) { double n, fx, fy; n = (double)(1 << z); fx = (x + px / TILE) / n; fy = (y + py / TILE) / n; *lon = fx * 360.0 - 180.0; *lat = atan(sinh(M_PI * (1.0 - 2.0 * fy))) * 180.0 / M_PI; } static void laynames(uchar *d, ulong n, int z, int x, int y, NameCB cb, void *arg) { uchar *kp[MVKL], *vp[MVVL]; ulong kl[MVKL], vl[MVVL]; int nk, nv, f, w; ulong v, i; uchar *p; ulong l; (void)z; (void)x; (void)y; nk = nv = 0; i = 0; while(pbnext(d, n, &i, &f, &w, &v, &p, &l)){ if(f == 3 && w == 2 && nk < MVKL){ kp[nk] = p; kl[nk] = l; nk++; }else if(f == 4 && w == 2 && nv < MVVL){ ulong j = 0; int ff, ww; ulong vv; uchar *pp; ulong ll; vp[nv] = NULL; vl[nv] = 0; while(pbnext(p, l, &j, &ff, &ww, &vv, &pp, &ll)) if(ff == 1 && ww == 2){ vp[nv] = pp; vl[nv] = ll; } nv++; } } i = 0; while(pbnext(d, n, &i, &f, &w, &v, &p, &l)){ uchar *gd, *tg, *name; ulong gn, tgn, nml, ti, j; int type, ff, ww; ulong vv; uchar *pp; ulong ll; if(f != 2 || w != 2) continue; gd = tg = name = NULL; gn = tgn = nml = 0; type = 0; j = 0; while(pbnext(p, l, &j, &ff, &ww, &vv, &pp, &ll)){ if(ff == 3 && ww == 0) type = (int)vv; else if(ff == 4 && ww == 2){ gd = pp; gn = ll; }else if(ff == 2 && ww == 2){ tg = pp; tgn = ll; } } if((type != 1 && type != 2) || gd == NULL || tg == NULL) continue; ti = 0; while(ti < tgn){ ulong ki, vi; ki = getvar(tg, tgn, &ti); if(ti >= tgn) break; vi = getvar(tg, tgn, &ti); if(ki < (ulong)nk && vi < (ulong)nv && vp[vi] != NULL && eqp(kp[ki], kl[ki], "name")){ name = vp[vi]; nml = vl[vi]; } } if(name == NULL) continue; featgeom(gd, gn, 4096); if(mvn > 0) cb(arg, name, nml, mvx[mvn / 2], mvy[mvn / 2]); } } static void tilenames(int z, int x, int y, NameCB cb, void *arg) { uchar *mvt; ulong mn, k; int f, w; ulong v; uchar *p; ulong l; mvt = ptile(&pmt, z, x, y, &mn); if(mvt == NULL) return; k = 0; while(pbnext(mvt, mn, &k, &f, &w, &v, &p, &l)){ uchar *np, *pp; ulong nl, j, ll, vv; int ff, ww; if(f != 3 || w != 2) continue; np = NULL; nl = 0; j = 0; while(pbnext(p, l, &j, &ff, &ww, &vv, &pp, &ll)) if(ff == 1 && ww == 2){ np = pp; nl = ll; } if(np == NULL) continue; if(eqp(np, nl, "places") || eqp(np, nl, "pois") || eqp(np, nl, "roads")) laynames(p, l, z, x, y, cb, arg); } free(mvt); } typedef struct Idx Idx; struct Idx { FILE *f; int z, x, y; }; static void idxcbn(void *arg, uchar *name, ulong nl, int px, int py) { Idx *ix; double lat, lon; ix = arg; tiletime(ix->z, ix->x, ix->y, px, py, &lat, &lon); fprintf(ix->f, "%.6f\t%.6f\t%.*s\n", lon, lat, (int)nl, (char *)name); } static void printcbn(void *arg, uchar *name, ulong nl, int px, int py) { (void)arg; (void)px; (void)py; printf("%.*s\n", (int)nl, (char *)name); } static int buildindex(int z, char *path) { Idx ix; int x, y, n; n = 1 << z; ix.f = fopen(path, "w"); if(ix.f == NULL) return -1; ix.z = z; for(y = 0; y < n; y++) for(x = 0; x < n; x++){ ix.x = x; ix.y = y; tilenames(z, x, y, idxcbn, &ix); } fclose(ix.f); return 0; } typedef struct Find Find; struct Find { char *q; double clat, clon, best, flat, flon; int rank; int z, x, y, found; char name[96]; }; static void findcbn(void *arg, uchar *name, ulong nl, int px, int py) { Find *fd; char tmp[96]; double lat, lon, d; int r; fd = arg; if(nl == 0 || nl >= sizeof tmp) return; memcpy(tmp, name, nl); tmp[nl] = 0; r = matchrank(tmp, fd->q); if(r > 2) return; tiletime(fd->z, fd->x, fd->y, px, py, &lat, &lon); d = distm(fd->clat, fd->clon, lat, lon); if(!fd->found || r < fd->rank || (r == fd->rank && d < fd->best)){ fd->found = 1; fd->best = d; fd->flat = lat; fd->flon = lon; snprintf(fd->name, sizeof fd->name, "%s", tmp); } } static int localscan(Find *fd, int z, int rad) { int cx, cy, i, j, n; n = 1 << z; cx = (int)(lntopx(fd->clon, z) / TILE); cy = (int)(lattopy(fd->clat, z) / TILE); for(j = cy - rad; j <= cy + rad; j++) for(i = cx - rad; i <= cx + rad; i++){ if(i < 0 || j < 0 || i >= n || j >= n) continue; fd->z = z; fd->x = i; fd->y = j; tilenames(z, i, j, findcbn, fd); } return fd->found ? 0 : -1; } static int matchrank(char *hay, char *q) { size_t n; n = strlen(q); if(strcasecmp(hay, q) == 0) return 0; if(strncasecmp(hay, q, n) == 0) return 1; if(strcasestr(hay, q) != NULL) return 2; return 3; } static int offlinefind(char *q, double *lat, double *lon, char *name, int max) { Find fd; FILE *f; char line[256], *t1, *t2; int r; memset(&fd, 0, sizeof fd); fd.q = q; fd.clat = pytolat(cam.y, cam.z); fd.clon = pxtolon(cam.x, cam.z); f = fopen("/var/lib/maps/places.idx", "r"); if(f != NULL){ while(fgets(line, sizeof line, f) != NULL){ double la, lo, d; line[strcspn(line, "\n")] = 0; t1 = strchr(line, '\t'); if(t1 == NULL) continue; *t1++ = 0; t2 = strchr(t1, '\t'); if(t2 == NULL) continue; *t2++ = 0; r = matchrank(t2, q); if(r > 2) continue; lo = strtod(line, NULL); la = strtod(t1, NULL); d = distm(fd.clat, fd.clon, la, lo); if(!fd.found || r < fd.rank || (r == fd.rank && d < fd.best)){ fd.found = 1; fd.rank = r; fd.best = d; fd.flat = la; fd.flon = lo; snprintf(fd.name, sizeof fd.name, "%s", t2); } } fclose(f); } if(!fd.found){ localscan(&fd, 15, 2); if(!fd.found) localscan(&fd, 14, 3); if(!fd.found) localscan(&fd, 11, 3); } if(!fd.found) return -1; *lat = fd.flat; *lon = fd.flon; snprintf(name, max, "%s", fd.name); return 0; } #define NCOL(r, g, b) ((ulong)(r) | ((ulong)(g) << 8) | \ ((ulong)(b) << 16) | 0xff000000UL) #define NAVNEAR 6.0 #define NAVBMAX 2400 static int navview = 0; static double navtilt = 18.0; static double navheading; static uchar *navbuf; static int navbufw, navbufh; static double navf, navsp, navcp, navmpp, naveye; static double navhor; static int navcx, navcy; typedef struct PBld PBld; struct PBld { double d; int n; int bx[NAVBFMAX], by[NAVBFMAX]; int tx[NAVBFMAX], ty[NAVBFMAX]; unsigned char ws[NAVBFMAX]; }; static PBld navb[NAVBMAX]; static int navbn; static ulong nblend(ulong a, ulong b, double t) { int r, g, bl; if(t < 0) t = 0; if(t > 1) t = 1; r = (int)((a & 0xff) * (1 - t) + (b & 0xff) * t); g = (int)(((a >> 8) & 0xff) * (1 - t) + ((b >> 8) & 0xff) * t); bl = (int)(((a >> 16) & 0xff) * (1 - t) + ((b >> 16) & 0xff) * t); return NCOL(r, g, bl); } static ulong nshade(ulong c, int s) { int r, g, b; r = (int)((c & 0xff) * s) >> 8; g = (int)(((c >> 8) & 0xff) * s) >> 8; b = (int)(((c >> 16) & 0xff) * s) >> 8; return NCOL(r, g, b); } static void navsetcam(void) { double pitch, lat; pitch = navtilt * M_PI / 180.0; lat = pytolat(cam.y, cam.z); navmpp = 156543.03392 * cos(lat * M_PI / 180.0) / (double)(1 << cam.z); if(navmpp < 0.01) navmpp = 0.01; navf = vw * 0.72; navcx = vw / 2; navcy = vh / 2; navsp = sin(pitch); navcp = cos(pitch); naveye = 70.0 / navmpp; if(naveye < 4) naveye = 4; navhor = navcy - navf * navsp / navcp; } static int navproj(double gx, double gy, double hpx, double *zc, int *sx, int *sy) { double dx, dy, z, x, zz, yc; dx = gx - cam.x; dy = gy - cam.y; z = dx * sin(navheading) - dy * cos(navheading); x = dx * cos(navheading) + dy * sin(navheading); if(z < NAVNEAR) return -1; zz = z * navcp + naveye * navsp; if(zz < 0.5) return -1; yc = z * navsp - (naveye + hpx) * navcp; *sx = navcx + (int)(navf * x / zz); *sy = navcy - (int)(navf * yc / zz); if(zc != NULL) *zc = zz; return 0; } static ulong tsampleb(Tile *t, double fx, double fy) { int x, y; int ax, ay; uchar *p, *q; int r, g, b; if(t == NULL) return NCOL(236, 233, 226); if(fx < 0) fx = 0; if(fy < 0) fy = 0; if(fx > t->w - 1.002) fx = t->w - 1.002; if(fy > t->h - 1.002) fy = t->h - 1.002; x = (int)fx; y = (int)fy; ax = (int)((fx - x) * 256.0); ay = (int)((fy - y) * 256.0); p = t->px + ((ulong)y * t->w + x) * 4; q = p + (ulong)t->w * 4; r = (p[0] * (256 - ax) + p[4] * ax) * (256 - ay) / 65536 + (q[0] * (256 - ax) + q[4] * ax) * ay / 65536; g = (p[1] * (256 - ax) + p[5] * ax) * (256 - ay) / 65536 + (q[1] * (256 - ax) + q[5] * ax) * ay / 65536; b = (p[2] * (256 - ax) + p[6] * ax) * (256 - ay) / 65536 + (q[2] * (256 - ax) + q[6] * ax) * ay / 65536; return NCOL(r, g, b); } static ulong navgsample(double wx, double wy, double dist) { double m, s, qx, qy, fog; int zz, i, j; Tile *t; ulong c; m = dist * navmpp; zz = cam.z; if(m > 24000) zz = cam.z - 4; else if(m > 8000) zz = cam.z - 3; else if(m > 2800) zz = cam.z - 2; else if(m > 900) zz = cam.z - 1; if(zz < 5) zz = 5; s = (double)(1 << (cam.z - zz)); qx = wx / s; qy = wy / s; i = (int)floor(qx / TILE); j = (int)floor(qy / TILE); t = tfindlocked(i, j, zz); c = tsampleb(t, qx - i * TILE, qy - j * TILE); fog = (m - 12000.0) / 26000.0; if(fog > 0) c = nblend(c, NCOL(214, 222, 231), fog); return c; } static void navrect(int x, int y, int stw, int sth, ulong c) { int i, j; for(j = y; j < y + sth && j < vh; j++) for(i = x; i < x + stw && i < vw; i++){ uchar *d; d = navbuf + ((ulong)j * vw + i) * 4; d[0] = c & 0xff; d[1] = (c >> 8) & 0xff; d[2] = (c >> 16) & 0xff; d[3] = 0xff; } } static void navpoint(int x, int y, ulong c) { uchar *d; if(x < 0 || y < 0 || x >= vw || y >= vh) return; d = navbuf + ((ulong)y * vw + x) * 4; d[0] = c & 0xff; d[1] = (c >> 8) & 0xff; d[2] = (c >> 16) & 0xff; d[3] = 0xff; } static void navtri(int x0, int y0, int x1, int y1, int x2, int y2, ulong c) { int minx, maxx, miny, maxy, x, y, e0, e1, e2, a; a = (x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0); if(a == 0) return; minx = x0 < x1 ? x0 : x1; if(x2 < minx) minx = x2; maxx = x0 > x1 ? x0 : x1; if(x2 > maxx) maxx = x2; miny = y0 < y1 ? y0 : y1; if(y2 < miny) miny = y2; maxy = y0 > y1 ? y0 : y1; if(y2 > maxy) maxy = y2; if(minx < 0) minx = 0; if(miny < 0) miny = 0; if(maxx > vw - 1) maxx = vw - 1; if(maxy > vh - 1) maxy = vh - 1; for(y = miny; y <= maxy; y++) for(x = minx; x <= maxx; x++){ e0 = (x - x0) * (y1 - y0) - (y - y0) * (x1 - x0); e1 = (x - x1) * (y2 - y1) - (y - y1) * (x2 - x1); e2 = (x - x2) * (y0 - y2) - (y - y2) * (x0 - x2); if((e0 >= 0 && e1 >= 0 && e2 >= 0) || (e0 <= 0 && e1 <= 0 && e2 <= 0)) navpoint(x, y, c); } } static void navquad(int x0, int y0, int x1, int y1, int x2, int y2, int x3, int y3, ulong c) { navtri(x0, y0, x1, y1, x2, y2, c); navtri(x0, y0, x2, y2, x3, y3, c); } static void navdisc(int cx, int cy, int rad, ulong c) { int x, y, r2; if(rad < 1) rad = 1; if(rad > 40) rad = 40; r2 = rad * rad; for(y = -rad; y <= rad; y++) for(x = -rad; x <= rad; x++) if(x * x + y * y <= r2) navpoint(cx + x, cy + y, c); } static int navbcmp(const void *a, const void *b) { const PBld *p, *q; p = a; q = b; if(p->d < q->d) return 1; if(p->d > q->d) return -1; return 0; } static void navbadd(int tx, int ty, BFoot *f) { PBld *b; int i, sx, syb, syt, minx, maxx, miny, maxy; double wx, wy, dx, dy, z, zc, hpx, nx, ny, l; if(f == NULL || f->n < 3 || navbn >= NAVBMAX) return; wx = tx * TILE + (f->x[0] + f->x[f->n / 2]) * 0.5; wy = ty * TILE + (f->y[0] + f->y[f->n / 2]) * 0.5; dx = wx - cam.x; dy = wy - cam.y; z = dx * sin(navheading) - dy * cos(navheading); if(z < 25 || z > 2600) return; hpx = f->h / navmpp; if(hpx < 1) hpx = 1; b = &navb[navbn]; b->n = f->n; b->d = z; minx = vw; maxx = -1; miny = vh; maxy = -1; for(i = 0; i < f->n; i++){ wx = tx * TILE + f->x[i]; wy = ty * TILE + f->y[i]; if(navproj(wx, wy, 0, &zc, &sx, &syb) != 0) return; if(navproj(wx, wy, hpx, &zc, &sx, &syt) != 0) return; b->bx[i] = sx; b->by[i] = syb; b->tx[i] = sx; b->ty[i] = syt; if(sx < minx) minx = sx; if(sx > maxx) maxx = sx; if(syb < miny) miny = syb; if(syt < miny) miny = syt; if(syt > maxy) maxy = syt; if(syb > maxy) maxy = syb; } if(maxx < 0 || minx >= vw || maxy < 0 || miny >= vh) return; if(maxx - minx < 2 && maxy - miny < 2) return; for(i = 0; i < f->n; i++){ int j, shade; j = (i + 1) % f->n; nx = ty * TILE + f->y[j] - wy; ny = -(tx * TILE + f->x[j] - wx); l = sqrt(nx * nx + ny * ny); if(l < 0.001){ shade = 180; }else{ nx /= l; ny /= l; shade = (int)(150 + 90 * fabs(nx * 0.55 + ny * 0.83)); } b->ws[i] = shade > 255 ? 255 : shade; } navbn++; } static void navbuild(void) { int tx0, ty0, r, i, j, k, n; Tile *t; navbn = 0; tx0 = (int)(cam.x / TILE); ty0 = (int)(cam.y / TILE); r = 2; n = 1 << cam.z; pthread_mutex_lock(&tlok); for(j = ty0 - r; j <= ty0 + r; j++) for(i = tx0 - r; i <= tx0 + r; i++){ if(i < 0 || j < 0 || i >= n || j >= n) continue; t = tfindlocked(i, j, cam.z); if(t == NULL || t->bf == NULL) continue; for(k = 0; k < t->nbf; k++) navbadd(i, j, &t->bf[k]); } pthread_mutex_unlock(&tlok); qsort(navb, navbn, sizeof navb[0], navbcmp); for(k = 0; k < navbn; k++){ PBld *b; int i2, j2; b = &navb[k]; for(i2 = 0; i2 < b->n; i2++){ j2 = (i2 + 1) % b->n; navquad(b->bx[i2], b->by[i2], b->bx[j2], b->by[j2], b->tx[j2], b->ty[j2], b->tx[i2], b->ty[i2], nshade(NCOL(197, 191, 183), b->ws[i2])); } for(i2 = 1; i2 + 1 < b->n; i2++) navtri(b->tx[0], b->ty[0], b->tx[i2], b->ty[i2], b->tx[i2 + 1], b->ty[i2 + 1], NCOL(228, 222, 211)); } } static void navprefetch(void) { int z, nz, cx, cy, r, i, j; Tile *t; for(z = cam.z; z >= 6 && z >= cam.z - 4; z--){ nz = 1 << z; cx = (int)(cam.x / TILE) >> (cam.z - z); cy = (int)(cam.y / TILE) >> (cam.z - z); r = 4 - (cam.z - z); if(r < 1) r = 1; for(j = cy - r; j <= cy + r; j++) for(i = cx - r; i <= cx + r; i++) if(i >= 0 && j >= 0 && i < nz && j < nz){ t = tilefetch(i, j, z); if(t != NULL) tinsert(t); } } } static void navtiles(void) { int cx, cy, r, i, j, z, nz; for(z = cam.z; z >= 6 && z >= cam.z - 4; z--){ nz = 1 << z; cx = (int)(cam.x / TILE) >> (cam.z - z); cy = (int)(cam.y / TILE) >> (cam.z - z); r = 4 - (cam.z - z); if(r < 1) r = 1; for(j = cy - r; j <= cy + r; j++) for(i = cx - r; i <= cx + r; i++) if(i >= 0 && j >= 0 && i < nz && j < nz) tilewant(i, j, z); } } static void navlook(void) { int i; if(gps_valid && gps_track > 0 && gps_track < 360){ navheading = gps_track * M_PI / 180; return; } if(npath > 1 && gps_valid){ for(i = 0; i + 1 < npath; i++){ if(distm(gps_lat, gps_lon, plat[i], plon[i]) < 150){ navheading = atan2( lntopx(plon[i + 1], 15) - lntopx(plon[i], 15), lattopy(plat[i], 15) - lattopy(plat[i + 1], 15)); return; } } } } static void navrender(void) { int x, y, st, y0; double A, den, z, zc, dxr, wx, wy, fwdx, fwdy, rtx, rty; ulong c; if(navbuf == NULL || navbufw != vw || navbufh != vh){ free(navbuf); navbuf = malloc((ulong)vw * vh * 4); navbufw = vw; navbufh = vh; if(navbuf == NULL) return; } navsetcam(); st = vw > 1100 ? 2 : 1; y0 = (int)navhor + 1; if(y0 < 0) y0 = 0; if(y0 > vh) y0 = vh; for(y = 0; y < y0; y++){ double t; t = y0 > 0 ? (double)y / y0 : 0; c = nblend(NCOL(190, 209, 229), NCOL(231, 238, 245), t); for(x = 0; x < vw; x += st) navrect(x, y, st, 1, c); } fwdx = sin(navheading); fwdy = -cos(navheading); rtx = cos(navheading); rty = sin(navheading); pthread_mutex_lock(&tlok); for(y = y0; y < vh; y += st){ A = y - navcy; den = navf * navsp + A * navcp; if(den < 0.5){ for(x = 0; x < vw; x += st) navrect(x, y, st, st, NCOL(226, 232, 238)); continue; } z = naveye * (navf * navcp - A * navsp) / den; if(z < 1) z = 1; zc = z * navcp + naveye * navsp; for(x = 0; x < vw; x += st){ dxr = zc * ((x + st * 0.5) - navcx) / navf; wx = cam.x + z * fwdx + dxr * rtx; wy = cam.y + z * fwdy + dxr * rty; navrect(x, y, st, st, navgsample(wx, wy, z)); } } pthread_mutex_unlock(&tlok); } static void navribbon(int i, int j, double halfm, ulong c) { double zca, zcb, dx, dy, l, nx, ny; int ax, ay, bx, by, rad; if(navproj(lntopx(plon[i], cam.z), lattopy(plat[i], cam.z), 0, &zca, &ax, &ay) != 0) return; if(navproj(lntopx(plon[j], cam.z), lattopy(plat[j], cam.z), 0, &zcb, &bx, &by) != 0) return; if(ay >= vh && by >= vh) return; if(ay < 0 && by < 0) return; dx = bx - ax; dy = by - ay; l = sqrt(dx * dx + dy * dy); if(l < 0.01) return; rad = (int)(navf * (halfm / navmpp) / ((zca + zcb) * 0.5)); if(rad > 26) rad = 26; if(rad < 1) rad = 1; nx = -dy / l * rad; ny = dx / l * rad; navquad(ax + nx, ay + ny, bx + nx, by + ny, bx - nx, by - ny, ax - nx, ay - ny, c); } static void navroute(void) { int i, sx, sy, rad; double zc; if(npath < 2) return; for(i = 0; i + 1 < npath; i++) navribbon(i, i + 1, 11.0, NCOL(252, 252, 252)); for(i = 0; i + 1 < npath; i++) navribbon(i, i + 1, 8.0, NCOL(36, 120, 255)); for(i = 1; i + 1 < npath; i++){ if(navproj(lntopx(plon[i], cam.z), lattopy(plat[i], cam.z), 0, &zc, &sx, &sy) != 0) continue; rad = (int)(navf * (8.0 / navmpp) / zc); navdisc(sx, sy, rad > 26 ? 26 : rad, NCOL(36, 120, 255)); } for(i = 0; i < ns && i < MAXSTEPS; i++){ if(navproj(lntopx(steps[i].lon, cam.z), lattopy(steps[i].lat, cam.z), 0, &zc, &sx, &sy) != 0) continue; rad = (int)(navf * (9.0 / navmpp) / zc); if(rad > 22) rad = 22; navdisc(sx, sy, rad, NCOL(255, 255, 255)); rad = rad * 2 / 3; navdisc(sx, sy, rad, NCOL(36, 120, 255)); } } static void navpaint(void) { Tile t; char b1[200], b2[200]; int y0, w, cx, my; if(!vtactive()) return; navlook(); navtiles(); navrender(); navbuild(); navroute(); if(navbuf == NULL) return; memset(&t, 0, sizeof t); t.px = navbuf; t.w = vw; t.h = vh; blittile(&t, fb.ox, fb.oy); cx = fb.ox + vw / 2; my = fb.oy + vh - 70; line(cx, my - 26, cx - 15, my + 10, 0x0000ffff); line(cx, my - 26, cx + 15, my + 10, 0x0000ffff); line(cx - 15, my + 10, cx + 15, my + 10, 0x0000ffff); line(cx, my - 20, cx, my + 4, 0x0000ffff); if(ns > 0 && step < ns){ snprintf(b1, sizeof b1, "%s", steps[step].instr); snprintf(b2, sizeof b2, "%s %.0f m | %.1f km %.0f min", steps[step].name, steps[step].dist, (pcum[npath - 1] - simdist) / 1000.0, (pcum[npath - 1] - simdist) / simspeed / 60.0); }else if(npath > 1){ snprintf(b1, sizeof b1, "Ziel"); snprintf(b2, sizeof b2, "%.0f m", pcum[npath - 1] - simdist); }else{ snprintf(b1, sizeof b1, "keine Route"); b2[0] = 0; } w = (int)strlen(b1) > (int)strlen(b2) ? (int)strlen(b1) : (int)strlen(b2); w = w * 8 + 20; y0 = fb.oy + 10; fillrect(fb.ox + 10, y0, fb.ox + 10 + w, y0 + 40, 0x00101418); text(fb.ox + 18, y0 + 4, b1, 0x00ffffff, 0x00101418); text(fb.ox + 18, y0 + 22, b2, 0x00cccccc, 0x00101418); } static void run(void) { struct pollfd fds[2]; char c; int k; int simframe = 0; for(;;){ if(!running) return; if(redrawnow){ redrawnow = 0; if(fb_pane_active()){ panesize(); renderframe(); } } fds[0].fd = 0; fds[0].events = POLLIN; fds[1].fd = wake[0]; fds[1].events = POLLIN; if(poll(fds, 2, 100) <= 0){ int tick; if(simon) simtick(); tick = fb_pane_tick(); if(tick == 1){ panesize(); renderframe(); }else if(tick == 2 || tick == 3){ if(fb_repaint(&fb) < 0){ panesize(); renderframe(); } }else if(simon && fb_pane_active()){ simframe++; if(simframe % 2 == 0) renderframe(); } continue; } if(fds[1].revents & POLLIN){ while(read(wake[0], &c, 1) == 1) ; panesize(); renderframe(); } if(fds[0].revents & POLLIN){ if(read(0, &c, 1) != 1) continue; if(inprompt){ promptchar(c); continue; } msg[0] = 0; k = getescape(c); switch(k){ case 'q': return; case KEYUP: pan(0, -vh / 3); break; case KEYDOWN: pan(0, vh / 3); break; case KEYLEFT: pan(-vw / 3, 0); break; case KEYRIGHT: pan(vw / 3, 0); break; case '+': case '=': zoom(1); break; case '-': case '_': zoom(-1); break; case 's': setstart(); break; case 'd': setdest(); break; case 'r': doroute(); break; case '\r': case '\n': case 'o': case 'g': startprompt(0); break; case 'a': startprompt(1); break; case 't': navtilt += 8; if(navtilt > 90) navtilt = 12; snprintf(msg, sizeof msg, "tilt %.0f", navtilt); renderframe(); break; case 'v': navview = !navview; renderframe(); break; case 'i': if(simon) simon = 0; else simstart(); renderframe(); break; case ',': simspeed *= 0.5; if(simspeed < 2) simspeed = 2; snprintf(msg, sizeof msg, "sim %.0f km/h", simspeed * 3.6); renderframe(); break; case '.': simspeed *= 2; if(simspeed > 100) simspeed = 100; snprintf(msg, sizeof msg, "sim %.0f km/h", simspeed * 3.6); renderframe(); break; case 'n': if(ns > 0 && step < ns - 1){ step++; renderframe(); } break; case 'p': if(ns > 0 && step > 0){ step--; renderframe(); } break; case '?': showhelp = !showhelp; renderframe(); break; case 'f': autofollow = !autofollow; if(autofollow && gps_valid){ snprintf(msg, sizeof msg, "auto-follow ON"); }else{ autofollow = 0; snprintf(msg, sizeof msg, "auto-follow OFF"); } renderframe(); break; default: break; } } } } int main(int argc, char **argv) { int i; pthread_t th; lruhead.next = &lruhead; lruhead.prev = &lruhead; profile = "driving"; if(argc > 5 && strcmp(argv[1], "sim") == 0){ int n, guard; slat = atof(argv[2]); slon = atof(argv[3]); dlat = atof(argv[4]); dlon = atof(argv[5]); hasstart = 1; hasdst = 1; curl_global_init(CURL_GLOBAL_ALL); if(routefetch() != 0){ fprintf(stderr, "route failed\n"); return 1; } placepath(); simdist = 0; simon = 1; guard = 0; while(simon && guard++ < 2000000) simtick(); n = 0; printf("%.1f km ticks %d pos %.6f %.6f step %d/%d\n", pcum[npath - 1] / 1000.0, guard, gps_lat, gps_lon, step + 1, ns); (void)n; return 0; } if(argc > 6 && strcmp(argv[1], "navshot") == 0){ int i; FILE *f; pmtinit(); if(!pmtready){ fprintf(stderr, "no pmtiles\n"); return 1; } vw = 800; vh = 480; cam.z = atoi(argv[5]); cam.x = lntopx(atof(argv[3]), cam.z); cam.y = lattopy(atof(argv[2]), cam.z); navheading = atof(argv[4]) * M_PI / 180; navprefetch(); if(argc > 8){ slat = atof(argv[2]); slon = atof(argv[3]); dlat = atof(argv[7]); dlon = atof(argv[8]); hasstart = 1; hasdst = 1; curl_global_init(CURL_GLOBAL_ALL); if(routefetch() == 0) placepath(); } navrender(); navbuild(); navroute(); f = fopen(argv[6], "wb"); if(f == NULL) return 1; fprintf(f, "P6\n%d %d\n255\n", vw, vh); for(i = 0; i < vw * vh; i++) fwrite(navbuf + i * 4, 1, 3, f); fclose(f); fprintf(stderr, "navshot ok\n"); return 0; } if(argc > 5 && strcmp(argv[1], "offroute") == 0){ pmtinit(); if(!pmtready) return 1; if(offlineroute(atof(argv[2]), atof(argv[3]), atof(argv[4]), atof(argv[5])) != 0){ fprintf(stderr, "offline route failed\n"); return 1; } printf("%.2f km %.0f min %d pts\n", dist / 1000.0, dur / 60.0, npath); return 0; } if(argc > 5 && strcmp(argv[1], "route") == 0){ int n; slat = atof(argv[2]); slon = atof(argv[3]); dlat = atof(argv[4]); dlon = atof(argv[5]); hasstart = 1; hasdst = 1; curl_global_init(CURL_GLOBAL_ALL); if(routefetch() != 0){ fprintf(stderr, "route failed\n"); return 1; } printf("%.1f km %.0f min %d steps\n", dist / 1000.0, dur / 60.0, ns); for(n = 0; n < ns && n < 8; n++) printf("%d %s %.0fm\n", n + 1, steps[n].instr, steps[n].dist); return 0; } if(argc > 4 && strcmp(argv[1], "names") == 0){ pmtinit(); if(!pmtready) return 1; tilenames(atoi(argv[2]), atoi(argv[3]), atoi(argv[4]), printcbn, NULL); return 0; } if(argc > 2 && strcmp(argv[1], "find") == 0){ double lat, lon; char nm[128]; pmtinit(); cam.z = 12; cam.x = lntopx(13.4050, cam.z); cam.y = lattopy(52.5200, cam.z); if(argc > 4){ cam.y = lattopy(atof(argv[3]), cam.z); cam.x = lntopx(atof(argv[4]), cam.z); } if(offlinefind(argv[2], &lat, &lon, nm, sizeof nm) != 0) return 1; printf("%s %f %f\n", nm, lat, lon); return 0; } if(argc > 1 && strcmp(argv[1], "buildindex") == 0){ int z; z = argc > 2 ? atoi(argv[2]) : 8; pmtinit(); if(!pmtready) return 1; if(buildindex(z, "/var/lib/maps/places.idx") != 0) return 1; return 0; } if(argc > 1 && strcmp(argv[1], "pane") == 0){ printf("%d\n", paneactive()); return 0; } if(argc > 1 && strcmp(argv[1], "places") == 0){ int n; placeload(); for(n = 0; n < nplaces; n++) printf("%s\t%0.6f\t%0.6f\n", places[n].name, places[n].lat, places[n].lon); return 0; } if(argc > 4 && strcmp(argv[1], "place") == 0){ if(placesave(argv[4], atof(argv[2]), atof(argv[3])) != 0) return 1; printf("%s\t%s\t%s\n", argv[4], argv[2], argv[3]); return 0; } if(argc > 5 && strcmp(argv[1], "tile") == 0){ Tile *t; FILE *f; pmtinit(); if(!pmtready){ fprintf(stderr, "cannot open pmtiles\n"); return 1; } t = tilefetch(atoi(argv[3]), atoi(argv[4]), atoi(argv[2])); if(t == NULL){ fprintf(stderr, "no tile\n"); return 1; } f = fopen(argv[5], "wb"); if(f == NULL) return 1; fprintf(f, "P6\n%d %d\n255\n", TILE, TILE); for(i = 0; i < TILE * TILE; i++) fwrite(t->px + i * 4, 1, 3, f); fclose(f); fprintf(stderr, "tile ok labels=%d\n", t->nlab); return 0; } for(i = 1; i < argc; i++){ if(strcmp(argv[i], "-p") == 0 && i + 1 < argc) profile = argv[++i]; } curl_global_init(CURL_GLOBAL_ALL); if(fb_open(&fb) != 0) return 1; rawmode(); atexit(cleanup); signal(SIGINT, sighandler); signal(SIGTERM, sighandler); signal(SIGHUP, sighandler); signal(SIGUSR1, usrsig); fb_hook_install(SIGUSR1); panesize(); printf("\033[?25l"); fflush(stdout); if(pipe(wake) != 0) return 1; fcntl(wake[0], F_SETFL, O_NONBLOCK); for(i = 0; i < NWORK; i++){ if(pthread_create(&th, NULL, worker, NULL) != 0) break; pthread_detach(th); } pthread_create(&th, NULL, gpsdthread, NULL); pthread_detach(th); autofollow = 1; pmtinit(); placeload(); cam.z = 12; cam.x = lntopx(13.4050, cam.z); cam.y = lattopy(52.5200, cam.z); setvis(); wanttiles(); renderframe(); run(); running = 0; pthread_mutex_lock(&tlok); pthread_cond_broadcast(&tlcd); pthread_mutex_unlock(&tlok); cleanup(); return 0; }