zjt blog/A pirate autopilot for SailNavSim: from a 2020 Perl scraper to weather routing on a home PCSubscribe

A pirate autopilot for SailNavSim: from a 2020 Perl scraper to weather routing on a home PC

World map of surface wind direction from the GFS forecast
The wind the game sails on: SailNavSim's own global wind-direction map, drawn from NOAA's GFS forecast.Screenshot of SailNavSim's maps page, by ls4096.

October 2026. The autopilot races in a free online sailing simulator; every number below comes from its code, its tests or a live run, and anything untested is marked as such.

SailNavSim is a free online sailing simulator by ls4096. You get a boat in a race somewhere in the real world, real forecast wind, and a web page where you set a course. The boat sails on in real time whether you're watching or not, so a race takes hours to weeks, and the boats that do well are the ones whose skippers check in at the right moments. Or that have an autopilot.

In July 2020 I wrote one: a Perl script that read my boat's web page, worked out a course and set it. Six years later I found it again, and over one long day it turned into something much better: a Python service on my home PC that plans the fastest route round land using the same wind forecast and boat-speed tables the game uses, sails that route by itself, explains its plan in pirate talk from a local language model, and shows everything on an e-ink Kindle by the sofa — with buttons, voice commands and a chart.

This is how it works, and what went wrong on the way.

The whole post in ten-hundred words
The whole post in ten-hundred wordsDrawn in the style of xkcd, as a nod to Randall Munroe's Thing Explainer; lettering in the xkcd Script font, CC BY-NC 3.0

The game, briefly

Each race has a start, optional waypoint boxes you must pass through, and a finish box. You control two things: the boat's course (degrees true) and whether it's sailing or stopped. The simulator does the rest: it takes wind from NOAA's GFS forecast, computes your speed from your angle to the wind with a per-boat-type speed table (a polar), and moves your boat once a minute. Boats range from a 25-foot cruiser to a Volvo 70 and an America's Cup catamaran; some races hide your position entirely and make you navigate by the stars.

The game's engine is open source (sailnavsim-core), and so is its land and water data. That turned out to matter a lot.

SailNavSim's start page
SailNavSim's start pageScreenshot of 8bitbyte.ca/sailnavsim, the game by ls4096

2020: a Perl script that read web pages

The original sailnavsim.pl was about 350 lines of Perl. Every run it:

  1. Fetched the boat's page and pulled numbers out of the text with regular expressions: position, course, speed over ground, wind, the finish box's four corners in degrees-minutes-seconds, and the other boats' table.
  2. Converted the finish box to decimal degrees and aimed at its middle (or at one corner, or at a list of waypoints passed in through environment variables).
  3. Compared the bearing to the finish with the wind: if the finish was within 30° or so of dead upwind, it set a course 40° off; otherwise it steered straight at it.
  4. Restarted the boat if it had stopped, and posted the new course.

It ran in Docker on an AWS machine, one container per boat (there were seven, with names like popeye, thor and cyberboat), built by GitLab CI. It also printed a leaderboard, worked out from the other boats' distances to the finish.

It worked, mostly. Reading it again in 2026 showed why it sometimes didn't:

  • Scraping breaks silently. Any change in the page's wording left a variable empty, and the script carried on regardless.
  • No sanity checks. An empty course became course 0°: due north, wherever the finish was.
  • Angles were compared naively. abs($course_dir - $wind_dir) thinks 350° and 10° are 340° apart.
  • No idea of land. It steered straight at the finish, islands or not.
  • Dependency pain. The last commit is literally called "perl version oddities", and Geo::Point needs Geo::Proj4, which needs the PROJ C library and a compiler — it wouldn't install on my laptop at all.

2026: start again, in Python, against the JSON API

The site now has a JSON API: boatinfo.php for your boat (by its secret key), raceinfo.php for the race and the other boats, and boatcmd.php to send a command. That removed the reason Perl was there in the first place (the pQuery HTML scraper), so the rewrite is Python with nothing but the standard library: about 425 lines for the autopilot service and 425 for the route planner.

It runs as a Docker container on my always-on gaming PC. The boat key is a Docker secret (a file mounted at /run/secrets/boat_key), never logged and never served. The service polls the game once a minute and exposes two endpoints on my home network:

EndpointWhat it does
GET /statusThe boat, the target, the wind, the route, the fleet placings, the autopilot's state and the last thing it did
POST /cmdautopilot on/off, course (absolute), nudge (±degrees), start, stop, replan, choose a route option

Small decisions that fixed the old bugs:

  • Signed angle differences everywhere (angle_diff(a, b) returns a value in −180..180), so north is never "340° away" from north.
  • Great-circle bearings and distances, not flat-earth maths — races can be thousands of miles long.
  • Boxes across the 180° meridian (where the minimum longitude is larger than the maximum) are handled when finding the middle.
  • Don't send what isn't needed: a course goes to the game only if it differs from the current one by 5° or more.
  • New boats have no data. A freshly created boat reports no position or wind until it's started once. The old script, and my first rewrite, would have crashed; the service now sends start and shows "waiting for first report".
  • Celestial races hide the position. The service then shows what it can and doesn't steer.
  • A manual course switches the autopilot off, or the next poll would undo it. Stopping the boat does too, or the autopilot would restart it.

The simple autopilot

With no route, the autopilot does what a sailor does. If the target is outside the no-go zone (closer than 45° to the wind, configurable), it steers straight at it. If not, it sails close-hauled on one tack — 45° off the wind — and stays on that tack until the target is clearly on the other side, which stops it zig-zagging every minute when the target is nearly dead upwind.

Every course it's about to send is first checked against land for the next two minutes of sailing (at least a nautical mile). If land is ahead, it tries headings 5°, 10°, 15°… either side until it finds one that's clear and still outside the no-go zone. That check uses the game's own land data, which comes next.


Weather routing: three ingredients from the game itself

The best course isn't straight at the finish. Wind changes over hours and across the race area, boats sail faster at some angles than others, and land is in the way. Ocean racers solve this with weather routing. The nice thing about a simulator is that you can use exactly the inputs the simulator uses.

1. Land. The game decides what's land with libproteus-geodata: one gzipped bit field per square degree of the earth, at 1 arcsecond (about 30 m), 1 for land. A missing file means the whole square degree is water. The planner downloads tiles as it needs them and caches them in a Docker volume. Routes keep 250 m off land (configurable). As a check, I printed the tiles around Cape Town as ASCII art: the Cape Peninsula and False Bay came out exactly as on a map.

2. Wind. The game sails on GFS, and Open-Meteo serves the GFS forecast for free. The planner fetches hourly wind speed, direction and gusts for up to 300 grid points over the race area, for as many days as the route might need, and interpolates in space and time. Wind is stored as east/north components rather than directions, so blending 350° and 10° gives 0°, not 180° — there's a test for exactly that.

3. Boat speed. The game's speed tables live in its C source. A small generated module carries them across: for each boat type, a factor for every 10° of wind angle at seven wind speeds (1–24 m/s), and the same interpolation the C code uses. A test checks the Python against the C formula.

The Hanse 385's speed at every angle to the wind, drawn from the game's table. The dots mark the best angles for beating upwind and running downwind, which the planner tacks and gybes at
The Hanse 385's speed at every angle to the wind, drawn from the game's table. The dots mark the best angles for beating upwind and running downwind, which the planner tacks and gybes atChart generated from boatspeed.py (data from sailnavsim-core, GPL-3.0)

From the speed table the planner also works out each boat's best upwind and downwind angles at each wind speed — the angle that gives the most speed towards the wind, which is rarely the closest angle you can point. Any direction inside those angles is sailed by tacking (or gybing) at the best angle, at the speed that makes good along it.

Isochrones failed; A* worked

Real routers use isochrones: from the start, fan out in every direction for an hour, keep the outermost points, repeat. It's elegant, and my first version did that. It failed the first real test: a route from False Bay, round Cape Point and back up into Table Bay. Isochrones keep only the points that got furthest, and a route that has to go away from the goal to round a headland gets pruned.

The replacement is a time-dependent A\* search — the algorithm in a car's satnav — on a latitude/longitude grid:

  • Each cell can move to 16 neighbours (the 8 compass points plus 8 knight's moves), so courses aren't limited to 45° steps.
  • The cost of a move is time: its length divided by the speed made good at the time the boat would get there, using the wind forecast for that hour.
  • Every move is checked against the land data, cell centres must be safely off land, and the search's estimate assumes the boat's top speed, which keeps it honest.
  • The grid size adapts to the race area (about 40,000 cells), and the search gives up after 16 days of sailing.

The grid track is then straightened into a handful of waypoints: runs that land allows and that stay within 25° of a straight line are merged, so the bends that remain are the ones the wind or the coast asked for. The autopilot sails from waypoint to waypoint, still doing its own tacking.

Cape Point to Table Bay: the route goes round the peninsula, 250 m off the rocks. Here's the planner run on the game's real land tiles, with a steady 16-knot south-easterly and a Hanse 385, drawn as text (# land, S start in False Bay, F the Table Bay finish, o the route):

laptop: planner.route() on the real Cape Peninsula tiles
...............##........#######################################
..........................######################################
..........................######################################
..................oF......######################################
................oo........######################################
...............oo###############################################
..............oo################################################
............ooo.################################################
...........oo.##################################################
..........oo.###################################################
.........oo#####################################################
.........o.##..#################################################
.........o.....#############.###################################
.........o....##########.###.#.........................#########
.........o....##########.................................#######
.........o..##########.....................................#####
.........oo.##########.......................................###
..........oo..#######....................................###.###
...........oo...#######..................................#######
............oo..########..................................######
.............ooo#########.............S.....................####
...............oo#######............ooo.....................####
................oo#######.........ooo....................#######
.................ooo####........ooo.....................########
...................ooo##.....oooo........................#######
.....................ooooooooo..........................########
.........................................................###..##
................................................................
................................................................
................................................................
route: 9 waypoints, 20584 s sailing = 5.7 h, searched in 1.97 s

Most of those two seconds is reading the land tile the first time; the search itself is the quick part.

The same route drawn properly: nine waypoints round Cape Point and up the Atlantic side, 250 m off the coast
The same route drawn properly: nine waypoints round Cape Point and up the Atlantic side, 250 m off the coastChart generated from the planner's output and the game's land tiles (libproteus-geodata)

The planner replans when the target changes, every 3 hours (new forecasts), when the boat ends up more than 3 nm off the route, and on request. Planning runs in a background thread, so the once-a-minute steering never waits for it.

Not modelled: ocean currents, waves and damage (which the game does simulate), and the game's newer "advanced" boat types, which have no table to copy.

Alternatives, in pirate

The fastest route isn't always the one you want. You might want to stay clear of a gusty headland, or bet on a forecast shift. So the planner also offers real alternatives: it forces a route through a point off each side of the straight line, 20% of the distance out — and if that point is on land, it keeps stepping out (up to two degrees) until it finds open water, which is how it finds the way round the far end of an island. An alternative is dropped if it ends up on the same side as the fastest route, or takes more than 1.6 times as long.

Then the fun part. The PC already runs Gemma 3 12B locally for my news digest. After each plan, the planner sends it the facts — distance, hours, which side, legs, wind range, worst gust — and asks for JSON: for every option, a button label, a summary and a one-line version, all in thick pirate, "keeping every number exactly as given". It comes back as things like "Hug the coast", "Stand out to sea" and "Beat north, ye dogs".

Models overrun limits, so labels are cut at a word boundary (never mid-word) to 22 characters, the one-liners to 60 with "...", and if the JSON is unusable or the model is down, plain labels ("Fastest course", "Bear north") take over and the route is sailed anyway.

Choosing an option is remembered for later replans to the same mark; a manual replan or a new mark goes back to the fastest.


The helm on a Kindle

The status and controls live on the sailing page of my e-ink Kindle dashboard (a separate post covers the dashboard). Everything fits on one 600×800 page:

  • Top line: distance to the next mark, progress through the race's waypoints, and the estimated landfall from the route.
  • The chart: coastlines from Natural Earth, wind arrows from a 6×5 grid of current GFS wind, the planned route, the finish box, and the boat — white with a black outline, pointing along its course — with a box of speed, heading and wind.
  • The route line: the pirate one-liner. Tap it, then tap again within 6 seconds, to replan.
  • Route choices: one button per option, with how much slower it is (+0.8 h).
  • The helm: < Port 10°, Autopilot ON / Steering by hand, Starb'd 10° >, and Heave to / Make sail! (with a "Sure, matey?" confirmation).
laptop: what the Kindle reads from the autopilot (selected fields)
$ curl -s http://<pc>:8793/status | jq '{dest_name, dest_nm, course, wind_dir, wind_kts, ap_mode, action, route}'
"dest_name": "finish",
"dest_nm": 28.5,
"course": 22,
"wind_dir": 337,
"wind_kts": 6.3,
"ap_mode": "route leg 1/1, starboard tack",
"action": "course 157 -> 22 (route leg 1/1, starboard tack)",
"route": { "hours": 3.2, "sailed_nm": 16.0,
  "summary_short": "Steer 20, sail 16 nm, finish in 3.2 hours, arr!",
  "options": [ { "id": "fastest", "label": "Swift Passage, Aye", "slower_h": 0.0 },
               { "id": "west", "label": "Westward Ho, Ye!", "slower_h": 1.1 } ] }
The same live state, rendered by the dashboard server
The same live state, rendered by the dashboard server

The Kindle long-polls the dashboard server, so a change shows within a second or two — after one bug, where turning the autopilot on didn't update /status until the next poll, a minute later. I tapped "auto" five times and kept toggling it back. It now updates at once, with a test.

Steering by voice

A microphone on the PC runs Vosk, an offline speech recogniser with a fixed grammar where every command starts with "kindle". The sailing ones: kindle steer port ten, kindle steer starboard five, kindle autopilot on, kindle replan. Speech gets misheard, so the service has two safety rails:

  • One nudge turns at most 90°, whatever number arrives.
  • A manual course that runs onto land within two polls is still obeyed (you're the skipper), but the reply carries a warning and the Kindle shows LAND HO dead ahead! above the confirmation.

Voice never starts or stops the boat.


Testing a game you can't pause

You can't rewind a race, and mistakes cost hours. So the code was tested in three layers:

  1. A fake game. The 20 autopilot tests run the real service against a stand-in API: starting a new boat, celestial mode, the ±180° line, tacking, the land-avoidance turn, nudges, replans, choosing a route, keeping going when the model is down.
  2. A fake world. The 20 planner tests use a made-up land tile — a wall of land — and check that routes go round it (and that alternatives go round each end), that upwind routes tack, that no wind means no route, that wind blends through north, and that the speed tables match the C formula. A fake language model checks the prompt, the labels and the bad-JSON fallback.
laptop: both suites, nothing sent to the game
$ python test_sailnav.py
....................
----------------------------------------------------------------------
Ran 20 tests in 0.548s
OK
$ python test_planner.py -v 2>&1 | tail -6
test_goes_round_the_wall (__main__.Routing.test_goes_round_the_wall) ... ok
test_no_wind_no_route (__main__.Routing.test_no_wind_no_route) ... ok
test_target_on_land_side_still_reached (__main__.Routing.test_target_on_land_side_still_reached) ... ok
test_upwind_direct_when_open (__main__.Routing.test_upwind_direct_when_open) ... ok
Ran 20 tests in 9.763s
OK
  1. The real thing. A test boat in a live race near Cape Point. First the plain autopilot: it started the boat, set 237° straight at the finish 48.5 nm away, and held it without resending. Then the planner: 4.9 hours to the finish on a reach with one waypoint — correct, since the way was open water — and the steering switched to following the route.

What I learned

  • Use the simulator's own inputs. Same land data, same forecast model, same speed tables: the planner's world is the game's world, not an approximation of it.
  • Isochrones can't double back. For routing round capes and into bays, a time-dependent A* on a grid is simpler and more robust.
  • Never compare angles with subtraction. Every bearing bug I've ever written was this one.
  • Fail loudly. The old script's worst habit was carrying on with empty numbers. The new one keeps serving the last good state, with the error beside it.
  • A language model makes a good presenter and a bad navigator. It never touches the route; it only names and explains options that the planner has already worked out, and the boat sails fine without it.
  • Put safety rails on the server, not the client: caps on nudges and land warnings apply to buttons, voice and anything added later.

Still open

  • Ocean currents, which the game models and the planner doesn't.
  • The advanced boat types.
  • Open-Meteo's free tier allows about 10,000 point-requests a day, and a plan can use 300; fine every 3 hours, but lots of manual replans on a huge race area could hit it.
  • A new race means a new boat key and a container restart.

By the numbers

20202026
LanguagePerl, ~350 linesPython, ~850 lines + 40 tests
Talks to the game byscraping HTMLJSON API
WhereAWS, one container per boathome PC, one container
Landnonethe game's 1-arcsecond data, 250 m margin
Windthe wind at the boat, nowGFS forecast over the race area, by the hour
Routingstraight at the finish, or 40° offtime-dependent A*, alternatives either side
Controlsenvironment variablesKindle buttons, voice, HTTP
Explains itselfsay "OPTIMAL (c)"in pirate

Published 2026-10-31 · 2,988 words · about 13 min read