GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / cosmic / tools/explore/theme

Pilot Nav and 1 more file

A JavaScript module in the theme folder of Cosmic that maps the Renewable Energy Planning Database (REPD) register. It makes route (`makeRoute`), turns word (`turnWord`) and turns cues (`turnCues`).

559 lines of JavaScript and CSS from cosmic, in 2 files. Topic: Kuiper, cosmos and drawing engines. Section 1151 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Pilot Nav geodesy · cosmic / tools/explore/theme/pilot-nav.js lines 1–504
  2. Pilot Subfind render · cosmic / tools/explore/theme/pilot-subfind.css lines 1–55

Pilot Nav

A JavaScript module in the theme folder of Cosmic that maps the Renewable Energy Planning Database (REPD) register. It makes route (`makeRoute`), turns word (`turnWord`) and turns cues (`turnCues`).

geodesycosmic / tools/explore/theme/pilot-nav.js · lines 1–504 of 504 · Entry point · pattern buildDestination (shared by 2 files)

What it does
It maps the REPD register. Defines 51 functions or classes, including distanceKm, initialBearingDeg, destinationPoint, localScaleKm, distanceToSegmentKm. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage field_execution (path word 'nav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work. Domain terms in the code: the REPD register.
Downstream impact
Used directly by 1 file: Pilot (cosmic, https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html).
What it achieves
Pilot SatNav (W09 / WAYMARK-09): route to a chosen asset or point, follow-route flight, turn cues and ETA. Its code works with 5 Hz. It responds to click events.
Why it matters
Loaded by the Pilot page at https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html.
Application
cosmic · tools/explore/theme · JavaScript module
VEDIC
MEASURE (GG2050-VEDIC-000001): GridAtlas / Geodesy · Mathematics / Spherical geometry. coordinate_pair, coordinate_pair → distance_km
VEDIC
BEARING (GG2050-VEDIC-000005): GridAtlas / Geodesy · Mathematics / Trigonometry. coordinate_pair, coordinate_pair → bearing_deg
VEDIC
DESTINATION (GG2050-VEDIC-000004): GridAtlas / Geodesy · Mathematics / Spherical geometry. coordinate_pair, distance_km, bearing_deg → coordinate_pair
Uses
none found
Used by
loaded by Pilot (script src)
Produces
distanceKm, initialBearingDeg, destinationPoint, localScaleKm, distanceToSegmentKm, metres, okLL, densify, makeRoute, follow, turnWord, turnCues
Defines here
distanceKm, initialBearingDeg, destinationPoint, localScaleKm, distanceToSegmentKm, metres, okLL, densify, makeRoute, follow, turnWord, turnCues, compass, nextCue, fmtDist, pad2, eta, flightSecs, speedFor, coordinate, parseDestination, buildDestination, camStop, asStop, build, to, addVia, clear, note, start
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/theme/pilot-nav.js:1-504 · blob f23a8131bbffb7aba11dc3fbed69cdf8195a25d1 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unknown
/* Pilot SatNav (W09 / WAYMARK-09): route to a chosen asset or point, follow-route flight, turn cues and ETA.
   Plain script, no libraries, no CDN. Builds only on the PILOT module contract v1 (window.PILOT).

   What the route is: an AIR route of straight great-circle legs from where the drone is, through any via points, to the
   destination. It is NOT a route by road or footpath. The estate's SatNav road routing is switched off until a controlled
   service exists (Ventusltd/gridatlas tools/satnav/regional/regional-config.mjs: endpoint null), so nothing here pretends
   to know roads, access or consent. Access to every destination is unverified, as SatNav itself says.

   Reused from the owner's own SatNav code (Apache-2.0, Ventus Ltd):
   - distanceKm, initialBearingDeg, destinationPoint, localScaleKm, distanceToSegmentKm: Ventusltd/satnav@ea69138
     preview/9698781539e549deaa6ecaa4a2b34610c1f9fd29/vendor/grid-distance-maths/src/geodesy.mjs (R_ATLAS = 6378.137 km).
   - parseDestination / buildDestination URL contract: same preview, nav/place.mjs (keys latitude, longitude, name,
     mode, source, id; GeoJSON order [lon, lat] inside).
   - createRouteFollower (progress, remaining, signed cross-track, off-route on segments of 1 km or less):
     Ventusltd/gridatlas@f944f8dcbc09cd09c0895f0126682ec241cd576f tools/satnav/line/route-follower.mjs (Apache-2.0), adapted to the drone position instead of a GPS fix. */
(function () {
  'use strict';
  if (typeof window !== 'undefined' && !window.PILOT) return;   // CONTRACT §1 (node tests load the pure core without a window)

  /* ================= pure core (no DOM; node-testable) ================= */
  var R_ATLAS = 6378.137, DEG = Math.PI / 180, WGS_A = 6378.137, WGS_F = 1 / 298.257223563, WGS_E2 = WGS_F * (2 - WGS_F);

  function distanceKm(lon1, lat1, lon2, lat2, radius) {
    radius = radius || R_ATLAS;
    var dLat = (lat2 - lat1) * DEG, dLon = (lon2 - lon1) * DEG;
    var x = Math.pow(Math.sin(dLat / 2), 2) + Math.cos(lat1 * DEG) * Math.cos(lat2 * DEG) * Math.pow(Math.sin(dLon / 2), 2);
    return radius * 2 * Math.atan2(Math.sqrt(x), Math.sqrt(1 - x));
  }
  function initialBearingDeg(lon1, lat1, lon2, lat2) {
    var p1 = lat1 * DEG, p2 = lat2 * DEG, dl = (lon2 - lon1) * DEG;
    var y = Math.sin(dl) * Math.cos(p2), x = Math.cos(p1) * Math.sin(p2) - Math.sin(p1) * Math.cos(p2) * Math.cos(dl);
    return (Math.atan2(y, x) / DEG + 360) % 360;
  }
  function destinationPoint(lon, lat, km, bearingDeg, radius) {
    radius = radius || R_ATLAS;
    var ad = km / radius, brg = bearingDeg * DEG, p1 = lat * DEG;
    var p2 = Math.asin(Math.sin(p1) * Math.cos(ad) + Math.cos(p1) * Math.sin(ad) * Math.cos(brg));
    var l2 = lon * DEG + Math.atan2(Math.sin(brg) * Math.sin(ad) * Math.cos(p1), Math.cos(ad) - Math.sin(p1) * Math.sin(p2));
    return [l2 / DEG, p2 / DEG];
  }
  function localScaleKm(latDeg) {
    var s = Math.sin(latDeg * DEG), t = 1 - WGS_E2 * s * s;
    var meridional = (WGS_A * (1 - WGS_E2)) / Math.pow(t, 1.5), primeVertical = WGS_A / Math.sqrt(t);
    return { kx: primeVertical * Math.cos(latDeg * DEG) * DEG, ky: meridional * DEG };
  }
  function distanceToSegmentKm(lon, lat, aLon, aLat, bLon, bLat) {
    var k = localScaleKm(lat), ax = (aLon - lon) * k.kx, ay = (aLat - lat) * k.ky, bx = (bLon - lon) * k.kx, by = (bLat - lat) * k.ky;
    var dx = bx - ax, dy = by - ay, len2 = dx * dx + dy * dy, t = 0;
    if (len2 > 0) { t = -(ax * dx + ay * dy) / len2; t = t < 0 ? 0 : t > 1 ? 1 : t; }
    var foot = [aLon + (bLon - aLon) * t, aLat + (bLat - aLat) * t];
    return { km: distanceKm(lon, lat, foot[0], foot[1]), foot: foot, t: t };
  }
  function metres(a, b) { return distanceKm(a[0], a[1], b[0], b[1]) * 1000; }   // a, b = [lon, lat]

  var okLL = function (lat, lon) { return isFinite(lat) && isFinite(lon) && Math.abs(lat) <= 90 && Math.abs(lon) <= 180 && lat !== null && lon !== null; };

  // Great-circle legs cut into pieces of at most maxM metres (route-follower refuses longer segments).
  function densify(pts, maxM) {
    maxM = maxM || 1000;
    var out = [pts[0].slice()];
    for (var i = 1; i < pts.length; i++) {
      var a = pts[i - 1], b = pts[i], d = metres(a, b), n = Math.max(1, Math.ceil(d / (maxM * 0.999))), brg = initialBearingDeg(a[0], a[1], b[0], b[1]);
      for (var k = 1; k < n; k++) out.push(destinationPoint(a[0], a[1], d / 1000 * k / n, brg));
      out.push(b.slice());
    }
    return out;
  }

  // stops: [{lat, lon, name, source, id}], first = origin, last = destination.
  function makeRoute(stops) {
    if (!Array.isArray(stops) || stops.length < 2) throw new Error('ROUTE_NEEDS_TWO_STOPS');
    stops.forEach(function (s) { if (!s || !okLL(s.lat, s.lon)) throw new Error('INVALID_STOP'); });
    var legs = [], coords = [], total = 0;
    for (var i = 1; i < stops.length; i++) {
      var a = [stops[i - 1].lon, stops[i - 1].lat], b = [stops[i].lon, stops[i].lat], m = metres(a, b);
      var piece = densify([a, b]);
      legs.push({ from: i - 1, to: i, m: m, startM: total, bearing: initialBearingDeg(a[0], a[1], b[0], b[1]), coordStart: coords.length ? coords.length - 1 : 0 });
      coords = coords.length ? coords.concat(piece.slice(1)) : piece;
      total += m;
    }
    return { stops: stops.map(function (s) { return { lat: +s.lat, lon: +s.lon, name: String(s.name || ''), source: s.source || null, id: s.id == null ? null : String(s.id) }; }),
             legs: legs, geometry: { type: 'LineString', coordinates: coords }, totalM: total, kind: 'air_straight_legs', accessStatus: 'unverified' };
  }

  // From route-follower.mjs: nearest segment, progress along the route, remaining, signed cross-track (+ right, - left).
  function follow(route, tolM) {
    tolM = tolM == null ? 50 : tolM;
    var c = route.geometry.coordinates, segs = [], total = 0;
    for (var i = 0; i < c.length - 1; i++) { var len = metres(c[i], c[i + 1]); if (len > 0) { segs.push({ a: c[i], b: c[i + 1], length: len, start: total, index: i }); total += len; } }
    return function locate(lat, lon) {
      if (!okLL(lat, lon) || !segs.length) return { status: 'invalid' };
      var best = null, hits = [];
      for (var j = 0; j < segs.length; j++) {
        var s = segs[j], h = distanceToSegmentKm(lon, lat, s.a[0], s.a[1], s.b[0], s.b[1]), d = h.km * 1000;
        hits.push({ s: s, h: h, d: d, p: s.start + h.t * s.length });
        if (!best || d < best.d) best = { s: s, h: h, d: d };
      }
      // route-follower.mjs AMBIGUOUS_ROUTE_POSITION guard, with the drone's exact position (accuracy 0 m): if another
      // part of the route is as near (within 5 m) but more than 30 m further along, the position on the route is
      // ambiguous (the route doubles back) and no progress is claimed.
      var bp = best.s.start + best.h.t * best.s.length;
      if (hits.some(function (x) { return x.d <= best.d + 5 && Math.abs(x.p - bp) > 30; })) return { status: 'uncertain', reason: 'AMBIGUOUS_ROUTE_POSITION' };
      var xt = null;
      if (best.h.t > 0 && best.h.t < 1) {
        var dir = initialBearingDeg(best.s.a[0], best.s.a[1], best.s.b[0], best.s.b[1]), off = initialBearingDeg(best.h.foot[0], best.h.foot[1], lon, lat);
        xt = best.d < 1e-6 ? 0 : Math.sign(Math.sin((off - dir) * DEG)) * best.d;
      }
      var progress = best.s.start + best.h.t * best.s.length;
      return { status: 'ok', segmentIndex: best.s.index, nearest: best.h.foot, offsetM: best.d, signedCrossTrackM: xt,
               progressM: progress, remainingM: Math.max(0, total - progress), totalM: total, offRoute: best.d > tolM, trackingOnly: true };
    };
  }

  function turnWord(delta) {   // delta: signed bearing change, degrees in (-180, 180]
    var a = Math.abs(delta), side = delta > 0 ? 'right' : 'left';
    if (a < 20) return { kind: 'continue', text: 'Continue straight', glyph: '↑' };
    if (a < 45) return { kind: 'bear-' + side, text: 'Bear ' + side, glyph: side === 'right' ? '↗' : '↖' };
    if (a <= 135) return { kind: 'turn-' + side, text: 'Turn ' + side, glyph: side === 'right' ? '↱' : '↰' };
    return { kind: 'sharp-' + side, text: 'Sharp ' + side, glyph: side === 'right' ? '↷' : '↶' };
  }
  function turnCues(route) {
    var cues = [], L = route.legs, S = route.stops;
    for (var i = 1; i < L.length; i++) {
      var d = ((L[i].bearing - L[i - 1].bearing) % 360 + 540) % 360 - 180, w = turnWord(d), at = S[L[i].from];
      cues.push({ atM: L[i].startM, kind: w.kind, glyph: w.glyph, delta: d, stop: L[i].from,
                  text: w.text + ' at ' + (at.name || 'via point') + ', then head ' + compass(L[i].bearing) });
    }
    var end = S[S.length - 1];
    cues.push({ atM: route.totalM, kind: 'arrive', glyph: '◎', delta: 0, stop: S.length - 1, text: 'Arrive at ' + (end.name || 'destination') });
    return cues;
  }
  var PTS = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'];
  function compass(b) { return PTS[Math.round(((b % 360) + 360) % 360 / 45) % 8]; }
  function nextCue(cues, progressM) {
    for (var i = 0; i < cues.length; i++) if (cues[i].atM > progressM + 1) return { cue: cues[i], inM: cues[i].atM - progressM, index: i };
    var last = cues[cues.length - 1]; return { cue: last, inM: Math.max(0, last.atM - progressM), index: cues.length - 1 };
  }
  function fmtDist(m) {
    if (!isFinite(m)) return '—';
    if (m < 1000) return Math.round(m) + ' m';
    if (m < 10000) return (m / 1000).toFixed(1) + ' km';
    return Math.round(m / 1000) + ' km';
  }
  function pad2(n) { return (n < 10 ? '0' : '') + n; }
  // ETA from remaining metres and a speed (m/s), or from a seconds estimate. Returns {min, clock, text}.
  function eta(remainingM, speedMs, nowMs, secs) {
    var s = secs != null ? secs : (speedMs >= 1 ? remainingM / speedMs : null);
    if (s == null || !isFinite(s)) return { min: null, clock: null, text: '—' };
    var t = new Date((nowMs || Date.now()) + s * 1000), min = Math.max(0, Math.round(s / 60));
    var lab = s < 60 ? Math.max(1, Math.round(s)) + ' s' : min < 90 ? min + ' min' : Math.floor(min / 60) + ' h ' + pad2(min % 60);
    return { min: min, secs: s, clock: pad2(t.getHours()) + ':' + pad2(t.getMinutes()), text: lab + ' (' + pad2(t.getHours()) + ':' + pad2(t.getMinutes()) + ')' };
  }
  // Seconds core flyTo takes for a leg (CONTRACT §4: > 5 km -> 3 s + 2.2 x log2(km); otherwise the 3.2 s arrival).
  function flightSecs(m) { var km = m / 1000; return km > 5 ? 3 + 2.2 * Math.log(km) / Math.LN2 : 3.2; }
  // Continuous-follow speed (used only if core offers PILOT.steer): fast on long open stretches, slow near turns/arrival.
  function speedFor(remainingM, toTurnM) {
    var near = Math.min(remainingM, toTurnM == null ? Infinity : toTurnM + 1500);
    var v = Math.max(20, Math.min(2500, near / 12));
    if (remainingM < 60) v = 0; else if (remainingM < 1500) v = Math.min(v, Math.max(8, remainingM / 20));
    return v;
  }

  // ---- satnav nav/place.mjs URL contract (ported; same keys and errors)
  var MODES = { compass: 1, road_to_field: 1, foot_survey: 1, cable_trench: 1 };
  function coordinate(value, max) {
    if (typeof value !== 'string' || !value.trim() || !/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(value.trim())) throw new Error('invalid coordinate');
    var n = Number(value); if (!isFinite(n) || Math.abs(n) > max) throw new Error('coordinate out of range'); return n;
  }
  function parseDestination(search) {
    var p = new URLSearchParams(search);
    ['latitude', 'longitude', 'to', 'name', 'mode', 'source', 'id'].forEach(function (k) { if (p.getAll(k).length > 1) throw new Error('duplicate ' + k); });
    var mode = p.get('mode') || 'compass'; if (!MODES[mode]) throw new Error('invalid mode');
    var lat = p.get('latitude'), lon = p.get('longitude'), legacy = p.get('to'), pair;
    if (legacy !== null && (lat !== null || lon !== null)) throw new Error('conflicting coordinates');
    if (legacy !== null) { var a = legacy.split(','); if (a.length !== 2) throw new Error('invalid legacy coordinates'); pair = [coordinate(a[1], 180), coordinate(a[0], 90)]; }
    else if (lat !== null || lon !== null) pair = [coordinate(lon, 180), coordinate(lat, 90)];
    else return null;
    var source = p.get('source'), id = p.get('id');
    if ((source === null) !== (id === null) || source === '' || id === '') throw new Error('incomplete asset identity');
    return { coordinates: pair, mode: mode, name: p.get('name') || '', asset: source === null ? null : { source: source, id: id }, accessStatus: 'unverified' };
  }
  function buildDestination(d) {
    var c = d && d.coordinates;
    if (!Array.isArray(c) || c.length !== 2 || !c.every(isFinite)) throw new Error('invalid coordinates');
    var mode = d.mode || 'compass';
    if (Math.abs(c[0]) > 180 || Math.abs(c[1]) > 90 || !MODES[mode]) throw new Error('invalid destination');
    var p = new URLSearchParams({ latitude: String(c[1]), longitude: String(c[0]), mode: mode, name: d.name || '' });
    if (d.asset) { if (typeof d.asset.source !== 'string' || typeof d.asset.id !== 'string' || !d.asset.source || !d.asset.id) throw new Error('invalid asset'); p.set('source', d.asset.source); p.set('id', d.asset.id); }
    return '?' + p.toString();
  }

  var CORE = { R_ATLAS: R_ATLAS, distanceKm: distanceKm, initialBearingDeg: initialBearingDeg, destinationPoint: destinationPoint,
    distanceToSegmentKm: distanceToSegmentKm, densify: densify, makeRoute: makeRoute, follow: follow, turnCues: turnCues,
    nextCue: nextCue, fmtDist: fmtDist, eta: eta, flightSecs: flightSecs, speedFor: speedFor, compass: compass,
    parseDestination: parseDestination, buildDestination: buildDestination };
  if (typeof module === 'object' && module.exports) { module.exports = CORE; return; }

  /* ================= browser wiring (CONTRACT v1) ================= */
  var PILOT = window.PILOT;
  if (!PILOT) return;
  if (PILOT.module) PILOT.module('nav', { version: '1', owner: 'W09' });
  var D = document, esc = PILOT.esc || function (s) { return String(s).replace(/[&<>"']/g, function (c) { return '&#' + c.charCodeAt(0) + ';'; }); };
  var CREDIT = 'SatNav: straight air legs (not a route by road; access unverified), geodesy from Ventus grid-distance-maths, Apache-2.0';

  var st = { route: null, locate: null, cues: null, fix: null, following: false, paused: false, arrived: false, leg: 0,
             legT0: 0, sel: null, tap: null, vias: [], dest: null, lastCue: -1, off: false, steering: false, tick: 0 };

  function camStop() {
    var c = PILOT.camLL ? PILOT.camLL() : null;
    return c && okLL(c.lat, c.lon) ? { lat: c.lat, lon: c.lon, name: 'Start (drone position)', source: 'pilot' } : null;
  }
  function asStop(a) {
    if (!a) return null;
    var lat = +a.lat, lon = +a.lon;
    if (!okLL(lat, lon)) return null;
    return { lat: lat, lon: lon, name: String(a.name || a.title || a.label || '').slice(0, 80) || (lat.toFixed(5) + ', ' + lon.toFixed(5)),
             source: a.source ? String(a.source) : null, id: a.id != null ? String(a.id) : (a.ref != null ? String(a.ref) : null) };
  }

  function build(origin) {
    var o = origin || camStop();
    if (!o || !st.dest) return null;
    stopFollow(true);
    var stops = [o].concat(st.vias, [st.dest]);
    st.route = makeRoute(stops); st.locate = follow(st.route); st.cues = turnCues(st.route);
    st.arrived = false; st.leg = 0; st.lastCue = -1; st.off = false; st.fix = st.locate(o.lat, o.lon);
    if (PILOT.credit) PILOT.credit('nav', CREDIT);
    if (PILOT.hash) try { PILOT.hash('nav', st.dest.lat.toFixed(5) + ',' + st.dest.lon.toFixed(5)); } catch (e) {}
    if (PILOT.emit) PILOT.emit('nav:route-built', { totalM: st.route.totalM, stops: st.route.stops.length, dest: st.dest });
    renderPanel(); renderHud(true);
    return st.route;
  }
  function to(a, opts) {
    var s = asStop(a); if (!s) { note('SatNav: that destination has no valid coordinates'); return null; }
    st.dest = s; if (!(opts && opts.keepVias)) st.vias = [];
    var r = build();
    if (!r) { renderPanel(); return null; }
    if (PILOT.openPanel && !(opts && opts.quiet)) PILOT.openPanel('nav');
    note('Route to ' + s.name + ': ' + fmtDist(r.totalM) + ' (air legs)');
    if (opts && opts.start) start();
    return r;
  }
  function addVia(a) {
    var s = asStop(a); if (!s) return null;
    if (st.vias.length >= 8) { note('SatNav: up to 8 via points'); return null; }
    st.vias.push(s);
    return st.dest ? build() : (renderPanel(), null);
  }
  function clear() {
    stopFollow(true);
    st.route = st.locate = st.cues = st.fix = st.dest = null; st.vias = []; st.arrived = false;
    if (PILOT.credit) PILOT.credit('nav', null);
    if (PILOT.hash) try { PILOT.hash('nav', null); } catch (e) {}
    renderPanel(); renderHud(true);
  }
  function note(t) { if (PILOT.note) PILOT.note(t, 3500); }

  // ---- follow-route flight
  // Preferred: core PILOT.steer (continuous pure-pursuit). Fallback (contract v1): chain PILOT.flyTo along each leg.
  function start() {
    if (!st.route) return;
    if (st.arrived || (st.fix && st.fix.remainingM < 60)) { build(); }
    // Re-route from where the drone is now, so the first leg starts under the camera.
    var here = camStop(); if (here && st.fix && st.fix.offsetM > 200) build(here);
    st.following = true; st.paused = false; st.arrived = false;
    var o = camStop(), p = o ? st.locate(o.lat, o.lon) : null;
    st.leg = legAt(p ? p.progressM : 0);
    if (PILOT.steer && !PILOT.reduced) { st.steering = true; PILOT.steer(steerFn); }
    else flyLeg();
    renderPanel(); renderHud(true);
  }
  function legAt(m) { var L = st.route.legs; for (var i = 0; i < L.length; i++) if (m < L[i].startM + L[i].m - 60) return i; return L.length - 1; }
  function flyLeg() {
    if (!st.following || !st.route) return;
    var L = st.route.legs, S = st.route.stops, i = st.leg, leg = L[i], tgt = S[leg.to], last = i === L.length - 1;
    var opts = last ? { label: tgt.name, source: 'nav', id: tgt.id || undefined }
                    : { dist: 0, alt: 250, pitch: -0.35, hdg: L[i + 1].bearing, label: tgt.name, source: 'nav', fast: 'auto' };
    st.legT0 = Date.now();
    var gen = ++st.tick, pr;
    try { pr = PILOT.flyTo(tgt.lat, tgt.lon, opts); } catch (e) { pr = null; }
    if (!pr || !pr.then) { stopFollow(); return; }
    pr.then(function () {
      if (gen !== st.tick || !st.following) return;
      if (last) { arrive(); return; }
      st.leg = i + 1;
      if (PILOT.reduced) { st.paused = true; renderPanel(); renderHud(true); return; }   // reduced motion: leg by leg on request
      flyLeg();
    }, function () {
      if (gen !== st.tick || !st.following) return;
      st.paused = true; renderPanel(); renderHud(true);                                // user took the controls
    });
  }
  function steerFn() {   // only used when core provides PILOT.steer
    var c = PILOT.camLL(), p = st.locate(c.lat, c.lon);
    if (p.status !== 'ok') return null;
    if (p.remainingM < 60) { stopFollow(); arrive(); return null; }
    var n = nextCue(st.cues, p.progressM), v = speedFor(p.remainingM, n.cue.kind === 'arrive' ? null : n.inM);
    var look = Math.max(150, Math.min(20000, Math.max(c.speed, v) * 4)), aim = pointAt(p.progressM + look);
    return { hdg: initialBearingDeg(c.lon, c.lat, aim[0], aim[1]), speed: v, agl: Math.max(120, Math.min(3000, v * 2.5)) };
  }
  function pointAt(m) {
    var r = st.route, L = r.legs; m = Math.max(0, Math.min(r.totalM, m));
    for (var i = 0; i < L.length; i++) if (m <= L[i].startM + L[i].m || i === L.length - 1) {
      var a = r.stops[L[i].from]; return destinationPoint(a.lon, a.lat, (m - L[i].startM) / 1000, L[i].bearing);
    }
  }
  function stopFollow(silent) {
    st.tick++;
    var was = st.following;
    st.following = false; st.paused = false;
    if (st.steering && PILOT.steer) { st.steering = false; PILOT.steer(null); }
    if (was && !silent && PILOT.stop) PILOT.stop();
    if (!silent) { renderPanel(); renderHud(true); }
  }
  function nextLeg() {   // reduced motion / paused: fly (or jump) the next leg only
    if (!st.route) return;
    st.following = true; st.paused = false;
    if (st.arrived) return;
    flyLeg(); renderPanel();
  }
  function arrive() {
    st.following = false; st.paused = false; st.arrived = true;
    var d = st.route.stops[st.route.stops.length - 1];
    if (PILOT.emit) PILOT.emit('nav:arrive', { lat: d.lat, lon: d.lon, name: d.name, source: d.source, id: d.id });
    note('Arrived: ' + d.name);
    renderPanel(); renderHud(true);
  }
  function rejoin() { if (st.dest) { var f = st.following; build(); if (f) start(); } }

  // ---- per-frame tracking (cheap: 5 Hz)
  var acc = 0;
  function frame(dt) {
    if (!st.route) return;
    acc += dt || 0; if (acc < 0.2) return; acc = 0;
    var c = PILOT.camLL(); if (!c) return;
    var nf = st.locate(c.lat, c.lon);
    // an ambiguous position keeps the last good fix (progress is never reset to zero by a doubled-back route)
    st.fix = nf.status === 'uncertain' && st.fix && st.fix.status === 'ok' ? Object.assign({}, st.fix, { uncertain: nf.reason }) : nf;
    var off = st.fix.status === 'ok' && st.fix.offsetM > 500 && !(st.following && !st.paused);
    if (off !== st.off) { st.off = off; renderPanel(); }
    renderHud(false);
  }

  function etaNow() {
    var f = st.fix, c = PILOT.camLL ? PILOT.camLL() : null;
    if (!f || f.status !== 'ok') return eta(0, 0);
    if (st.following && !st.paused && !st.steering) {   // chained flyTo: sum the core's leg flight times
      var L = st.route.legs, s = Math.max(0.5, flightSecs(L[st.leg].m) - (Date.now() - st.legT0) / 1000);
      for (var i = st.leg + 1; i < L.length; i++) s += flightSecs(L[i].m);
      return eta(f.remainingM, 0, Date.now(), s);
    }
    return eta(f.remainingM, c ? c.speed : 0, Date.now());
  }

  // ---- HUD (top slot, keyed)
  var hudEl = null;
  function renderHud(force) {
    if (!PILOT.hud) return;
    if (!st.route) { PILOT.hud('top:nav', null); hudEl = null; return; }
    var f = st.fix, prog = f && f.status === 'ok' ? f.progressM : 0, n = nextCue(st.cues, prog), e = etaNow();
    var cue = st.arrived ? { glyph: '◎', text: 'Arrived at ' + st.route.stops[st.route.stops.length - 1].name } : n.cue;
    var dist = st.arrived ? '' : 'in ' + fmtDist(n.inM);
    var sub = st.arrived ? 'Air route complete' : fmtDist(f ? f.remainingM : st.route.totalM) + ' to go · ETA ' + e.text + (st.off ? ' · OFF ROUTE' : '');
    sub += ' · straight air legs, not a route by road; access unverified';   // screening limit beside the result (review finding 3)
    var changed = n.index !== st.lastCue || force;
    if (!hudEl || changed) {
      st.lastCue = n.index;
      hudEl = PILOT.hud('top:nav', '<div class="p-nav-hud" role="group" aria-label="SatNav next instruction">' +
        '<b class="p-nav-glyph" aria-hidden="true">' + cue.glyph + '</b>' +
        '<span class="p-nav-cue" aria-live="polite">' + esc(cue.text) + '</span>' +
        '<em class="p-nav-in">' + esc(dist) + '</em>' +
        '<small class="p-nav-sub">' + esc(sub) + '</small></div>');
    } else if (hudEl && hudEl.querySelector) {
      var a = hudEl.querySelector('.p-nav-in'), b = hudEl.querySelector('.p-nav-sub');
      if (a) a.textContent = dist; if (b) b.textContent = sub;
    }
  }

  // ---- panel
  function btn(act, label, extra) { return '<button type="button" class="p-nav-btn" data-nav="' + act + '"' + (extra || '') + '>' + esc(label) + '</button>'; }
  function renderPanel() {
    if (!PILOT.panel) return;
    var h = '<div class="p-nav">';
    var cand = st.sel || st.tap;
    if (cand) {
      h += '<p class="p-nav-cap">' + (st.sel ? 'SELECTED' : 'TAPPED POINT') + '</p><p class="p-nav-sel">' + esc(cand.name) +
        (cand.source ? ' <span class="p-nav-dim">(' + esc(cand.source) + ')</span>' : '') + '</p><div class="p-nav-row">' +
        btn('route-sel', 'Route here') + (st.dest ? btn('via-sel', 'Add as via') : '') + '</div>';
    } else if (!st.route) {
      h += '<p class="p-nav-dim">Pick an asset (tap a substation, line, REPD site or vicinity row) or tap the ground, then choose Route here.</p>';
    }
    if (st.route) {
      var r = st.route, end = r.stops[r.stops.length - 1];
      h += '<p class="p-nav-cap">ROUTE</p><p class="p-nav-dest">' + esc(end.name) + (end.source ? ' <span class="p-nav-dim">(' + esc(end.source) + (end.id ? ' ' + esc(end.id) : '') + ')</span>' : '') +
        '</p><p>' + fmtDist(r.totalM) + ' in ' + r.legs.length + ' leg' + (r.legs.length === 1 ? '' : 's') + '</p><ol class="p-nav-legs">';
      r.legs.forEach(function (L, i) {
        h += '<li' + (st.following && i === st.leg ? ' class="p-nav-on"' : '') + '>' + esc(r.stops[L.to].name) + ' · ' + fmtDist(L.m) + ' ' + compass(L.bearing) + ' ' + Math.round(L.bearing) + '°</li>';
      });
      h += '</ol><div class="p-nav-row">';
      if (st.following && !st.paused) h += btn('stop', 'Stop');
      else if (st.paused) h += btn(PILOT.reduced ? 'next' : 'resume', PILOT.reduced ? 'Next leg' : 'Resume') + btn('stop', 'Stop');
      else h += btn('start', st.arrived ? 'Fly again' : 'Fly route');
      if (st.off) h += btn('rejoin', 'Rejoin');
      h += btn('copy', 'Copy link') + btn('clear', 'Clear') + '</div>';
      if (st.off) h += '<p class="p-nav-warn" role="status">Off route by ' + fmtDist(st.fix.offsetM) + '. Rejoin re-routes from here.</p>';
    }
    h += '<p class="p-nav-dim p-nav-scope">Air route of straight legs for the drone, not a route by road: SatNav road routing is off until a controlled service exists. Access unverified.</p></div>';
    var body = PILOT.panel('nav', h, { title: 'SatNav', icon: 'NAV' });
    if (body && !body.__navWired) { body.__navWired = true; body.addEventListener('click', onPanelClick); }
  }
  function onPanelClick(e) {
    var b = e.target && e.target.closest ? e.target.closest('[data-nav]') : null; if (!b) return;
    var a = b.getAttribute('data-nav'), cand = st.sel || st.tap;
    if (a === 'route-sel' && cand) to(cand, { quiet: true });
    else if (a === 'via-sel' && cand) addVia(cand);
    else if (a === 'start') start();
    else if (a === 'resume') start();
    else if (a === 'next') nextLeg();
    else if (a === 'stop') stopFollow();
    else if (a === 'rejoin') rejoin();
    else if (a === 'clear') clear();
    else if (a === 'copy') copyLink();
  }
  function shareURL() {
    var d = st.dest, q = buildDestination({ coordinates: [+d.lon.toFixed(6), +d.lat.toFixed(6)], name: d.name, asset: d.source && d.id ? { source: d.source, id: d.id } : null });
    return location.origin + location.pathname + q;
  }
  function copyLink() {
    if (!st.dest) return;
    var u = shareURL();
    if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(u).then(function () { note('Route link copied'); }, function () { note(u); });
    else note(u);
  }
  // A 44 px "Route here" button other modules may put in their cards (W07 plan uses PILOT.nav.button).
  function button(asset, label) {
    var b = D.createElement('button'); b.type = 'button'; b.className = 'p-nav-btn p-nav-route'; b.textContent = label || 'Route here';
    b.addEventListener('click', function (e) { e.stopPropagation(); to(asset); });
    return b;
  }

  // ---- route layer: draped on the ground, done part dim, stop beacons
  var layer = {
    id: 'nav', title: 'SatNav route', order: 40, visible: true,
    draw: function (g, v, now) {
      if (!st.route) return;
      var c = st.route.geometry.coordinates, bb = v.bbox, done = st.fix && st.fix.status === 'ok' ? st.fix.progressM : 0;
      var step = v.lod >= 3 ? 8 : v.lod === 2 ? 4 : v.lod === 1 ? 2 : 1, pad = bb ? Math.max(0.05, (bb.n - bb.s) * 0.5) : 0;
      var inb = function (p) { return !bb || (p[1] >= bb.s - pad && p[1] <= bb.n + pad && p[0] >= bb.w - pad && p[0] <= bb.e + pad); };
      g.save(); g.lineCap = 'round'; g.lineJoin = 'round';
      var pass = function (dim) {
        g.beginPath(); var m = 0, prev = c[0], j = 0;
        while (j < c.length - 1) {
          j = Math.min(j + step, c.length - 1);
          var p = c[j], segM = metres(prev, p), isDone = m + segM <= done;
          if (isDone === dim && (inb(prev) || inb(p))) v.line([prev[1], prev[0], null], [p[1], p[0], null]);
          m += segM; prev = p;
        }
        g.strokeStyle = dim ? 'rgba(120,160,170,.55)' : '#ff3df0'; g.lineWidth = dim ? 3 : 5; g.stroke();
      };
      pass(true); pass(false);
      var S = st.route.stops;
      for (var k = 1; k < S.length; k++) {
        var a = v.project(S[k].lat, S[k].lon, null), b = v.project(S[k].lat, S[k].lon, (PILOT.ground ? PILOT.ground(S[k].lat, S[k].lon) : 0) + 120);
        if (!a || !b) continue;
        var last = k === S.length - 1;
        g.strokeStyle = last ? '#ff3df0' : '#ffd23d'; g.lineWidth = 3; g.beginPath(); g.moveTo(a.x, a.y); g.lineTo(b.x, b.y); g.stroke();
        g.fillStyle = g.strokeStyle; g.font = 'bold 12px ui-monospace,monospace'; g.fillText((last ? '◎ ' : k + ' ') + S[k].name.slice(0, 32), b.x + 6, b.y);
      }
      g.restore();
    },
    pick: function () { return null; }
  };

  // ---- inputs from other modules (events only, CONTRACT §1/§8)
  function remember(kind) { return function (d) { var s = asStop(Object.assign({ source: kind }, d || {})); if (s) { st.sel = s; renderPanel(); } }; }
  if (PILOT.on) {
    PILOT.on('nav:route', function (d) { to(d); });
    PILOT.on('nav:via', function (d) { addVia(d); });
    PILOT.on('ukpn:select', remember('ukpn'));
    PILOT.on('grid:select', remember('grid'));
    PILOT.on('repd:select', remember('repd'));
    PILOT.on('pick', function (d) { var o = d && (d.pick || d); if (o && okLL(+o.lat, +o.lon)) { st.sel = asStop(o); renderPanel(); } });
    PILOT.on('tap', function (d) { var s = asStop(Object.assign({ name: 'Tapped point ' + (+d.lat).toFixed(5) + ', ' + (+d.lon).toFixed(5) }, d)); if (s) { st.tap = s; st.sel = null; renderPanel(); } });
    PILOT.on('steer:cancel', function () { if (st.following) { st.steering = false; st.paused = true; renderPanel(); renderHud(true); } });
  }
  if (PILOT.onFrame) PILOT.onFrame(frame);
  if (PILOT.addLayer) PILOT.addLayer(layer);

  PILOT.nav = { version: '1', core: CORE, to: to, addVia: addVia, clear: clear, start: start, stop: function () { stopFollow(); }, resume: start,
    nextLeg: nextLeg, rejoin: rejoin, button: button, link: function () { return st.dest ? shareURL() : null; },
    route: function () { return st.route; },
    state: function () { return { following: st.following, paused: st.paused, arrived: st.arrived, leg: st.leg, off: st.off, fix: st.fix,
      cue: st.route && st.fix && st.fix.status === 'ok' ? nextCue(st.cues, st.fix.progressM).cue : null, steering: st.steering }; } };

  function boot() {
    renderPanel();
    var d = null;
    try { var p = parseDestination(location.search); if (p) d = { lat: p.coordinates[1], lon: p.coordinates[0], name: p.name, source: p.asset && p.asset.source, id: p.asset && p.asset.id }; }
    catch (e) { note('SatNav link not used: ' + e.message); }
    if (!d && PILOT.hash) { var h = PILOT.hash('nav'); if (h) { var a = String(h).split(','); if (a.length >= 2) d = { lat: +a[0], lon: +a[1], name: a.slice(2).join(',') || '' }; } }
    if (d) to(d);   // a SatNav link opens the panel with its route
  }
  if (PILOT.ready) PILOT.ready(boot); else boot();
})();

Pilot Subfind

A style sheet in the theme folder of Cosmic.

rendercosmic / tools/explore/theme/pilot-subfind.css · lines 1–55 of 55 · Entry point

What it does
Side effects: changes the web page (DOM).
Downstream impact
Used directly by 1 file: Pilot (cosmic, https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html).
What it achieves
Pilot module "subfind" (AZIMUTH-47). Every selector prefixed p-subfind-; colours follow `pilot.css` tokens.
Why it matters
Loaded by the Pilot page at https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html.
Application
cosmic · tools/explore/theme · style sheet
Uses
none found
Used by
loaded by Pilot (stylesheet)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/theme/pilot-subfind.css:1-55 · blob e2ed6fbee8d4c67a6c8b8a8742ea9032b4ecd8c6 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
/* Pilot module "subfind" (AZIMUTH-47). Every selector prefixed p-subfind-; colours follow pilot.css tokens. */
.p-subfind-hudbtn { min-height: 44px; padding: 0 16px; gap: 8px; font-size: 13px; font-weight: 600; color: #000; background: var(--acc, #00ffff); border-color: var(--acc, #00ffff); white-space: nowrap; }
.p-subfind-hudbtn:hover, .p-subfind-hudbtn:active { color: #000; background: #fff; border-color: #fff; }
.p-subfind-hudbtn span { font-size: 16px; line-height: 1; }
@media (max-width: 899px) { .p-subfind-hudbtn { min-height: 48px; min-width: 220px; font-size: 15px; } }
.p-hud-sub:has(> .p-subfind-hudbtn) { padding: 2px; background: none; border: 0; }

.p-subfind-form { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
.p-subfind-sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
.p-subfind-lab { font-size: 10px; letter-spacing: .12em; color: var(--dim, #a6adbb); margin: 0; }
.p-subfind-bar { display: flex; gap: 6px; min-width: 0; }
.p-subfind-q { flex: 1 1 160px; min-width: 0; min-height: 48px; box-sizing: border-box; padding: 0 12px; font: 16px ui-monospace, Menlo, Consolas, monospace;
  color: #fff; background: #05080d; border: 1px solid var(--line, #2f343d); border-radius: 6px; }
.p-subfind-q:focus { border-color: var(--acc, #00ffff); outline: none; }
.p-subfind-go { flex: 0 0 auto; min-width: 72px; min-height: 48px; color: #000; background: var(--acc, #00ffff); border-color: var(--acc, #00ffff); font-weight: 600; }
.p-subfind-dim { color: var(--dim, #a6adbb); margin: 0; font-size: 11px; overflow-wrap: anywhere; }
.p-subfind-chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0 0; min-width: 0; }
.p-subfind-chip { display: inline-flex; align-items: center; gap: 6px; min-height: 44px; min-width: 44px; box-sizing: border-box; padding: 0 12px; max-width: 100%;
  font: 12px ui-monospace, Menlo, monospace; color: #d8dde6; background: var(--panel, rgba(11, 14, 20, .86)); border: 1px solid var(--line, #2f343d); border-radius: 22px; cursor: pointer; overflow-wrap: anywhere; text-align: left; }
.p-subfind-chip i { width: 10px; height: 10px; border-radius: 2px; flex: 0 0 auto; }
.p-subfind-chip small { color: var(--dim, #a6adbb); }
.p-subfind-chip[aria-pressed="true"] { color: #000; background: var(--acc, #00ffff); border-color: #fff; }
.p-subfind-chip:hover, .p-subfind-chip:focus-visible { border-color: var(--acc, #00ffff); }
.p-subfind-status { margin: 8px 0 0; color: var(--dim, #a6adbb); overflow-wrap: anywhere; }
.p-subfind-status:empty { display: none; }
.p-subfind-error { color: #ffb3b3; } .p-subfind-warn, .p-subfind-none { color: var(--warn, #ffae00); }
p.p-subfind-error, p.p-subfind-warn, p.p-subfind-none { margin: 6px 0; overflow-wrap: anywhere; }
.p-subfind-status.p-subfind-error, p.p-subfind-error { border-left: 3px solid #ff5c5c; padding-left: 8px; }
.p-subfind-h { margin: 12px 0 4px; font-size: 12px; color: var(--acc, #00ffff); letter-spacing: .04em; overflow-wrap: anywhere; }
.p-subfind-h small { color: var(--dim, #a6adbb); font-weight: 400; }
.p-subfind-origin { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-top: 10px; padding: 6px 8px; border: 1px solid #00ffff55; border-radius: 6px; overflow-wrap: anywhere; min-width: 0; }
.p-subfind-origin > div { min-width: 0; }
.p-subfind-origin .pbtn { flex: 0 0 auto; }
.p-subfind-pin { display: inline-block; width: 0; height: 0; margin-right: 6px; border: 6px solid transparent; border-top: 10px solid var(--acc, #00ffff); vertical-align: -3px; }
.p-subfind-alts { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin-top: 6px; }
.p-subfind-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; }
.p-subfind-row { padding: 8px; background: var(--panel, rgba(11, 14, 20, .86)); border: 1px solid var(--line, #2f343d); border-radius: 6px; min-width: 0; }
.p-subfind-head { display: flex; align-items: baseline; gap: 8px; min-width: 0; }
.p-subfind-rank { flex: 0 0 auto; width: 22px; height: 22px; line-height: 20px; box-sizing: border-box; text-align: center; border: 2px solid; border-radius: 50%; font-size: 11px; color: #fff; align-self: center; }
.p-subfind-name { flex: 1 1 auto; min-width: 0; color: #fff; font-weight: 600; overflow-wrap: anywhere; }
.p-subfind-d { flex: 0 0 auto; color: var(--acc, #00ffff); white-space: nowrap; }
.p-subfind-tie { flex: 0 0 auto; font-size: 10px; color: #000; background: var(--warn, #ffae00); border-radius: 3px; padding: 0 4px; }
.p-subfind-brg { flex: 0 0 auto; color: #d8dde6; white-space: nowrap; }
.p-subfind-meta { margin: 2px 0 6px 30px; color: #d8dde6; font-size: 11px; overflow-wrap: anywhere; }
.p-subfind-unk { color: var(--warn, #ffae00); }
.p-subfind-acts { display: flex; flex-wrap: wrap; gap: 6px; }
.p-subfind-acts .pbtn { flex: 1 1 96px; touch-action: manipulation; line-height: 1.2; text-align: center; }
.p-subfind-fly { color: #000; background: var(--acc, #00ffff); border-color: var(--acc, #00ffff); font-weight: 600; }
.p-subfind-ga { color: var(--link, #66ccff); }
.p-subfind-rhead { display: flex; align-items: center; justify-content: space-between; margin-top: 12px; }
.p-subfind-cav { font-size: 10px; color: var(--dim, #a6adbb); margin: 10px 0 0; overflow-wrap: anywhere; }
.p-subfind-cmeta { margin: 2px 0; overflow-wrap: anywhere; }
.p-subfind-link { display: inline-flex; align-items: center; min-height: 44px; }
@media (max-width: 899px) { .p-subfind-wide, #p-subfind-hint { display: none; } .p-subfind-chips { gap: 5px; margin-top: 6px; } .p-subfind-chip { padding: 0 10px; } }
@media (prefers-reduced-motion: reduce) { .p-subfind-hudbtn, .p-subfind-chip, .p-subfind-row { transition: none; animation: none; } }