sgeo --trip: draw the journey as an ordered polyline with time labels
Reads a stag CSV, orders the geotagged rows by their parsed timestamp (ISO and EXIF-colon forms sort together), and draws the trip on an OSM map: blue line with white halo, direction arrowhead per leg, red marker per stop, MM-DD HH:MM label per timestamped stop. Rows without a timestamp go last in CSV order; rows without coordinates are skipped. Reuses sgeo tile/zoom/marker code via shared fetch_tiles/draw_attribution helpers. Tests: 11/11 in tests/run_tests.sh (3 new trip cases + tests/check_trip.py). Docs: docs/trip-path.md.
This commit is contained in:
1 parent
a2106045a6
commit
934c336667
6 files changed
+1117
-50
No files matched your search
@@ -316,7 +316,7 @@ sfile/
|
||||
tools/get_sample_urls.py extracts sample_urls.json from the raw pages
|
||||
tools/extract_cpp.py extracts all_formats.cpp from the raw pages
|
||||
tests/run_tests.py the per-format test loop
|
||||
tests/run_tests.sh the stag/sgeo test suite (8 checks, fake sfile + local tile server)
|
||||
tests/run_tests.sh the stag/sgeo test suite (11 checks, fake sfile + local tile server)
|
||||
tests/test_json.py --json tests: parses + matches the text table (make test-json)
|
||||
tests/test_lib.sh library link test, static + shared (make test-lib)
|
||||
tests/test_library.c link-test program (decodes via the public API only)
|
||||
@@ -327,6 +327,7 @@ sfile/
|
||||
docs/json.md --json output: schema, geotags, examples
|
||||
docs/library.md libsfile: API, building, example, tests
|
||||
docs/stag-sgeo.md stag/sgeo usage, CSV format, map + attribution, network dependency
|
||||
docs/trip-path.md sgeo --trip: the journey as a polyline with time labels
|
||||
docs/geotag-contract.md the sfile <-> stag/sgeo geotag seam (what sfile prints, what the client accepts)
|
||||
samples/ one real sample file per format + manifests
|
||||
```
|
||||
@@ -352,7 +353,10 @@ decisions are made, and the limits.
|
||||
file (`file,format,latitude,longitude,altitude,datum,timestamp,source`);
|
||||
every scanned file gets a row, with empty geo fields when no location
|
||||
was found. `sgeo` plots the geotagged files on an OpenStreetMap image
|
||||
(one red marker each, attribution baked onto the PNG). Both run the
|
||||
(one red marker each, attribution baked onto the PNG). `sgeo --trip
|
||||
geotags.csv` draws the same points as a journey instead: the rows in
|
||||
timestamp order, connected as a polyline with time labels (see
|
||||
`docs/trip-path.md`). Both run the
|
||||
`sfile` binary and parse its `Geotagging:` section — they never parse
|
||||
containers themselves; the seam is `docs/geotag-contract.md`.
|
||||
|
||||
@@ -376,7 +380,7 @@ tokyo_real.jpg,JPEG image,35.676200,139.650300,,WGS-84,,EXIF GPS IFD (JPEG APP1
|
||||
and the `© OpenStreetMap contributors` attribution drawn on the image
|
||||
must stay there. See `docs/stag-sgeo.md` for the full usage, the CSV
|
||||
format and the empty-coords rule, the test suite
|
||||
(`tests/run_tests.sh`, 8/8 pass), and the build caveat.
|
||||
(`tests/run_tests.sh`, 11/11 pass), and the build caveat.
|
||||
|
||||
## Sources
|
||||
|
||||
|
||||
+18
-3
@@ -169,6 +169,12 @@ $ file /tmp/realgeo-fresh.png
|
||||
San Francisco and Tokyo are far apart, so the zoom drops to 2 and
|
||||
the image is 1024x256 from 4 tiles.
|
||||
|
||||
### Trip path
|
||||
|
||||
`sgeo --trip <csv> [outfile]` draws the journey a stag CSV records
|
||||
— the geotagged rows in timestamp order, as a polyline with time
|
||||
labels — instead of just markers. See `docs/trip-path.md`.
|
||||
|
||||
### No geotags
|
||||
|
||||
If no file in the directory has a location, `sgeo` prints an error
|
||||
@@ -208,7 +214,7 @@ tile server.
|
||||
end to end with a fake `sfile` (`tests/bin/sfile`, canned GPS values
|
||||
dispatched on filename) and a local tile server
|
||||
(`tests/tile_server.py`, via `$SGEO_TILE_BASE`), so the suite is
|
||||
offline. Eight checks, all passing:
|
||||
offline. Eleven checks, all passing:
|
||||
|
||||
```console
|
||||
$ ./tests/run_tests.sh
|
||||
@@ -220,6 +226,9 @@ PASS: sgeo no-geotag: non-zero, message, no file
|
||||
PASS: stag empty-dir CSV (header only)
|
||||
PASS: sgeo empty-dir: non-zero, no file
|
||||
PASS: default outfiles geotags.csv / map.png
|
||||
PASS: sgeo --trip ordered polyline + time labels
|
||||
PASS: sgeo --trip single point
|
||||
PASS: sgeo --trip failures (no geotags, bad header, missing file)
|
||||
stag/sgeo tests: ALL PASS
|
||||
```
|
||||
|
||||
@@ -228,5 +237,11 @@ Cases covered: a multi-file directory (CSV byte-for-byte against
|
||||
attribution plaque), a single point, a no-geotag directory (stag
|
||||
rows are empty, sgeo fails with no file), an empty directory (stag
|
||||
header only, sgeo fails with no file), and the default outfiles
|
||||
(`geotags.csv` / `map.png` in the cwd). The real-file path against
|
||||
the decoder build of sfile is shown in the examples above.
|
||||
(`geotags.csv` / `map.png` in the cwd). The `--trip` cases use a
|
||||
synthetic CSV (rows out of timestamp order, one EXIF-colon timestamp,
|
||||
one untimestamped row, one row with no geotag): `tests/check_trip.py`
|
||||
re-implements the projection and checks the markers land on their
|
||||
projected points, the blue line follows the timestamp-ordered legs
|
||||
(and not the file-order hops), and every timestamped marker has a
|
||||
label plaque. The real-file path against the decoder build of sfile
|
||||
is shown in the examples above.
|
||||
@@ -0,0 +1,150 @@
|
||||
# sgeo --trip: draw the journey as a path on the map
|
||||
|
||||
`sgeo --trip <csv> [outfile]` reads a [stag](stag-sgeo.md) CSV and
|
||||
draws the trip it records: the geotagged rows in timestamp order,
|
||||
connected as an ordered polyline on an OpenStreetMap image — not just
|
||||
markers. Each stop gets a red marker, each leg a blue line with a
|
||||
white halo and an arrowhead showing the direction of travel, and each
|
||||
timestamped stop a time label (`MM-DD HH:MM`, UTC, as stag printed
|
||||
it) next to its marker.
|
||||
|
||||
## Usage
|
||||
|
||||
```console
|
||||
$ make sgeo
|
||||
$ stag photos/ # -> geotags.csv in the cwd
|
||||
$ sgeo --trip geotags.csv # -> trip.png in the cwd
|
||||
$ sgeo --trip geotags.csv day1.png
|
||||
```
|
||||
|
||||
`outfile` defaults to `trip.png` in the current directory. The map is
|
||||
built from OpenStreetMap raster tiles fetched at runtime, exactly like
|
||||
`sgeo`'s directory mode (same zoom choice from the points' bounding
|
||||
box, same tile budget, same attribution plaque baked onto the image).
|
||||
`$SGEO_TILE_BASE` overrides the tile base URL; the tests use it to
|
||||
point at a local tile server. No `sfile` binary is needed: the input
|
||||
is the CSV itself, so `--trip` works on a CSV made anywhere — by stag,
|
||||
by hand, or by a spreadsheet — as long as it has stag's columns.
|
||||
|
||||
Exit code 0 on success; 1 if the CSV cannot be read, has a bad
|
||||
header, or has no geotagged rows (no output file is written then),
|
||||
2 on a usage error.
|
||||
|
||||
## CSV input expectations
|
||||
|
||||
The header must start with stag's columns:
|
||||
|
||||
```text
|
||||
file,format,latitude,longitude,altitude,datum,timestamp,source
|
||||
```
|
||||
|
||||
Rows are parsed as real CSV (quoted fields, with `""` for a quote
|
||||
inside, are handled, so filenames containing commas work). Only the
|
||||
latitude, longitude and timestamp columns matter:
|
||||
|
||||
| column | how --trip uses it |
|
||||
| --- | --- |
|
||||
| `latitude` / `longitude` | the stop's position; empty means "no geotag" and the row is skipped (the CSV's empty-coords rule) |
|
||||
| `timestamp` | the stop's time, for ordering and the label; empty means "time unknown" and the stop goes last, in CSV order, with no label |
|
||||
| the rest | ignored (`file` appears in warnings only) |
|
||||
|
||||
A row with garbage coordinates (non-numeric, or latitude outside
|
||||
±90 / longitude outside ±180) is warned about on stderr and skipped;
|
||||
the count is reported at the end. A row with fewer than 7 fields is
|
||||
malformed and skipped the same way.
|
||||
|
||||
## Timestamp ordering
|
||||
|
||||
Rows are ordered by their timestamp, not by their position in the
|
||||
file — a CSV in filename order is almost never in time order, and
|
||||
drawing file order would draw the wrong journey. The timestamp is
|
||||
parsed, not compared as text, so the two forms stag emits sort
|
||||
together:
|
||||
|
||||
- ISO, as the decoder prints it: `2024-05-01 12:34:56` (or date-only
|
||||
`2024-05-01`, which labels as `05-01` and sorts at midnight)
|
||||
- EXIF-colon, as the fallback path passes it through:
|
||||
`2024:06:15 08:30:00`
|
||||
|
||||
(A text comparison would put every `YYYY:MM:DD` row after every
|
||||
`YYYY-MM-DD` row, whatever the dates — `:` sorts after `-`.) Rows
|
||||
with equal timestamps, and all rows with no timestamp, keep CSV
|
||||
order, so the path is deterministic. A time-only value (no date)
|
||||
cannot be ordered and is treated as no timestamp.
|
||||
|
||||
Labels show `MM-DD HH:MM` (date-only: `MM-DD`). The year is omitted:
|
||||
a trip path fits on one map, and the year is in the CSV. Times are
|
||||
UTC, as stag prints them.
|
||||
|
||||
## What is drawn, in order
|
||||
|
||||
1. The legs, in timestamp order: a blue line (radius 2) with a white
|
||||
halo (radius 4) so the path reads over any tile.
|
||||
2. One arrowhead per leg, at the leg's midpoint, pointing along the
|
||||
direction of travel (legs shorter than 80 px get none — the arrow
|
||||
would touch the markers).
|
||||
3. One red marker per stop (the same marker as directory mode),
|
||||
drawn on top of the line.
|
||||
4. One time label per timestamped stop: a white plaque with black
|
||||
text, upper-right of the marker, flipped to the left (or below) at
|
||||
the image edge. Untimestamped stops get a marker but no label.
|
||||
5. The `© OpenStreetMap contributors` attribution plaque, last, so
|
||||
it is never covered up.
|
||||
|
||||
A single geotagged row draws just its marker and label, like
|
||||
directory mode with one point.
|
||||
|
||||
## Example
|
||||
|
||||
Five photos around San Francisco, in the CSV in filename order
|
||||
(`c.jpg` first, `a.jpg` second — deliberately not time order), one
|
||||
with no timestamp, one with no geotag at all:
|
||||
|
||||
```console
|
||||
$ cat trip.csv
|
||||
file,format,latitude,longitude,altitude,datum,timestamp,source
|
||||
c.jpg,JPEG image,37.784900,-122.379400,,WGS-84,2024-05-01 10:00:00,EXIF GPS
|
||||
a.jpg,JPEG image,37.774900,-122.419400,,WGS-84,2024-05-01 08:00:00,EXIF GPS
|
||||
d.jpg,JPEG image,37.754900,-122.439400,,WGS-84,2024-05-01 11:00:00,EXIF GPS
|
||||
b.jpg,JPEG image,37.804900,-122.409400,,WGS-84,2024:05:01 09:00:00,EXIF GPS
|
||||
e.jpg,JPEG image,37.794900,-122.439400,,WGS-84,,EXIF GPS
|
||||
plain.jpg,JPEG image,,,,,,
|
||||
$ sgeo --trip trip.csv trip.png
|
||||
sgeo: 6 row(s) in 'trip.csv', 5 point(s), 4 with timestamps, zoom 13, 768x768, 9 tile(s) -> trip.png
|
||||
```
|
||||
|
||||
The drawn path is 08:00 (downtown) → 09:00 (Telegraph Hill) →
|
||||
10:00 (over the Bay) → 11:00 (Castro) → the untimestamped stop
|
||||
(Presidio Heights) last — not the file's c → a → d → b → e order.
|
||||
The b.jpg leg proves the mixed-format sort: its EXIF-colon
|
||||
`2024:05:01 09:00:00` slots between the two ISO timestamps, where a
|
||||
text sort would have put it after all of them. The same map rendered
|
||||
against live OSM tiles is the feature image of the follow-up article
|
||||
on fileformat.vpscoder.com (see the stag/sgeo article there).
|
||||
|
||||
## Limits
|
||||
|
||||
- A trip crossing the antimeridian (±180°) draws the long way
|
||||
around the map: the polyline connects the projected points
|
||||
directly, with no wrap. (Directory mode has the same shape of
|
||||
limitation for markers at opposite edges.)
|
||||
- In a dense cluster, time labels can overlap each other or a leg:
|
||||
labels are placed per-marker with no collision avoidance. Split
|
||||
the CSV if the labels collide.
|
||||
- The path is a straight line between consecutive stops
|
||||
(great-circle segments are not drawn); for a day's photos the
|
||||
difference is invisible at these zooms.
|
||||
- Only the first location per file is used: the CSV has one row per
|
||||
file, so a file with several locations contributes its first
|
||||
block, as stag records it (see `docs/geotag-contract.md`,
|
||||
"first source wins").
|
||||
|
||||
## Tests
|
||||
|
||||
`tests/run_tests.sh` covers `--trip` with a synthetic CSV (the
|
||||
example above, against the local tile server) plus a single-point
|
||||
CSV and the failure cases — see `tests/check_trip.py`, which
|
||||
re-implements the projection and checks the markers land on their
|
||||
projected points, the blue line follows the timestamp-ordered legs
|
||||
(and not the file-order hops), and every timestamped marker has a
|
||||
label plaque. Eleven checks in the suite, all passing.
|
||||
+547
-43
@@ -4,6 +4,11 @@
|
||||
* dir directory to scan, non-recursive (default ".")
|
||||
* outfile PNG file to write (default "map.png" in the cwd)
|
||||
*
|
||||
* sgeo --trip <csv> [outfile]
|
||||
* draw a trip path from a stag CSV: the geotagged rows in
|
||||
* timestamp order, as an ordered polyline with time labels
|
||||
* (default outfile "trip.png"; see docs/trip-path.md)
|
||||
*
|
||||
* Coordinates come from running the `sfile` binary on each file and
|
||||
* parsing its "Geotagging:" section (see src/geotag_client.c and
|
||||
* docs/geotag-contract.md). The map is built from OpenStreetMap raster
|
||||
@@ -22,7 +27,9 @@
|
||||
* Exit status: 0 on success; 1 if the directory cannot be read, sfile
|
||||
* cannot be run, a tile cannot be fetched, or the map cannot be
|
||||
* written. If no file in the directory carries a geotag, sgeo prints
|
||||
* a message to stderr, exits 1, and writes NO output file.
|
||||
* a message to stderr, exits 1, and writes NO output file. In
|
||||
* --trip mode the input is a stag CSV instead of a directory; a CSV
|
||||
* with no geotagged rows fails the same way.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include <curl/curl.h>
|
||||
@@ -74,9 +81,10 @@ static double lat_to_px(double lat, int zoom)
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Tiny 5x7 bitmap font (attribution only). Each glyph is 7 rows; */
|
||||
/* bit 4 of a row is the leftmost pixel. Only the characters in */
|
||||
/* "© OpenStreetMap contributors" are defined; anything else is blank. */
|
||||
/* Tiny 5x7 bitmap font. Each glyph is 7 rows; bit 4 of a row is the */
|
||||
/* leftmost pixel. Defined: the letters in the attribution string */
|
||||
/* plus digits, '-' and ':' for the trip time labels; anything else */
|
||||
/* is blank. */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
static const unsigned char *font_glyph(char c)
|
||||
@@ -98,6 +106,18 @@ static const unsigned char *font_glyph(char c)
|
||||
static const unsigned char g_s[7] = { 0x00, 0x00, 0x0F, 0x10, 0x0E, 0x01, 0x1E };
|
||||
static const unsigned char g_t[7] = { 0x04, 0x04, 0x0E, 0x04, 0x04, 0x04, 0x03 };
|
||||
static const unsigned char g_u[7] = { 0x00, 0x00, 0x11, 0x11, 0x11, 0x13, 0x0D };
|
||||
static const unsigned char g_0[7] = { 0x0E, 0x11, 0x13, 0x15, 0x19, 0x11, 0x0E };
|
||||
static const unsigned char g_1[7] = { 0x04, 0x0C, 0x04, 0x04, 0x04, 0x04, 0x0E };
|
||||
static const unsigned char g_2[7] = { 0x0E, 0x11, 0x01, 0x06, 0x08, 0x10, 0x1F };
|
||||
static const unsigned char g_3[7] = { 0x0E, 0x11, 0x01, 0x06, 0x01, 0x11, 0x0E };
|
||||
static const unsigned char g_4[7] = { 0x02, 0x06, 0x0A, 0x12, 0x1F, 0x02, 0x02 };
|
||||
static const unsigned char g_5[7] = { 0x1F, 0x10, 0x1E, 0x01, 0x01, 0x11, 0x0E };
|
||||
static const unsigned char g_6[7] = { 0x06, 0x08, 0x10, 0x1E, 0x11, 0x11, 0x0E };
|
||||
static const unsigned char g_7[7] = { 0x1F, 0x01, 0x02, 0x04, 0x08, 0x08, 0x08 };
|
||||
static const unsigned char g_8[7] = { 0x0E, 0x11, 0x11, 0x0E, 0x11, 0x11, 0x0E };
|
||||
static const unsigned char g_9[7] = { 0x0E, 0x11, 0x11, 0x0F, 0x01, 0x02, 0x0C };
|
||||
static const unsigned char g_dash[7] = { 0x00, 0x00, 0x00, 0x0E, 0x00, 0x00, 0x00 };
|
||||
static const unsigned char g_colon[7] = { 0x00, 0x0C, 0x0C, 0x00, 0x0C, 0x0C, 0x00 };
|
||||
switch (c) {
|
||||
case ' ': return g_space;
|
||||
case '.': return g_dot;
|
||||
@@ -116,6 +136,18 @@ static const unsigned char *font_glyph(char c)
|
||||
case 's': return g_s;
|
||||
case 't': return g_t;
|
||||
case 'u': return g_u;
|
||||
case '0': return g_0;
|
||||
case '1': return g_1;
|
||||
case '2': return g_2;
|
||||
case '3': return g_3;
|
||||
case '4': return g_4;
|
||||
case '5': return g_5;
|
||||
case '6': return g_6;
|
||||
case '7': return g_7;
|
||||
case '8': return g_8;
|
||||
case '9': return g_9;
|
||||
case '-': return g_dash;
|
||||
case ':': return g_colon;
|
||||
default: return g_space;
|
||||
}
|
||||
}
|
||||
@@ -420,10 +452,519 @@ static int pick_zoom(const Geotag *pts, int n)
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Shared map rendering (directory mode and --trip mode) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/* Fetch every tile in range r into img (w wide, already allocated).
|
||||
* Returns 0 on success, -1 on any fetch or decode failure. */
|
||||
static int fetch_tiles(const char *base, const TileRange *r,
|
||||
unsigned char *img, int w)
|
||||
{
|
||||
curl_global_init(CURL_GLOBAL_DEFAULT);
|
||||
int failed = 0;
|
||||
for (int ty = r->ty0; ty <= r->ty1 && !failed; ty++) {
|
||||
for (int tx = r->tx0; tx <= r->tx1 && !failed; tx++) {
|
||||
MemBuf m = { NULL, 0, 0 };
|
||||
if (fetch_tile(base, r->zoom, tx, ty, &m) != 0) {
|
||||
free(m.data);
|
||||
failed = 1;
|
||||
break;
|
||||
}
|
||||
int tw = 0, th = 0;
|
||||
unsigned char *tile = decode_png(m.data, m.len, &tw, &th);
|
||||
free(m.data);
|
||||
if (!tile) {
|
||||
fprintf(stderr, "%s: tile %d/%d/%d is not a decodable PNG\n",
|
||||
prog, r->zoom, tx, ty);
|
||||
failed = 1;
|
||||
break;
|
||||
}
|
||||
int cw = tw < TILE_PX ? tw : TILE_PX;
|
||||
int ch = th < TILE_PX ? th : TILE_PX;
|
||||
int dx = (tx - r->tx0) * TILE_PX, dy = (ty - r->ty0) * TILE_PX;
|
||||
for (int row = 0; row < ch; row++)
|
||||
memcpy(img + ((size_t)(dy + row) * w + dx) * 3,
|
||||
tile + (size_t)row * tw * 3, (size_t)cw * 3);
|
||||
free(tile);
|
||||
}
|
||||
}
|
||||
curl_global_cleanup();
|
||||
return failed ? -1 : 0;
|
||||
}
|
||||
|
||||
/* Attribution, drawn on the image: white plaque, black text,
|
||||
* bottom-left. Drawn last so it is never covered up. */
|
||||
static void draw_attribution(unsigned char *img, int w, int h)
|
||||
{
|
||||
static const char attr[] = "\xC2\xA9 OpenStreetMap contributors";
|
||||
int tw = text_width(attr);
|
||||
int px = 4, py = h - 15;
|
||||
if (py < 0) py = 0;
|
||||
fill_rect(img, w, h, px, py, tw + 8, 13, 255, 255, 255);
|
||||
draw_text(img, w, h, px + 4, py + 3, attr, 0, 0, 0);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Trip mode: sgeo --trip <csv> [outfile] */
|
||||
/* */
|
||||
/* Reads a stag CSV (docs/stag-sgeo.md), orders the geotagged rows by */
|
||||
/* their timestamp, and draws the journey as an ordered polyline -- */
|
||||
/* a blue line with a white halo, an arrowhead per leg showing the */
|
||||
/* direction of travel, a red marker per stop, and a time label */
|
||||
/* ("MM-DD HH:MM", UTC, as stag printed it) next to each marker. */
|
||||
/* Rows without a timestamp go last, in CSV order; rows with no */
|
||||
/* coordinates are skipped (the CSV's empty-coords rule). A single */
|
||||
/* point draws just its marker and label, like the directory mode. */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
typedef struct {
|
||||
Geotag g; /* latitude/longitude, timestamp text */
|
||||
char file[256]; /* basename, for diagnostics only */
|
||||
long long tkey; /* sortable timestamp, LLONG_MAX when unknown */
|
||||
int has_time; /* timestamp parsed */
|
||||
int has_clock; /* timestamp included a time of day */
|
||||
int mo, dy, hh, mi; /* label pieces */
|
||||
int order; /* CSV row order: tiebreak */
|
||||
} TripPoint;
|
||||
|
||||
/* Timestamp order; ties (including all timestamp-less rows) keep CSV
|
||||
* order, so the path is deterministic. */
|
||||
static int trip_cmp(const void *a, const void *b)
|
||||
{
|
||||
const TripPoint *x = a, *y = b;
|
||||
if (x->tkey != y->tkey) return x->tkey < y->tkey ? -1 : 1;
|
||||
return x->order - y->order;
|
||||
}
|
||||
|
||||
/* Filled disc, used as the brush for the path line. */
|
||||
static void draw_disc(unsigned char *img, int w, int h, int cx, int cy, int r,
|
||||
unsigned char R, unsigned char G, unsigned char B)
|
||||
{
|
||||
for (int dy = -r; dy <= r; dy++)
|
||||
for (int dx = -r; dx <= r; dx++)
|
||||
if (dx * dx + dy * dy <= r * r)
|
||||
put_px(img, w, h, cx + dx, cy + dy, R, G, B);
|
||||
}
|
||||
|
||||
/* One leg of the journey: a blue line with a white halo, stamped as
|
||||
* discs along a Bresenham walk so it stays visible over the tiles.
|
||||
* Two passes: the whole halo first, then the whole core. (Stamping
|
||||
* both at each step would let each step's halo paint over the
|
||||
* previous step's core, leaving a white line.) */
|
||||
static void draw_path_seg(unsigned char *img, int w, int h,
|
||||
int x0, int y0, int x1, int y1)
|
||||
{
|
||||
for (int pass = 0; pass < 2; pass++) {
|
||||
int dx = abs(x1 - x0), sx = x0 < x1 ? 1 : -1;
|
||||
int dy = -abs(y1 - y0), sy = y0 < y1 ? 1 : -1;
|
||||
int err = dx + dy, x = x0, y = y0;
|
||||
for (;;) {
|
||||
if (pass == 0) draw_disc(img, w, h, x, y, 4, 255, 255, 255);
|
||||
else draw_disc(img, w, h, x, y, 2, 0, 0, 255);
|
||||
if (x == x1 && y == y1) break;
|
||||
int e2 = 2 * err;
|
||||
if (e2 >= dy) { err += dy; x += sx; }
|
||||
if (e2 <= dx) { err += dx; y += sy; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static double tri_sign(double x1, double y1, double x2, double y2,
|
||||
double x3, double y3)
|
||||
{
|
||||
return (x1 - x3) * (y2 - y3) - (x2 - x3) * (y1 - y3);
|
||||
}
|
||||
|
||||
static int in_tri(double px, double py,
|
||||
double ax, double ay, double bx, double by,
|
||||
double cx, double cy)
|
||||
{
|
||||
double d1 = tri_sign(px, py, ax, ay, bx, by);
|
||||
double d2 = tri_sign(px, py, bx, by, cx, cy);
|
||||
double d3 = tri_sign(px, py, cx, cy, ax, ay);
|
||||
int neg = (d1 < 0) || (d2 < 0) || (d3 < 0);
|
||||
int pos = (d1 > 0) || (d2 > 0) || (d3 > 0);
|
||||
return !(neg && pos);
|
||||
}
|
||||
|
||||
/* Direction arrow at the midpoint of a leg: a small filled triangle
|
||||
* pointing along the leg, blue with a white halo. Only drawn when the
|
||||
* leg is long enough that the arrow clears both markers. */
|
||||
static void draw_arrow(unsigned char *img, int w, int h,
|
||||
int x0, int y0, int x1, int y1)
|
||||
{
|
||||
double dx = (double)(x1 - x0), dy = (double)(y1 - y0);
|
||||
double len = sqrt(dx * dx + dy * dy);
|
||||
if (len < 80.0) return;
|
||||
double ux = dx / len, uy = dy / len; /* along the leg */
|
||||
double px = -uy, py = ux; /* perpendicular */
|
||||
double mx = (x0 + x1) / 2.0, my = (y0 + y1) / 2.0;
|
||||
/* tip 9px ahead, base 7px back, half-width 5px */
|
||||
double ax = mx + ux * 9, ay = my + uy * 9;
|
||||
double bx = mx - ux * 7 + px * 5, by = my - uy * 7 + py * 5;
|
||||
double cx = mx - ux * 7 - px * 5, cy = my - uy * 7 - py * 5;
|
||||
/* halo: same triangle grown 1.6x about its centroid */
|
||||
double gx = (ax + bx + cx) / 3.0, gy = (ay + by + cy) / 3.0;
|
||||
double ax2 = gx + (ax - gx) * 1.6, ay2 = gy + (ay - gy) * 1.6;
|
||||
double bx2 = gx + (bx - gx) * 1.6, by2 = gy + (by - gy) * 1.6;
|
||||
double cx2 = gx + (cx - gx) * 1.6, cy2 = gy + (cy - gy) * 1.6;
|
||||
int minx = (int)floor(fmin(fmin(ax2, bx2), cx2)) - 1;
|
||||
int maxx = (int)ceil(fmax(fmax(ax2, bx2), cx2)) + 1;
|
||||
int miny = (int)floor(fmin(fmin(ay2, by2), cy2)) - 1;
|
||||
int maxy = (int)ceil(fmax(fmax(ay2, by2), cy2)) + 1;
|
||||
for (int y = miny; y <= maxy; y++) {
|
||||
for (int x = minx; x <= maxx; x++) {
|
||||
double cxp = x + 0.5, cyp = y + 0.5;
|
||||
if (in_tri(cxp, cyp, ax2, ay2, bx2, by2, cx2, cy2))
|
||||
put_px(img, w, h, x, y, 255, 255, 255);
|
||||
if (in_tri(cxp, cyp, ax, ay, bx, by, cx, cy))
|
||||
put_px(img, w, h, x, y, 0, 0, 255);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Time label next to a marker: white plaque, black text, upper-right
|
||||
* of the marker, flipped to the left (or below) at the image edge. */
|
||||
static void draw_time_label(unsigned char *img, int w, int h,
|
||||
int mx, int my, const char *text)
|
||||
{
|
||||
int tw = text_width(text);
|
||||
int lx = mx + 12, ly = my - 18;
|
||||
if (lx + tw + 8 > w) lx = mx - 12 - (tw + 8);
|
||||
if (lx < 0) lx = 0;
|
||||
if (ly < 0) ly = my + 12;
|
||||
if (ly + 13 > h) ly = h - 13;
|
||||
if (ly < 0) ly = 0;
|
||||
fill_rect(img, w, h, lx, ly, tw + 8, 13, 255, 255, 255);
|
||||
draw_text(img, w, h, lx + 4, ly + 3, text, 0, 0, 0);
|
||||
}
|
||||
|
||||
/* ---- stag CSV reading ---- */
|
||||
|
||||
static void free_csv_fields(char **fields, int n)
|
||||
{
|
||||
if (!fields) return;
|
||||
for (int i = 0; i < n; i++) free(fields[i]);
|
||||
free(fields);
|
||||
}
|
||||
|
||||
static int csv_add_field(char ***fields, int *n, int *cap, const char *buf)
|
||||
{
|
||||
if (*n == *cap) {
|
||||
int nc = *cap ? *cap * 2 : 8;
|
||||
char **nf = realloc(*fields, sizeof *nf * (size_t)nc);
|
||||
if (!nf) return -1;
|
||||
*fields = nf; *cap = nc;
|
||||
}
|
||||
(*fields)[*n] = strdup(buf);
|
||||
if (!(*fields)[*n]) return -1;
|
||||
(*n)++;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Split one CSV line into fields. Handles stag's quoting: a field
|
||||
* containing ',' '"' or a newline is wrapped in '"' with '""' for a
|
||||
* quote. Returns the field count, or -1 on allocation failure.
|
||||
* Caller frees with free_csv_fields(). */
|
||||
static int split_csv_line(char *line, char ***out)
|
||||
{
|
||||
char **fields = NULL;
|
||||
int n = 0, cap = 0;
|
||||
char *buf = malloc(strlen(line) + 1);
|
||||
if (!buf) return -1;
|
||||
size_t blen = 0;
|
||||
int in_quotes = 0;
|
||||
int rc = -1;
|
||||
for (char *p = line; ; p++) {
|
||||
char c = *p;
|
||||
if (in_quotes) {
|
||||
if (c == '"') {
|
||||
if (p[1] == '"') { buf[blen++] = '"'; p++; }
|
||||
else in_quotes = 0;
|
||||
} else if (c == '\0') {
|
||||
buf[blen] = '\0'; /* unterminated quote: keep the field */
|
||||
if (csv_add_field(&fields, &n, &cap, buf) != 0) goto out;
|
||||
rc = n;
|
||||
goto out;
|
||||
} else buf[blen++] = c;
|
||||
continue;
|
||||
}
|
||||
if (c == '"') { in_quotes = 1; continue; }
|
||||
if (c == ',' || c == '\0') {
|
||||
buf[blen] = '\0';
|
||||
if (csv_add_field(&fields, &n, &cap, buf) != 0) goto out;
|
||||
blen = 0;
|
||||
if (c == '\0') { rc = n; goto out; }
|
||||
continue;
|
||||
}
|
||||
buf[blen++] = c;
|
||||
}
|
||||
out:
|
||||
free(buf);
|
||||
if (rc < 0) free_csv_fields(fields, n);
|
||||
else *out = fields;
|
||||
return rc;
|
||||
}
|
||||
|
||||
/* Parse a stag timestamp into a sort key. Accepts the ISO form the
|
||||
* decoder prints ("YYYY-MM-DD HH:MM:SS", date-only "YYYY-MM-DD") and
|
||||
* the EXIF-colon form the fallback path passes through
|
||||
* ("YYYY:MM:DD HH:MM:SS"). Returns 1 on success, filling the sort
|
||||
* key and the label pieces; 0 when there is no usable timestamp
|
||||
* (a time-only value is also 0: with no date it cannot be ordered). */
|
||||
static int parse_trip_time(const char *s, long long *key, int *has_clock,
|
||||
int *mo, int *dy, int *hh, int *mi)
|
||||
{
|
||||
int y = 0, m = 0, d = 0, h = 0, mn = 0, sec = 0, n = 0;
|
||||
if (!s || !*s) return 0;
|
||||
n = sscanf(s, "%d-%d-%d %d:%d:%d", &y, &m, &d, &h, &mn, &sec);
|
||||
if (n < 3)
|
||||
n = sscanf(s, "%d:%d:%d %d:%d:%d", &y, &m, &d, &h, &mn, &sec);
|
||||
if (n < 3) return 0;
|
||||
if (n < 6) { h = 0; mn = 0; sec = 0; }
|
||||
if (m < 1 || m > 12 || d < 1 || d > 31 || h < 0 || h > 23 ||
|
||||
mn < 0 || mn > 59 || sec < 0 || sec > 59) return 0;
|
||||
*key = (((((long long)y * 12 + (m - 1)) * 31 + (d - 1)) * 24 + h) * 60 + mn) * 60 + sec;
|
||||
*has_clock = (n >= 5);
|
||||
*mo = m; *dy = d; *hh = h; *mi = mn;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* "MM-DD HH:MM" for a full timestamp, "MM-DD" for a date-only one.
|
||||
* The year is omitted: a trip path fits on one map, and the year is
|
||||
* in the CSV. Times are UTC, as stag prints them. */
|
||||
static void trip_label(char *buf, size_t n, const TripPoint *t)
|
||||
{
|
||||
if (t->has_clock)
|
||||
snprintf(buf, n, "%02d-%02d %02d:%02d", t->mo, t->dy, t->hh, t->mi);
|
||||
else
|
||||
snprintf(buf, n, "%02d-%02d", t->mo, t->dy);
|
||||
}
|
||||
|
||||
/* Strict decimal: strtod must consume the whole field (modulo
|
||||
* surrounding blanks). Returns 1 on success. */
|
||||
static int parse_coord(const char *s, double *v)
|
||||
{
|
||||
if (!s || !*s) return 0;
|
||||
char *end = NULL;
|
||||
double x = strtod(s, &end);
|
||||
if (end == s) return 0;
|
||||
while (*end == ' ' || *end == '\t') end++;
|
||||
if (*end != '\0') return 0;
|
||||
*v = x;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Read a stag CSV into timestamp-sorted TripPoints. Returns 0 on
|
||||
* success, -1 on any fatal problem (unreadable file, bad header, no
|
||||
* geotagged rows). Rows with empty coordinates are skipped silently
|
||||
* (the CSV's empty-coords rule); rows with garbage coordinates are
|
||||
* warned about and skipped. *out_rows counts data rows seen. */
|
||||
static int read_trip_csv(const char *path, TripPoint **out_pts, int *out_n,
|
||||
int *out_rows)
|
||||
{
|
||||
FILE *fp = fopen(path, "r");
|
||||
if (!fp) {
|
||||
fprintf(stderr, "%s: cannot read '%s': %s\n", prog, path, strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
char *line = NULL;
|
||||
size_t cap = 0;
|
||||
ssize_t len = getline(&line, &cap, fp);
|
||||
if (len < 0) {
|
||||
fprintf(stderr, "%s: '%s' is empty -- not a stag CSV\n", prog, path);
|
||||
fclose(fp);
|
||||
free(line);
|
||||
return -1;
|
||||
}
|
||||
while (len > 0 && (line[len-1] == '\n' || line[len-1] == '\r')) line[--len] = '\0';
|
||||
{
|
||||
static const char want[] = "file,format,latitude,longitude";
|
||||
size_t wlen = strlen(want);
|
||||
if (strncmp(line, want, wlen) != 0 ||
|
||||
(line[wlen] != ',' && line[wlen] != '\0')) {
|
||||
fprintf(stderr, "%s: '%s' is not a stag CSV (bad header -- expected "
|
||||
"'file,format,latitude,longitude,...')\n", prog, path);
|
||||
fclose(fp);
|
||||
free(line);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
TripPoint *pts = NULL;
|
||||
int npts = 0, rows = 0, skipped = 0;
|
||||
int rc = -1;
|
||||
while ((len = getline(&line, &cap, fp)) >= 0) {
|
||||
while (len > 0 && (line[len-1] == '\n' || line[len-1] == '\r')) line[--len] = '\0';
|
||||
if (len == 0) continue; /* blank line */
|
||||
rows++;
|
||||
char **f = NULL;
|
||||
int nf = split_csv_line(line, &f);
|
||||
if (nf < 0) {
|
||||
fprintf(stderr, "%s: out of memory\n", prog);
|
||||
goto out;
|
||||
}
|
||||
if (nf < 7) {
|
||||
fprintf(stderr, "%s: skipping malformed row %d (%d field(s))\n", prog, rows, nf);
|
||||
free_csv_fields(f, nf);
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
double lat = 0, lon = 0;
|
||||
if (f[2][0] == '\0' && f[3][0] == '\0') {
|
||||
free_csv_fields(f, nf); /* no geotag: the empty-coords rule */
|
||||
continue;
|
||||
}
|
||||
if (!parse_coord(f[2], &lat) || !parse_coord(f[3], &lon) ||
|
||||
lat < -90.0 || lat > 90.0 || lon < -180.0 || lon > 180.0) {
|
||||
fprintf(stderr, "%s: skipping row %d ('%s'): bad coordinates\n", prog, rows, f[0]);
|
||||
free_csv_fields(f, nf);
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
TripPoint *nb = realloc(pts, sizeof *pts * (size_t)(npts + 1));
|
||||
if (!nb) { fprintf(stderr, "%s: out of memory\n", prog); free_csv_fields(f, nf); goto out; }
|
||||
pts = nb;
|
||||
TripPoint *t = &pts[npts];
|
||||
memset(t, 0, sizeof *t);
|
||||
t->g.latitude = lat;
|
||||
t->g.longitude = lon;
|
||||
t->g.found = 1;
|
||||
snprintf(t->g.timestamp, sizeof t->g.timestamp, "%s", f[6]);
|
||||
snprintf(t->file, sizeof t->file, "%s", f[0]);
|
||||
t->order = rows;
|
||||
t->tkey = LLONG_MAX;
|
||||
{
|
||||
long long key = 0;
|
||||
int hc = 0, mo = 0, dy = 0, hh = 0, mi = 0;
|
||||
if (parse_trip_time(f[6], &key, &hc, &mo, &dy, &hh, &mi)) {
|
||||
t->tkey = key;
|
||||
t->has_time = 1;
|
||||
t->has_clock = hc;
|
||||
t->mo = mo; t->dy = dy; t->hh = hh; t->mi = mi;
|
||||
}
|
||||
}
|
||||
npts++;
|
||||
free_csv_fields(f, nf);
|
||||
}
|
||||
if (npts == 0) {
|
||||
fprintf(stderr, "%s: no geotagged rows in '%s' -- nothing to plot\n", prog, path);
|
||||
goto out;
|
||||
}
|
||||
qsort(pts, (size_t)npts, sizeof *pts, trip_cmp);
|
||||
if (skipped)
|
||||
fprintf(stderr, "%s: skipped %d malformed row(s)\n", prog, skipped);
|
||||
*out_pts = pts;
|
||||
*out_n = npts;
|
||||
*out_rows = rows;
|
||||
rc = 0;
|
||||
out:
|
||||
if (rc != 0) free(pts);
|
||||
fclose(fp);
|
||||
free(line);
|
||||
return rc;
|
||||
}
|
||||
|
||||
static int trip_main(int argc, char **argv)
|
||||
{
|
||||
const char *csv = NULL;
|
||||
const char *outfile = "trip.png";
|
||||
if (argc > 1) csv = argv[1];
|
||||
if (argc > 2) outfile = argv[2];
|
||||
if (!csv || argc > 3) {
|
||||
fprintf(stderr, "usage: sgeo --trip <csv> [outfile]\n");
|
||||
return 2;
|
||||
}
|
||||
|
||||
TripPoint *trip = NULL;
|
||||
int ntrip = 0, rows = 0;
|
||||
if (read_trip_csv(csv, &trip, &ntrip, &rows) != 0)
|
||||
return 1;
|
||||
|
||||
Geotag *pts = malloc(sizeof *pts * (size_t)ntrip);
|
||||
if (!pts) { fprintf(stderr, "%s: out of memory\n", prog); free(trip); return 1; }
|
||||
int ntimed = 0;
|
||||
for (int i = 0; i < ntrip; i++) {
|
||||
pts[i] = trip[i].g;
|
||||
if (trip[i].has_time) ntimed++;
|
||||
}
|
||||
|
||||
int zoom = pick_zoom(pts, ntrip);
|
||||
double *xs = malloc(sizeof *xs * (size_t)ntrip);
|
||||
double *ys = malloc(sizeof *ys * (size_t)ntrip);
|
||||
if (!xs || !ys) {
|
||||
fprintf(stderr, "%s: out of memory\n", prog);
|
||||
free(xs); free(ys); free(pts); free(trip);
|
||||
return 1;
|
||||
}
|
||||
for (int i = 0; i < ntrip; i++) {
|
||||
xs[i] = lon_to_px(pts[i].longitude, zoom);
|
||||
ys[i] = lat_to_px(pts[i].latitude, zoom);
|
||||
}
|
||||
TileRange r;
|
||||
compute_range(xs, ys, ntrip, zoom, &r);
|
||||
int w = (r.tx1 - r.tx0 + 1) * TILE_PX;
|
||||
int h = (r.ty1 - r.ty0 + 1) * TILE_PX;
|
||||
int ox = r.tx0 * TILE_PX, oy = r.ty0 * TILE_PX;
|
||||
|
||||
unsigned char *img = malloc((size_t)w * h * 3);
|
||||
if (!img) {
|
||||
fprintf(stderr, "%s: out of memory\n", prog);
|
||||
free(xs); free(ys); free(pts); free(trip);
|
||||
return 1;
|
||||
}
|
||||
memset(img, 0xF2, (size_t)w * h * 3);
|
||||
|
||||
const char *base = getenv("SGEO_TILE_BASE");
|
||||
if (!base || !*base) base = "https://tile.openstreetmap.org";
|
||||
int rc = 1;
|
||||
if (fetch_tiles(base, &r, img, w) != 0) goto done;
|
||||
|
||||
/* The journey, in timestamp order: legs, then direction arrows,
|
||||
* then markers, then time labels. Markers sit on top of the line. */
|
||||
for (int i = 1; i < ntrip; i++)
|
||||
draw_path_seg(img, w, h,
|
||||
(int)lrint(xs[i - 1]) - ox, (int)lrint(ys[i - 1]) - oy,
|
||||
(int)lrint(xs[i]) - ox, (int)lrint(ys[i]) - oy);
|
||||
for (int i = 1; i < ntrip; i++)
|
||||
draw_arrow(img, w, h,
|
||||
(int)lrint(xs[i - 1]) - ox, (int)lrint(ys[i - 1]) - oy,
|
||||
(int)lrint(xs[i]) - ox, (int)lrint(ys[i]) - oy);
|
||||
for (int i = 0; i < ntrip; i++)
|
||||
draw_marker(img, w, h, (int)lrint(xs[i]) - ox, (int)lrint(ys[i]) - oy);
|
||||
for (int i = 0; i < ntrip; i++) {
|
||||
if (!trip[i].has_time) continue;
|
||||
char label[16];
|
||||
trip_label(label, sizeof label, &trip[i]);
|
||||
draw_time_label(img, w, h,
|
||||
(int)lrint(xs[i]) - ox, (int)lrint(ys[i]) - oy, label);
|
||||
}
|
||||
|
||||
draw_attribution(img, w, h);
|
||||
|
||||
if (write_png(outfile, img, w, h) != 0) {
|
||||
remove(outfile);
|
||||
goto done;
|
||||
}
|
||||
fprintf(stderr, "%s: %d row(s) in '%s', %d point(s), %d with timestamps, "
|
||||
"zoom %d, %dx%d, %d tile(s) -> %s\n",
|
||||
prog, rows, csv, ntrip, ntimed, zoom, w, h, tile_count(&r), outfile);
|
||||
rc = 0;
|
||||
done:
|
||||
free(img);
|
||||
free(xs); free(ys);
|
||||
free(pts);
|
||||
free(trip);
|
||||
return rc;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
if (argc > 1 && strcmp(argv[1], "--trip") == 0)
|
||||
return trip_main(argc - 1, argv + 1);
|
||||
|
||||
const char *dir = ".";
|
||||
const char *outfile = "map.png";
|
||||
if (argc > 1) dir = argv[1];
|
||||
@@ -488,50 +1029,13 @@ int main(int argc, char **argv)
|
||||
|
||||
const char *base = getenv("SGEO_TILE_BASE");
|
||||
if (!base || !*base) base = "https://tile.openstreetmap.org";
|
||||
curl_global_init(CURL_GLOBAL_DEFAULT);
|
||||
int fetch_failed = 0;
|
||||
for (int ty = r.ty0; ty <= r.ty1 && !fetch_failed; ty++) {
|
||||
for (int tx = r.tx0; tx <= r.tx1 && !fetch_failed; tx++) {
|
||||
MemBuf m = { NULL, 0, 0 };
|
||||
if (fetch_tile(base, zoom, tx, ty, &m) != 0) {
|
||||
free(m.data);
|
||||
fetch_failed = 1;
|
||||
break;
|
||||
}
|
||||
int tw = 0, th = 0;
|
||||
unsigned char *tile = decode_png(m.data, m.len, &tw, &th);
|
||||
free(m.data);
|
||||
if (!tile) {
|
||||
fprintf(stderr, "%s: tile %d/%d/%d is not a decodable PNG\n",
|
||||
prog, zoom, tx, ty);
|
||||
fetch_failed = 1;
|
||||
break;
|
||||
}
|
||||
int cw = tw < TILE_PX ? tw : TILE_PX;
|
||||
int ch = th < TILE_PX ? th : TILE_PX;
|
||||
int dx = (tx - r.tx0) * TILE_PX, dy = (ty - r.ty0) * TILE_PX;
|
||||
for (int row = 0; row < ch; row++)
|
||||
memcpy(img + ((size_t)(dy + row) * w + dx) * 3,
|
||||
tile + (size_t)row * tw * 3, (size_t)cw * 3);
|
||||
free(tile);
|
||||
}
|
||||
}
|
||||
curl_global_cleanup();
|
||||
if (fetch_failed) { free(img); free(xs); free(ys); goto done; }
|
||||
if (fetch_tiles(base, &r, img, w) != 0) { free(img); free(xs); free(ys); goto done; }
|
||||
|
||||
for (int i = 0; i < npts; i++)
|
||||
draw_marker(img, w, h, (int)lrint(xs[i]) - ox, (int)lrint(ys[i]) - oy);
|
||||
free(xs); free(ys);
|
||||
|
||||
/* Attribution, drawn on the image: white plaque, black text. */
|
||||
{
|
||||
static const char attr[] = "\xC2\xA9 OpenStreetMap contributors";
|
||||
int tw = text_width(attr);
|
||||
int px = 4, py = h - 15;
|
||||
if (py < 0) py = 0;
|
||||
fill_rect(img, w, h, px, py, tw + 8, 13, 255, 255, 255);
|
||||
draw_text(img, w, h, px + 4, py + 3, attr, 0, 0, 0);
|
||||
}
|
||||
draw_attribution(img, w, h);
|
||||
|
||||
if (write_png(outfile, img, w, h) != 0) {
|
||||
remove(outfile);
|
||||
|
||||
@@ -0,0 +1,338 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check a trip.png produced by `sgeo --trip` (stdlib only).
|
||||
|
||||
Usage: check_trip.py trip.csv trip.png
|
||||
|
||||
Verifies, against the CSV:
|
||||
- one red marker cluster per geotagged row, centred on the projected
|
||||
point (projection mirrors sgeo.c: Web Mercator, zoom from the
|
||||
bounding box, 64px padding);
|
||||
- a blue polyline leg between consecutive rows in timestamp order:
|
||||
blue pixels off the midpoint, so the arrowhead alone cannot pass,
|
||||
and blue at the midpoint too;
|
||||
- NO blue line where the CSV file order would have connected points
|
||||
(the first two wrong-order hops), proving the sort actually
|
||||
happened rather than the file order being drawn;
|
||||
- a time-label plaque (white + dark text) by every timestamped
|
||||
marker, and none by an untimestamped marker.
|
||||
The attribution plaque is checked by check_map.py in the suite.
|
||||
"""
|
||||
import csv
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from check_map import read_png
|
||||
|
||||
TILE_PX = 256
|
||||
MAX_TILES = 100
|
||||
TARGET_W = 900
|
||||
TARGET_H = 620
|
||||
PAD_PX = 64
|
||||
SINGLE_POINT_ZOOM = 15
|
||||
MAX_ZOOM = 18
|
||||
MAX_LAT = 85.05112878
|
||||
|
||||
|
||||
def world_px(z):
|
||||
return TILE_PX * (1 << z)
|
||||
|
||||
|
||||
def lon_to_px(lon, z):
|
||||
return (lon + 180.0) / 360.0 * world_px(z)
|
||||
|
||||
|
||||
def lat_to_px(lat, z):
|
||||
lat = max(-MAX_LAT, min(MAX_LAT, lat))
|
||||
r = math.radians(lat)
|
||||
return (1.0 - math.asinh(math.tan(r)) / math.pi) / 2.0 * world_px(z)
|
||||
|
||||
|
||||
def compute_range(xs, ys, zoom):
|
||||
minx, maxx = min(xs), max(xs)
|
||||
miny, maxy = min(ys), max(ys)
|
||||
ntiles = 1 << zoom
|
||||
tx0 = max(0, math.floor((minx - PAD_PX) / TILE_PX))
|
||||
tx1 = min(ntiles - 1, math.floor((maxx + PAD_PX) / TILE_PX))
|
||||
ty0 = max(0, math.floor((miny - PAD_PX) / TILE_PX))
|
||||
ty1 = min(ntiles - 1, math.floor((maxy + PAD_PX) / TILE_PX))
|
||||
return zoom, tx0, ty0, tx1, ty1
|
||||
|
||||
|
||||
def pick_zoom(pts):
|
||||
minlon = min(p[1] for p in pts)
|
||||
maxlon = max(p[1] for p in pts)
|
||||
minlat = min(p[0] for p in pts)
|
||||
maxlat = max(p[0] for p in pts)
|
||||
lon_span = (maxlon - minlon) / 360.0
|
||||
y0 = lat_to_px(minlat, 0) / world_px(0)
|
||||
y1 = lat_to_px(maxlat, 0) / world_px(0)
|
||||
lat_span = abs(y1 - y0)
|
||||
if lon_span == 0.0 and lat_span == 0.0:
|
||||
return SINGLE_POINT_ZOOM
|
||||
zoom = 0
|
||||
for z in range(MAX_ZOOM, -1, -1):
|
||||
if (lon_span * world_px(z) <= TARGET_W
|
||||
and lat_span * world_px(z) <= TARGET_H):
|
||||
zoom = z
|
||||
break
|
||||
while True:
|
||||
xs = [lon_to_px(p[1], zoom) for p in pts]
|
||||
ys = [lat_to_px(p[0], zoom) for p in pts]
|
||||
_, tx0, ty0, tx1, ty1 = compute_range(xs, ys, zoom)
|
||||
if (tx1 - tx0 + 1) * (ty1 - ty0 + 1) <= MAX_TILES or zoom == 0:
|
||||
return zoom
|
||||
zoom -= 1
|
||||
|
||||
|
||||
def parse_time(s):
|
||||
"""Mirror sgeo's parse_trip_time: ISO or EXIF-colon, date-only ok.
|
||||
Returns a dict, or None."""
|
||||
m = re.match(r"^(\d+)-(\d+)-(\d+)(?: (\d+):(\d+)(?::(\d+))?)?$", s or "")
|
||||
if not m:
|
||||
m = re.match(r"^(\d+):(\d+):(\d+)(?: (\d+):(\d+)(?::(\d+))?)?$",
|
||||
s or "")
|
||||
if not m:
|
||||
return None
|
||||
y, mo, d = int(m.group(1)), int(m.group(2)), int(m.group(3))
|
||||
has_clock = m.group(5) is not None
|
||||
h = int(m.group(4) or 0) if has_clock else 0
|
||||
mi = int(m.group(5) or 0) if has_clock else 0
|
||||
sec = int(m.group(6) or 0) if has_clock else 0
|
||||
if not (1 <= mo <= 12 and 1 <= d <= 31 and 0 <= h <= 23
|
||||
and 0 <= mi <= 59 and 0 <= sec <= 59):
|
||||
return None
|
||||
key = (((((y * 12 + (mo - 1)) * 31 + (d - 1)) * 24 + h) * 60 + mi)
|
||||
* 60 + sec)
|
||||
return {"key": key, "has_clock": has_clock, "mo": mo, "dy": d,
|
||||
"hh": h, "mi": mi}
|
||||
|
||||
|
||||
def label_text(t):
|
||||
if t["has_clock"]:
|
||||
return "%02d-%02d %02d:%02d" % (t["mo"], t["dy"], t["hh"], t["mi"])
|
||||
return "%02d-%02d" % (t["mo"], t["dy"])
|
||||
|
||||
|
||||
def label_rect(mx, my, text, w, h):
|
||||
"""Mirror sgeo's draw_time_label placement."""
|
||||
tw = len(text) * 6 - 1
|
||||
lx, ly = mx + 12, my - 18
|
||||
if lx + tw + 8 > w:
|
||||
lx = mx - 12 - (tw + 8)
|
||||
if lx < 0:
|
||||
lx = 0
|
||||
if ly < 0:
|
||||
ly = my + 12
|
||||
if ly + 13 > h:
|
||||
ly = h - 13
|
||||
if ly < 0:
|
||||
ly = 0
|
||||
return lx, ly, tw + 8, 13
|
||||
|
||||
|
||||
def dist_pt_seg(px, py, x0, y0, x1, y1):
|
||||
dx, dy = x1 - x0, y1 - y0
|
||||
dd = dx * dx + dy * dy
|
||||
if dd == 0:
|
||||
return math.hypot(px - x0, py - y0)
|
||||
t = max(0.0, min(1.0, ((px - x0) * dx + (py - y0) * dy) / dd))
|
||||
return math.hypot(px - (x0 + t * dx), py - (y0 + t * dy))
|
||||
|
||||
|
||||
def main():
|
||||
csv_path, png_path = sys.argv[1], sys.argv[2]
|
||||
rows = []
|
||||
with open(csv_path, newline="") as f:
|
||||
for i, row in enumerate(csv.DictReader(f)):
|
||||
if not row["latitude"] or not row["longitude"]:
|
||||
continue
|
||||
t = parse_time(row["timestamp"])
|
||||
rows.append({
|
||||
"file": row["file"],
|
||||
"lat": float(row["latitude"]),
|
||||
"lon": float(row["longitude"]),
|
||||
"order": i,
|
||||
"time": t,
|
||||
})
|
||||
ordered = sorted(rows, key=lambda r: (r["time"] is None,
|
||||
r["time"]["key"] if r["time"] else 0,
|
||||
r["order"]))
|
||||
pts = [(r["lat"], r["lon"]) for r in ordered]
|
||||
zoom = pick_zoom(pts)
|
||||
xs = [lon_to_px(p[1], zoom) for p in pts]
|
||||
ys = [lat_to_px(p[0], zoom) for p in pts]
|
||||
_, tx0, ty0, tx1, ty1 = compute_range(xs, ys, zoom)
|
||||
w, h, px = read_png(png_path)
|
||||
assert w == (tx1 - tx0 + 1) * TILE_PX, "width mismatch: %d" % w
|
||||
assert h == (ty1 - ty0 + 1) * TILE_PX, "height mismatch: %d" % h
|
||||
ox, oy = tx0 * TILE_PX, ty0 * TILE_PX
|
||||
mx = [int(round(x)) - ox for x in xs]
|
||||
my = [int(round(y)) - oy for y in ys]
|
||||
|
||||
def rgb(x, y):
|
||||
o = (y * w + x) * 3
|
||||
return px[o], px[o + 1], px[o + 2]
|
||||
|
||||
def is_blue(x, y):
|
||||
r, g, b = rgb(x, y)
|
||||
return b >= 200 and r <= 90 and g <= 90
|
||||
|
||||
def is_red(x, y):
|
||||
r, g, b = rgb(x, y)
|
||||
return r >= 200 and g <= 90 and b <= 90
|
||||
|
||||
def blue_near(x, y, rad=8):
|
||||
for dy in range(-rad, rad + 1):
|
||||
for dx in range(-rad, rad + 1):
|
||||
if dx * dx + dy * dy > rad * rad:
|
||||
continue
|
||||
xx, yy = x + dx, y + dy
|
||||
if 0 <= xx < w and 0 <= yy < h and is_blue(xx, yy):
|
||||
return True
|
||||
return False
|
||||
|
||||
fails = []
|
||||
|
||||
# 1. Red marker clusters: one per point, centred on the projection.
|
||||
red = [(x, y) for y in range(h) for x in range(w) if is_red(x, y)]
|
||||
parent = {}
|
||||
|
||||
def find(a):
|
||||
while parent[a] != a:
|
||||
parent[a] = parent[parent[a]]
|
||||
a = parent[a]
|
||||
return a
|
||||
|
||||
cells = {}
|
||||
for p in red:
|
||||
parent[p] = p
|
||||
cells.setdefault((p[0] // 4, p[1] // 4), []).append(p)
|
||||
for (x, y) in red:
|
||||
for cx in (x // 4 - 1, x // 4, x // 4 + 1):
|
||||
for cy in (y // 4 - 1, y // 4, y // 4 + 1):
|
||||
for q in cells.get((cx, cy), []):
|
||||
if q != (x, y) and abs(q[0] - x) <= 2 and abs(q[1] - y) <= 2:
|
||||
ra, rb = find((x, y)), find(q)
|
||||
if ra != rb:
|
||||
parent[ra] = rb
|
||||
groups = {}
|
||||
for p in red:
|
||||
groups.setdefault(find(p), []).append(p)
|
||||
clusters = [(sum(p[0] for p in ps) / len(ps),
|
||||
sum(p[1] for p in ps) / len(ps), len(ps))
|
||||
for ps in groups.values() if len(ps) >= 20]
|
||||
print("trip: %dx%d zoom=%d markers=%d (sizes %s)"
|
||||
% (w, h, zoom, len(clusters), sorted(c[2] for c in clusters)))
|
||||
if len(clusters) != len(pts):
|
||||
fails.append("marker clusters %d != points %d"
|
||||
% (len(clusters), len(pts)))
|
||||
else:
|
||||
unmatched = list(clusters)
|
||||
for i, (cx, cy) in enumerate(zip(mx, my)):
|
||||
best = min(unmatched,
|
||||
key=lambda c: (c[0] - cx) ** 2 + (c[1] - cy) ** 2)
|
||||
d = math.hypot(best[0] - cx, best[1] - cy)
|
||||
if d > 4:
|
||||
fails.append("marker %d off projection by %.1fpx"
|
||||
% (i, d))
|
||||
unmatched.remove(best)
|
||||
|
||||
# Label plaque rects (for skipping line samples hidden under them).
|
||||
plaques = []
|
||||
for i, r in enumerate(ordered):
|
||||
if r["time"]:
|
||||
plaques.append(label_rect(mx[i], my[i], label_text(r["time"]),
|
||||
w, h))
|
||||
|
||||
def in_plaque(x, y):
|
||||
for (lx, ly, pw, ph) in plaques:
|
||||
if lx - 2 <= x <= lx + pw + 2 and ly - 2 <= y <= ly + ph + 2:
|
||||
return True
|
||||
return False
|
||||
|
||||
# 2. Ordered legs: blue off the midpoint, and blue at the midpoint.
|
||||
for i in range(1, len(ordered)):
|
||||
x0, y0, x1, y1 = mx[i - 1], my[i - 1], mx[i], my[i]
|
||||
seg_len = math.hypot(x1 - x0, y1 - y0)
|
||||
off_mid = False
|
||||
tried = 0
|
||||
for t in (0.25, 0.4, 0.6, 0.75):
|
||||
sx, sy = int(round(x0 + t * (x1 - x0))), int(round(y0 + t * (y1 - y0)))
|
||||
if math.hypot(sx - x0, sy - y0) < 12:
|
||||
continue
|
||||
if math.hypot(sx - x1, sy - y1) < 12:
|
||||
continue
|
||||
if in_plaque(sx, sy):
|
||||
continue
|
||||
tried += 1
|
||||
if blue_near(sx, sy):
|
||||
off_mid = True
|
||||
break
|
||||
mid = blue_near((x0 + x1) // 2, (y0 + y1) // 2)
|
||||
print("leg %d->%d len=%.0fpx off-mid=%s (tried %d) mid=%s"
|
||||
% (i - 1, i, seg_len, off_mid, tried, mid))
|
||||
if not off_mid:
|
||||
fails.append("leg %d->%d: no blue off the midpoint" % (i - 1, i))
|
||||
if not mid:
|
||||
fails.append("leg %d->%d: no blue at the midpoint" % (i - 1, i))
|
||||
|
||||
# 3. Wrong-order hops (file order) must have NO blue at midpoint.
|
||||
file_order = sorted(rows, key=lambda r: r["order"])
|
||||
file_xy = []
|
||||
for r in file_order:
|
||||
j = ordered.index(r)
|
||||
file_xy.append((mx[j], my[j]))
|
||||
legs = [(mx[i - 1], my[i - 1], mx[i], my[i])
|
||||
for i in range(1, len(ordered))]
|
||||
for k in range(min(2, len(file_xy) - 1)):
|
||||
wx = (file_xy[k][0] + file_xy[k + 1][0]) // 2
|
||||
wy = (file_xy[k][1] + file_xy[k + 1][1]) // 2
|
||||
mind = min(dist_pt_seg(wx, wy, *leg) for leg in legs)
|
||||
print("wrong hop %d midpoint (%d,%d) min-dist-to-real-leg %.1fpx"
|
||||
% (k, wx, wy, mind))
|
||||
if mind <= 25:
|
||||
fails.append("wrong-hop probe %d inconclusive (%.1fpx from a "
|
||||
"real leg)" % (k, mind))
|
||||
elif blue_near(wx, wy):
|
||||
fails.append("wrong hop %d: blue line where file order would "
|
||||
"connect" % k)
|
||||
|
||||
# 4. Time labels: plaque + text by timestamped markers, none by the
|
||||
# untimestamped one.
|
||||
for i, r in enumerate(ordered):
|
||||
lx, ly, pw, ph = label_rect(mx[i], my[i],
|
||||
label_text(r["time"]) if r["time"]
|
||||
else "MM-DD HH:MM", w, h)
|
||||
white = dark = 0
|
||||
for y in range(max(0, ly), min(h, ly + ph)):
|
||||
for x in range(max(0, lx), min(w, lx + pw)):
|
||||
rr, gg, bb = rgb(x, y)
|
||||
if rr > 245 and gg > 245 and bb > 245:
|
||||
white += 1
|
||||
elif rr < 100 and gg < 100 and bb < 100:
|
||||
dark += 1
|
||||
if r["time"]:
|
||||
print("label %s: white=%d dark=%d" % (r["file"], white, dark))
|
||||
if white < 100 or dark < 5:
|
||||
fails.append("label %s: plaque/text missing (white=%d "
|
||||
"dark=%d)" % (r["file"], white, dark))
|
||||
else:
|
||||
print("no-label %s: white=%d dark=%d" % (r["file"], white, dark))
|
||||
if white >= 20:
|
||||
fails.append("untimestamped %s has a label plaque "
|
||||
"(white=%d)" % (r["file"], white))
|
||||
|
||||
if fails:
|
||||
print("check_trip: FAIL")
|
||||
for f in fails:
|
||||
print(" - " + f)
|
||||
return 1
|
||||
print("check_trip: PASS")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+57
-1
@@ -3,7 +3,9 @@
|
||||
# PATH=tests/bin:$PATH (fake `sfile` with canned GPS values)
|
||||
# SGEO_TILE_BASE=http://127.0.0.1:<port> (tests/tile_server.py)
|
||||
# Cases: multi-file dir (CSV byte-for-byte + map markers), single
|
||||
# point, no-geotag dir, empty dir, and the default outfiles.
|
||||
# point, no-geotag dir, empty dir, the default outfiles, and
|
||||
# sgeo --trip (ordered polyline + time labels from a synthetic CSV,
|
||||
# single point, and the failure cases).
|
||||
# Usage: ./tests/run_tests.sh (run from the repo root)
|
||||
set -u
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
@@ -99,5 +101,59 @@ else
|
||||
fail "default outfiles geotags.csv / map.png"
|
||||
fi
|
||||
|
||||
# 7. sgeo --trip: synthetic CSV, rows out of timestamp order.
|
||||
# b.jpg uses the EXIF-colon timestamp form stag's fallback passes
|
||||
# through, so the sort must handle mixed ISO/EXIF formats; e.jpg has
|
||||
# no timestamp and goes last; plain.jpg has no coords and is skipped.
|
||||
cat > "$TMP/trip.csv" <<'EOF'
|
||||
file,format,latitude,longitude,altitude,datum,timestamp,source
|
||||
c.jpg,JPEG image,37.784900,-122.379400,,WGS-84,2024-05-01 10:00:00,EXIF GPS
|
||||
a.jpg,JPEG image,37.774900,-122.419400,,WGS-84,2024-05-01 08:00:00,EXIF GPS
|
||||
d.jpg,JPEG image,37.754900,-122.439400,,WGS-84,2024-05-01 11:00:00,EXIF GPS
|
||||
b.jpg,JPEG image,37.804900,-122.409400,,WGS-84,2024:05:01 09:00:00,EXIF GPS
|
||||
e.jpg,JPEG image,37.794900,-122.439400,,WGS-84,,EXIF GPS
|
||||
plain.jpg,JPEG image,,,,,,
|
||||
EOF
|
||||
if ./sgeo --trip "$TMP/trip.csv" "$TMP/trip.png" 2>"$TMP/trip.log"; then
|
||||
python3 tests/check_map.py "$TMP/trip.png" 5 >/tmp/check-trip-map.txt 2>&1 \
|
||||
&& python3 tests/check_trip.py "$TMP/trip.csv" "$TMP/trip.png" >/tmp/check-trip.txt 2>&1 \
|
||||
&& pass "sgeo --trip ordered polyline + time labels" \
|
||||
|| { fail "sgeo --trip ordered polyline + time labels"; cat /tmp/check-trip-map.txt /tmp/check-trip.txt "$TMP/trip.log"; }
|
||||
else
|
||||
fail "sgeo --trip exit 0"; cat "$TMP/trip.log"
|
||||
fi
|
||||
|
||||
# 8. sgeo --trip: single point (marker + label, no line).
|
||||
cat > "$TMP/trip-one.csv" <<'EOF'
|
||||
file,format,latitude,longitude,altitude,datum,timestamp,source
|
||||
a.jpg,JPEG image,37.774900,-122.419400,,WGS-84,2024-05-01 08:00:00,EXIF GPS
|
||||
EOF
|
||||
if ./sgeo --trip "$TMP/trip-one.csv" "$TMP/trip-one.png" 2>/dev/null; then
|
||||
python3 tests/check_map.py "$TMP/trip-one.png" 1 >/tmp/check-trip1.txt 2>&1 \
|
||||
&& pass "sgeo --trip single point" \
|
||||
|| { fail "sgeo --trip single point"; cat /tmp/check-trip1.txt; }
|
||||
else
|
||||
fail "sgeo --trip single point exit 0"
|
||||
fi
|
||||
|
||||
# 9. sgeo --trip failures: no geotags, bad header, missing file.
|
||||
# Each must exit non-zero, print its message, and write no file.
|
||||
cat > "$TMP/trip-nogeo.csv" <<'EOF'
|
||||
file,format,latitude,longitude,altitude,datum,timestamp,source
|
||||
plain.jpg,JPEG image,,,,,,
|
||||
EOF
|
||||
printf 'not,a,stag,csv\n1,2,3\n' > "$TMP/trip-bad.csv"
|
||||
trip_fail=0
|
||||
./sgeo --trip "$TMP/trip-nogeo.csv" "$TMP/trip-nogeo.png" 2>"$TMP/trip-nogeo.err" && trip_fail=1
|
||||
[ -e "$TMP/trip-nogeo.png" ] && trip_fail=1
|
||||
grep -q "no geotagged" "$TMP/trip-nogeo.err" || trip_fail=1
|
||||
./sgeo --trip "$TMP/trip-bad.csv" "$TMP/trip-bad.png" 2>"$TMP/trip-bad.err" && trip_fail=1
|
||||
[ -e "$TMP/trip-bad.png" ] && trip_fail=1
|
||||
grep -q "not a stag CSV" "$TMP/trip-bad.err" || trip_fail=1
|
||||
./sgeo --trip "$TMP/trip-missing.csv" "$TMP/trip-missing.png" 2>/dev/null && trip_fail=1
|
||||
[ -e "$TMP/trip-missing.png" ] && trip_fail=1
|
||||
[ "$trip_fail" = 0 ] && pass "sgeo --trip failures (no geotags, bad header, missing file)" \
|
||||
|| { fail "sgeo --trip failures"; cat "$TMP/trip-nogeo.err" "$TMP/trip-bad.err"; }
|
||||
|
||||
echo "stag/sgeo tests: $([ "$FAIL" = 0 ] && echo ALL PASS || echo FAILURES PRESENT)"
|
||||
exit "$FAIL"
|
||||
Reference in new issue
Block a user