From 00dd546b1cb44e108bf6fcbf22cc7e08d8886d73 Mon Sep 17 00:00:00 2001 From: James Babcock Date: Thu, 3 Sep 2026 12:47:30 -0700 Subject: [PATCH] Navigate app: Location indicator rotates based on the compass; darken the map background color --- .../faceclaw/app/FaceclawBleCommunicator.java | 86 +++++++++--- .../faceclaw/app/FaceclawCompassListener.java | 2 +- CHANGELOG | 2 + app/apps/navigate/navigate-app.worker.ts | 125 ++++++++++++++++-- app/native/compass.ts | 15 ++- app/native/mapbox.ts | 58 ++++++-- 6 files changed, 246 insertions(+), 42 deletions(-) diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleCommunicator.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleCommunicator.java index 7f09b50d..4537aa71 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleCommunicator.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleCommunicator.java @@ -60,7 +60,18 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable { private volatile FaceclawBleCommunicatorListener listener; private final java.util.List imuListeners = new java.util.concurrent.CopyOnWriteArrayList<>(); - private final java.util.List compassListeners = + /** A compass subscriber plus the Looper it registered from (see addCompassListener). */ + private static final class CompassSubscription { + final FaceclawCompassListener listener; + final Handler handler; + + CompassSubscription(FaceclawCompassListener listener, Handler handler) { + this.listener = listener; + this.handler = handler; + } + } + + private final java.util.List compassSubscriptions = new java.util.concurrent.CopyOnWriteArrayList<>(); private final java.util.List micStatusListeners = new java.util.concurrent.CopyOnWriteArrayList<>(); @@ -90,7 +101,13 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable { private int firmwareDebugFlagsLastSent = -1; // Desired CFW mode-10 compass state. It survives reconnects; lastSent is // reset with each session so an open Compass window is re-asserted. - private boolean compassEnabled; + /** + * Who currently wants the stock compass running (the Compass window, the + * Navigate worker, ...). The magnetometer is one shared resource, so it + * stays on while any owner holds it and is released when the last lets go; + * this keeps one app's release from silently switching off another's feed. + */ + private final java.util.Set compassOwners = new java.util.HashSet<>(); private int compassControlLastSent = -1; // Whether the glasses-side compass may still be running: set when an enable // is enqueued, cleared only when a disable is acked. Drives the forced @@ -481,12 +498,32 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable { * stock sid-0x08 navigation notifications and FaceclawCompassListeners. */ public void setCompassEnabled(boolean enable) { + setCompassEnabled("compass", enable); + } + + /** + * As above, on behalf of a named owner. The compass runs while at least + * one owner has enabled it; an owner disabling it only takes effect once + * no other owner still wants it. + */ + public void setCompassEnabled(String owner, boolean enable) { synchronized (lock) { - compassEnabled = enable; + boolean before = !compassOwners.isEmpty(); + if (enable) { + compassOwners.add(owner); + } else { + compassOwners.remove(owner); + } + boolean wanted = !compassOwners.isEmpty(); + if (wanted == before && compassControlLastSent == (wanted ? 1 : 0)) { + logLine("compass " + (enable ? "enable" : "disable") + " by " + owner + + "; state unchanged (owners=" + compassOwners + ")"); + return; + } compassControlLastSent = -1; clearMessagesOfKindLocked("compass-control"); if (running && sessionReady && !shutdownRequested && fixedLayoutCreated) { - enqueueCompassControlLocked(true, compassEnabled); + enqueueCompassControlLocked(true, wanted); } else { logLine("defer compass " + (enable ? "enable" : "disable") + "; display path not ready"); } @@ -645,15 +682,28 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable { } } + /** + * Subscribe to compass events. Callbacks are delivered on the Looper of + * the thread that registered (falling back to the main thread), so app + * worker isolates can listen without a cross-thread hop into their JS. + */ public void addCompassListener(FaceclawCompassListener listener) { - if (listener != null) { - compassListeners.add(listener); + if (listener == null) { + return; } + Looper looper = Looper.myLooper(); + Handler handler = looper != null ? new Handler(looper) : mainHandler; + compassSubscriptions.add(new CompassSubscription(listener, handler)); } public void removeCompassListener(FaceclawCompassListener listener) { - if (listener != null) { - compassListeners.remove(listener); + if (listener == null) { + return; + } + for (CompassSubscription subscription : compassSubscriptions) { + if (subscription.listener == listener) { + compassSubscriptions.remove(subscription); + } } } @@ -1897,10 +1947,11 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable { } if (messageToPrewrite == null && !shutdownRequested && fixedLayoutCreated - && (compassEnabled ? 1 : 0) != compassControlLastSent + && (compassOwners.isEmpty() ? 0 : 1) != compassControlLastSent && pendingMessages.isEmpty() && inFlightMessages.isEmpty()) { - Log.i(TAG, "enqueueing compass " + (compassEnabled ? "enable" : "disable")); - enqueueCompassControlLocked(false, compassEnabled); + boolean wanted = !compassOwners.isEmpty(); + Log.i(TAG, "enqueueing compass " + (wanted ? "enable" : "disable")); + enqueueCompassControlLocked(false, wanted); } // Up to WINDOW_SIZE messages may be in flight at once (full @@ -3310,18 +3361,15 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable { } private void emitCompassEvent(int command, int headingDegrees) { - if (compassListeners.isEmpty()) { - return; - } - mainHandler.post(() -> { - for (FaceclawCompassListener compassListener : compassListeners) { + for (CompassSubscription subscription : compassSubscriptions) { + subscription.handler.post(() -> { try { - compassListener.onCompassEvent(command, headingDegrees); + subscription.listener.onCompassEvent(command, headingDegrees); } catch (Throwable t) { Log.w(TAG, "listener onCompassEvent failed", t); } - } - }); + }); + } } private void emitSilentMode(boolean silent) { diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawCompassListener.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawCompassListener.java index 39f476f3..9c77ce2c 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawCompassListener.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawCompassListener.java @@ -1,6 +1,6 @@ package com.faceclaw.app; -/** Receives stock compass heading and calibration notifications on the main thread. */ +/** Receives stock compass heading and calibration notifications on the thread that subscribed. */ public interface FaceclawCompassListener { void onCompassEvent(int command, int headingDegrees); } diff --git a/CHANGELOG b/CHANGELOG index aac58adc..7c3535de 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -6,6 +6,8 @@ * Move some items from app context menus to the system context menu * Long-press now opens the system context menu and tap-then-hold the app context menu (games keep long-press as a move while playing) * Content beneath an open context menu is dimmed +* Navigate app: Location indicator rotates based on the compass +* Navigate app: Darken the map background color ## 0.6.4 - 2026-09-02 * Context menus are centered and include window title diff --git a/app/apps/navigate/navigate-app.worker.ts b/app/apps/navigate/navigate-app.worker.ts index 6feb920a..1e6bb848 100644 --- a/app/apps/navigate/navigate-app.worker.ts +++ b/app/apps/navigate/navigate-app.worker.ts @@ -30,6 +30,9 @@ import { type RouteProfile, type StaticMapCamera, } from "../../native/mapbox"; +import { addCompassListener, COMPASS_CHANGED, setCompassEnabled, type CompassEvent } from "../../native/compass"; +import { magneticDeclinationDegrees } from "../../native/geomagnetic"; +import { calibrateHeading, normalizeHeading } from "../compass/calibration"; import { bearingDegrees, haversineMeters, RouteFollower, type RouteProgress } from "./route-follower"; import { drawManeuverGlyph } from "./maneuver-icons"; @@ -49,6 +52,10 @@ const FIRST_FIX_TIMEOUT_MS = 10_000; const LOCATION_INTERVAL_MS = 1_000; /** Above this speed a GPS bearing is trustworthy for heading-up. */ const BEARING_MIN_SPEED_MPS = 2.5; +/** The head-direction chevron only redraws once the wearer has turned this far. */ +const HEADING_STEP_DEG = 4; +/** Our claim on the shared glasses magnetometer (see setCompassEnabled). */ +const COMPASS_OWNER = "navigate"; const largeFont = getFont("terminus32"); const mediumFont = getFont("terminus24"); @@ -134,6 +141,17 @@ let mapLastFetchAtMs = 0; let mapLastFetchCenter: [number, number] | null = null; let mapNextRetryAtMs = 0; let mapLastError = ""; +/** Bearing the current map image was rendered with (its "up"), for follow mode. */ +let mapFetchedBearingDeg = 0; + +// Glasses compass: the same firmware feed and wearer calibration as the +// Compass app, so the position chevron shows where the wearer is looking +// relative to the map rather than always pointing up the direction of travel. +let compassActive = false; +let unsubscribeCompass: (() => void) | null = null; +/** Wearer's true heading (degrees clockwise from north) as last drawn, or null before compass data arrives. */ +let headHeadingDeg: number | null = null; +let declinationCache: { latitude: number; longitude: number; degrees: number | null } | null = null; let tickTimer: ReturnType | null = null; let firstFixWaiters: Array<(fix: TrackedLocation) => void> = []; @@ -177,6 +195,7 @@ global.onmessage = (event: { data: WorkerAppMessage }) => { case "close-window": stopNavigation(""); window = null; + reconcileCompass(); break; case "input": if (!window || window.windowId !== message.windowId) { @@ -204,6 +223,7 @@ global.onmessage = (event: { data: WorkerAppMessage }) => { if (!window) break; window.foreground = message.foreground; window.focused = message.focused; + reconcileCompass(); if (window.foreground) { maybeRefreshMap(); render(); @@ -211,6 +231,7 @@ global.onmessage = (event: { data: WorkerAppMessage }) => { break; case "screen": screenOn = message.on; + reconcileCompass(); if (screenOn && window?.foreground) { maybeRefreshMap(); render(); @@ -397,6 +418,59 @@ function waitForFix(): Promise { }); } +// --------------------------------------------------------------------------- +// Head heading (glasses compass) + +/** Hold the magnetometer only while its reading is actually on screen. */ +function reconcileCompass(): void { + const wanted = + window !== null && window.foreground && screenOn && phase === "navigating" && mapMode === "follow"; + if (wanted === compassActive) return; + compassActive = wanted; + if (wanted) { + unsubscribeCompass = addCompassListener(handleCompassEvent); + setCompassEnabled(true, COMPASS_OWNER); + } else { + setCompassEnabled(false, COMPASS_OWNER); + unsubscribeCompass?.(); + unsubscribeCompass = null; + headHeadingDeg = null; + } +} + +function handleCompassEvent(event: CompassEvent): void { + if (!compassActive || event.command !== COMPASS_CHANGED || event.headingDegrees < 0) return; + // Wearer-fit offset from the Compass app's calibration, then declination + // from our own GPS fix: the map is always true-north referenced. + const magnetic = calibrateHeading(event.headingDegrees); + const heading = normalizeHeading(magnetic + (currentDeclination() ?? 0)); + if (headHeadingDeg !== null && angularDistance(heading, headHeadingDeg) < HEADING_STEP_DEG) return; + headHeadingDeg = heading; + render(); +} + +/** Declination at the last fix; it only varies over tens of kilometres, so cache per coarse position. */ +function currentDeclination(): number | null { + if (!lastFix) return null; + if ( + !declinationCache || + Math.abs(declinationCache.latitude - lastFix.latitude) > 0.5 || + Math.abs(declinationCache.longitude - lastFix.longitude) > 0.5 + ) { + declinationCache = { + latitude: lastFix.latitude, + longitude: lastFix.longitude, + degrees: magneticDeclinationDegrees(lastFix.latitude, lastFix.longitude), + }; + } + return declinationCache.degrees; +} + +function angularDistance(a: number, b: number): number { + const delta = Math.abs(normalizeHeading(a) - normalizeHeading(b)); + return Math.min(delta, 360 - delta); +} + function ensureTickTimer(): void { const shouldRun = phase === "navigating"; if (shouldRun && tickTimer === null) { @@ -515,9 +589,10 @@ function maybeRefreshMap(): void { .then((image) => { mapInFlight = false; if (generation !== routeGeneration) return; // Route/mode changed mid-fetch. - boostContrast(image); + levelMap(image); mapImage = image; mapFetchedKey = view.key; + mapFetchedBearingDeg = view.camera.kind === "center" ? view.camera.bearingDeg : 0; mapLastFetchAtMs = Date.now(); mapLastFetchCenter = view.camera.kind === "center" ? [view.camera.longitude, view.camera.latitude] : null; mapLastError = ""; @@ -542,11 +617,25 @@ function simplifyPath(path: Array<[number, number]>, maxPoints: number): Array<[ return out; } -/** Stretch the dark-style render so roads survive 4bpp quantization. */ -function boostContrast(image: GrayImage): void { +/** + * Level the render for the lens. The dominant tone is the land fill: black + * when the style override took, dark gray otherwise. Either way it becomes + * the black point, and everything above it is stretched so roads survive + * 4bpp quantization. + */ +function levelMap(image: GrayImage): void { + const histogram = new Uint32Array(256); + for (let i = 0; i < image.pixels.length; i++) histogram[image.pixels[i]!]++; + let black = 0; + for (let value = 1; value < 256; value++) { + if (histogram[value]! > histogram[black]!) black = value; + } + // A bright dominant tone isn't a floor (a large plaza, a fetch that came + // back mostly label); flattening it would eat the roads. + if (black > 64) black = 0; for (let i = 0; i < image.pixels.length; i++) { const value = image.pixels[i]!; - image.pixels[i] = Math.max(0, Math.min(255, Math.round((value - 12) * 1.7))); + image.pixels[i] = value <= black ? 0 : Math.min(255, Math.round((value - black) * 1.7)); } } @@ -728,7 +817,12 @@ function paintNavigating(image: GrayImage, win: NavWindow): void { // Map pane (left). if (mapImage) { image.bitBlt(mapImage, 0, 0); - if (mapMode === "follow") drawChevron(image, MAP_SIZE / 2, MAP_SIZE / 2); + if (mapMode === "follow") { + // Head heading relative to the map's up (its render bearing); no + // compass reading yet means "up", i.e. the direction of travel. + const angle = headHeadingDeg === null ? 0 : headHeadingDeg - mapFetchedBearingDeg; + drawChevron(image, MAP_SIZE / 2, MAP_SIZE / 2, angle); + } } else { image.drawRect(0, 0, MAP_SIZE, MAP_SIZE, 60); const text = mapLastError ? "Map unavailable" : "Loading map..."; @@ -788,11 +882,21 @@ function paintNavigating(image: GrayImage, win: NavWindow): void { drawFooter(image, `${GESTURE_SCROLL} zoom ${GESTURE_CLICK} ${modeHint} ${GESTURE_DOUBLE_CLICK} back`, PANEL_X + 8); } -/** Position chevron, fixed at the map center (heading-up: it always points up). */ -function drawChevron(image: GrayImage, cx: number, cy: number): void { +/** + * Position chevron, fixed at the map center and rotated `angleDeg` clockwise + * from straight up (the map's render bearing) to the wearer's head heading. + */ +function drawChevron(image: GrayImage, cx: number, cy: number, angleDeg: number): void { + const radians = (angleDeg * Math.PI) / 180; + const cos = Math.cos(radians); + const sin = Math.sin(radians); + const triangle = (points: Array<[number, number]>, value: number): void => { + const [a, b, c] = points.map(([x, y]): [number, number] => [cx + x * cos - y * sin, cy + x * sin + y * cos]); + fillTriangle(image, a![0], a![1], b![0], b![1], c![0], c![1], value); + }; // Black halo first so it reads over bright roads. - fillTriangle(image, cx, cy - 11, cx - 9, cy + 9, cx + 9, cy + 9, 0); - fillTriangle(image, cx, cy - 8, cx - 6, cy + 6, cx + 6, cy + 6, 255); + triangle([[0, -11], [-9, 9], [9, 9]], 0); + triangle([[0, -8], [-6, 6], [6, 6]], 255); } function fillTriangle(image: GrayImage, x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, value: number): void { @@ -876,6 +980,9 @@ function render(): void { } function renderAndSubmit(win: NavWindow, inputFrameId: number): void { + // Every state change funnels through here, so it doubles as the point where + // the compass claim tracks foreground/phase/mode. + reconcileCompass(); if (!win.foreground && inputFrameId === 0) return; const frameId = inputFrameId > 0 ? inputFrameId : frameTimings.startFrame(`render:${win.windowId}`); try { diff --git a/app/native/compass.ts b/app/native/compass.ts index e8b5751e..5b4cbdfb 100644 --- a/app/native/compass.ts +++ b/app/native/compass.ts @@ -20,16 +20,23 @@ function activeCommunicator(): any { } } -/** Request CFW mode 10 to start/stop the stock firmware compass. */ -export function setCompassEnabled(enabled: boolean): void { +/** + * Request CFW mode 10 to start/stop the stock firmware compass on behalf of + * `owner`. The magnetometer is shared: it runs while any owner wants it and + * stops once the last one releases it, so apps can't switch each other off. + */ +export function setCompassEnabled(enabled: boolean, owner = "compass"): void { try { - activeCommunicator()?.setCompassEnabled(enabled); + activeCommunicator()?.setCompassEnabled(owner, enabled); } catch (error) { console.warn(`setCompassEnabled failed: ${error}`); } } -/** Subscribe to stock compass heading/calibration notifications. */ +/** + * Subscribe to stock compass heading/calibration notifications. Events are + * delivered on the calling thread's Looper, so this works from app workers. + */ export function addCompassListener(listener: (event: CompassEvent) => void): () => void { const active = activeCommunicator(); if (!active) return () => {}; diff --git a/app/native/mapbox.ts b/app/native/mapbox.ts index a8336f31..364d9252 100644 --- a/app/native/mapbox.ts +++ b/app/native/mapbox.ts @@ -18,6 +18,23 @@ const DIRECTIONS_ROOT = "https://api.mapbox.com/directions/v5"; const STATIC_ROOT = "https://api.mapbox.com/styles/v1"; /** Classic dark style; readable after gray conversion. Swappable for a custom Studio style later. */ const MAP_STYLE = "mapbox/dark-v11"; +/** + * Render-time style override: a black background inserted beneath the road + * stack so land, landuse, water, and building fills all come out black on the + * lens (dark-v11's own fills are dark gray, which the lens shows as a lit + * haze). Static Images allows one added layer per request; `before_layer` + * must name a layer in the style, so candidates are tried in order and a + * rejected one is skipped for the rest of the session, ending with the plain + * style (the worker's levelling pass then does what it can client-side). + */ +const STYLE_OVERRIDE_LAYER = JSON.stringify({ + id: "faceclaw-blackout", + type: "background", + paint: { "background-color": "#000000" }, +}); +/** First road layer of dark-v11, then a layer common to every Streets-based style. */ +const STYLE_OVERRIDE_BEFORE_LAYERS = ["tunnel-path-trail", "building"]; +let styleOverrideIndex = 0; const FETCH_TIMEOUT_MS = 15_000; export type RouteProfile = "driving" | "walking" | "cycling"; @@ -188,18 +205,32 @@ export async function fetchStaticMapGray(options: { : `${round6(options.camera.longitude)},${round6(options.camera.latitude)},` + `${options.camera.zoom.toFixed(2)},${Math.round(normalizeBearing(options.camera.bearingDeg))}`; const size = `${Math.round(options.width)}x${Math.round(options.height)}`; - const params = queryString({ - access_token: requireToken(), - logo: "false", - attribution: "false", - }); - const url = `${STATIC_ROOT}/${MAP_STYLE}/static/${overlay}${camera}/${size}?${params}`; + let bytes: ArrayBuffer; + for (;;) { + const beforeLayer = STYLE_OVERRIDE_BEFORE_LAYERS[styleOverrideIndex]; + const params: Record = { + access_token: requireToken(), + logo: "false", + attribution: "false", + }; + if (beforeLayer !== undefined) { + params.addlayer = STYLE_OVERRIDE_LAYER; + params.before_layer = beforeLayer; + } + const url = `${STATIC_ROOT}/${MAP_STYLE}/static/${overlay}${camera}/${size}?${queryString(params)}`; - const response = await fetchWithTimeout(url, "Mapbox static map"); - if (!response.ok) { + const response = await fetchWithTimeout(url, "Mapbox static map"); + if (response.ok) { + bytes = await response.arrayBuffer(); + break; + } + if (beforeLayer !== undefined && isStyleOverrideRejection(response.status)) { + console.warn(`Mapbox rejected the map style override (before_layer=${beforeLayer}, HTTP ${response.status}); falling back`); + styleOverrideIndex++; + continue; + } throw new Error(`Mapbox static map failed (HTTP ${response.status}).`); } - const bytes = await response.arrayBuffer(); if (!global.isAndroid) throw new Error("Map decoding is only available on Android."); const image = grayImageFromPacket( com.faceclaw.app.ImageFileLoader.loadGrayFromBytes(bytes, Math.round(options.width), Math.round(options.height)), @@ -281,6 +312,15 @@ async function fetchWithTimeout(url: string, label: string): Promise { } } +/** + * A client error that plausibly blames the added layer (an unknown + * before_layer, or a style without it), as opposed to token or quota trouble + * that the plain request would hit just the same. + */ +function isStyleOverrideRejection(status: number): boolean { + return status >= 400 && status < 500 && status !== 401 && status !== 403 && status !== 429; +} + function normalizeBearing(bearingDeg: number): number { return ((bearingDeg % 360) + 360) % 360; }