diff --git a/app/apps/compass/calibration-layer.ts b/app/apps/compass/calibration-layer.ts new file mode 100644 index 00000000..305e6ffa --- /dev/null +++ b/app/apps/compass/calibration-layer.ts @@ -0,0 +1,111 @@ +/** + * The compass calibration screen: a crosshair the wearer aims at a landmark + * of known heading, plus raw/offset/calibrated readouts. Swipe adjusts the + * offset by 1°, double-tap returns to the compass. + */ +import { GrayImage } from "../../graphics/image"; +import { getDefaultMediumFont, getDefaultSmallFont } from "../../graphics/ui-fonts"; +import { wrapText } from "../../graphics/textwrap"; +import { type DashboardInputEvent, type Layer, type LayerContext } from "../../ui/layers"; +import { lineStep } from "../../ui/metrics"; +import { screenCenterInViewportX } from "../../ui/shell/geometry"; +import { + formatOffset, + getCompassOffset, + markCompassCalibrated, + normalizeHeading, + setCompassOffset, +} from "./calibration"; + +const INSTRUCTIONS = + "This compass uses the magnetometer in the right arm of the glasses; depending how it rests on your head, " + + "it may be slightly off. To calibrate, look at a distant object or down a street where you know the true " + + "compass heading, then adjust the calibration offset below"; + +/** Margins around the instruction paragraph. */ +const TEXT_PADDING_X = 16; +const TEXT_PADDING_TOP = 10; + +export class CompassCalibrationLayer implements Layer { + constructor( + /** Current uncorrected magnetometer heading, or null before the first reading. */ + private readonly getRawHeading: () => number | null, + ) {} + + paint(ctx: LayerContext): GrayImage { + const { width, height } = ctx.stack.getBaseSize(); + const image = new GrayImage(width, height, 0); + const small = getDefaultSmallFont(); + const medium = getDefaultMediumFont(); + const smallStep = lineStep(small); + + const lines = wrapText(small, INSTRUCTIONS, width - TEXT_PADDING_X * 2); + for (let i = 0; i < lines.length; i++) { + image.drawText(small, TEXT_PADDING_X, TEXT_PADDING_TOP + i * smallStep, lines[i]!, 190); + } + const textBottom = TEXT_PADDING_TOP + lines.length * smallStep; + + // Readouts along the bottom: dim label over a bright value, in thirds. + const valueTop = height - medium.lineHeight; + const labelTop = valueTop - small.lineHeight; + const raw = this.getRawHeading(); + const offset = getCompassOffset(); + const columns: Array<[string, string]> = [ + ["Raw", raw === null ? "--°" : `${Math.round(raw)}°`], + ["Offset", formatOffset(offset)], + ["Calibrated", raw === null ? "--°" : `${Math.round(normalizeHeading(raw + offset))}°`], + ]; + const columnWidth = width / columns.length; + for (let i = 0; i < columns.length; i++) { + const [label, value] = columns[i]!; + const center = columnWidth * (i + 0.5); + image.drawText(small, Math.round(center - small.measureText(label) / 2), labelTop, label, 130); + image.drawText(medium, Math.round(center - medium.measureText(value) / 2), valueTop, value, 255); + } + + // The crosshair marks where the wearer is looking, so its horizontal + // position must be the true centre of the display, not of the app + // viewport the sidebar has pushed to the right. Vertically it just sits in + // the free space between the instructions and the readouts; the window + // band's own placement on screen is the wearer's Display setting and + // doesn't affect the heading being aimed. + const crosshairX = screenCenterInViewportX(); + const crosshairY = Math.round((textBottom + labelTop) / 2); + drawCrosshair(image, crosshairX, crosshairY); + return image; + } + + handleInput(event: DashboardInputEvent, ctx: LayerContext): void { + if (event.type === "scroll-up") { + this.adjust(1); + } else if (event.type === "scroll-down") { + this.adjust(-1); + } else if (event.type === "double-click") { + // Leaving the screen counts as accepting the calibration, so an offset + // the wearer decides is already correct still clears the prompt. + markCompassCalibrated(); + ctx.stack.pop(); + } + } + + private adjust(delta: number): void { + setCompassOffset(getCompassOffset() + delta); + markCompassCalibrated(); + } +} + +/** A gapped crosshair: four arms around an open centre with a ring. */ +function drawCrosshair(image: GrayImage, cx: number, cy: number): void { + const gap = 5; + const arm = 16; + const radius = 9; + image.drawLine(cx - gap - arm, cy, cx - gap, cy, 255); + image.drawLine(cx + gap, cy, cx + gap + arm, cy, 255); + image.drawLine(cx, cy - gap - arm, cx, cy - gap, 255); + image.drawLine(cx, cy + gap, cx, cy + gap + arm, 255); + for (let angle = 0; angle < 360; angle += 6) { + const radians = (angle * Math.PI) / 180; + image.setPixel(Math.round(cx + Math.cos(radians) * radius), Math.round(cy + Math.sin(radians) * radius), 180); + } + image.setPixel(cx, cy, 255); +} diff --git a/app/apps/compass/calibration.ts b/app/apps/compass/calibration.ts new file mode 100644 index 00000000..57d1da30 --- /dev/null +++ b/app/apps/compass/calibration.ts @@ -0,0 +1,58 @@ +/** + * Wearer calibration for the glasses compass. + * + * The magnetometer lives in the right arm, which curls around the wearer's + * head, so its zero depends on head shape and how the glasses sit — no + * firmware-side calibration can account for that. We store one persisted + * offset in degrees, added to every raw heading before it is shown. + * + * The "calibrated" flag is separate from a nonzero offset: an offset of 0 can + * be a perfectly good calibration result, and we only want to nag first-time + * users. + */ +import { getBooleanSetting, getStringSetting, setBooleanSetting, setStringSetting } from "../../native/settings-store"; + +const OFFSET_KEY = "compass.calibrationOffsetDegrees"; +const CALIBRATED_KEY = "compass.calibrated"; + +/** Wrap any angle into [0, 360). */ +export function normalizeHeading(value: number): number { + return ((value % 360) + 360) % 360; +} + +/** Persisted calibration offset, wrapped into (-180, 180]. */ +export function getCompassOffset(): number { + const parsed = parseInt(getStringSetting(OFFSET_KEY, "0"), 10); + return Number.isFinite(parsed) ? signedDegrees(parsed) : 0; +} + +export function setCompassOffset(degrees: number): number { + const normalized = signedDegrees(Math.round(degrees)); + setStringSetting(OFFSET_KEY, String(normalized)); + return normalized; +} + +export function isCompassCalibrated(): boolean { + return getBooleanSetting(CALIBRATED_KEY, false); +} + +/** Called once the wearer has been through the calibration screen. */ +export function markCompassCalibrated(): void { + if (!isCompassCalibrated()) setBooleanSetting(CALIBRATED_KEY, true); +} + +/** Raw magnetometer heading corrected by the persisted offset. */ +export function calibrateHeading(rawDegrees: number): number { + return normalizeHeading(rawDegrees + getCompassOffset()); +} + +/** Format a signed offset for display, e.g. "+4°", "0°", "-12°". */ +export function formatOffset(degrees: number): string { + return `${degrees > 0 ? "+" : ""}${degrees}°`; +} + +/** Wrap into (-180, 180] so the offset reads as a small correction either way. */ +function signedDegrees(value: number): number { + const wrapped = normalizeHeading(value); + return wrapped > 180 ? wrapped - 360 : wrapped; +} diff --git a/app/apps/compass/compass-app.ts b/app/apps/compass/compass-app.ts index a6885d7f..39fd807f 100644 --- a/app/apps/compass/compass-app.ts +++ b/app/apps/compass/compass-app.ts @@ -8,7 +8,10 @@ import { setCompassEnabled, type CompassEvent, } from "../../native/compass"; +import { wrapText } from "../../graphics/textwrap"; import { type DashboardInputEvent, type Layer, type LayerContext } from "../../ui/layers"; +import { lineStep } from "../../ui/metrics"; +import { screenCenterInViewportX } from "../../ui/shell/geometry"; import { createInProcessWindow, YieldAtRootLayer, @@ -16,14 +19,21 @@ import { type InProcessWindow, } from "../../ui/shell/in-process-window"; import { shell } from "../../ui/shell/shell"; +import { calibrateHeading, isCompassCalibrated, normalizeHeading } from "./calibration"; +import { CompassCalibrationLayer } from "./calibration-layer"; export const COMPASS_WINDOW_ID = "compass"; export const COMPASS_SURFACE_ID = "window:compass"; const RECONCILE_INTERVAL_MS = 400; +/** Vertical breathing room between the rose, the readout and the status line. */ +const STACK_GAP = 8; +/** Inset of the cardinal-label ring from the rose's outer circle. */ +const LABEL_INSET = 14; class CompassLayer implements Layer { - private heading: number | null = null; - private status = "Waiting for compass data…"; + private rawHeading: number | null = null; + /** A firmware calibration message, shown until the next heading arrives. */ + private firmwareStatus: string | null = null; private enabled = false; private removed = false; private timer: ReturnType | null = null; @@ -52,56 +62,76 @@ class CompassLayer implements Layer { this.stop(); } + openCalibration(ctx: LayerContext): void { + if (ctx.stack.topMatches((layer) => layer instanceof CompassCalibrationLayer)) return; + ctx.stack.push(new CompassCalibrationLayer(() => this.rawHeading)); + } + private reconcile(): void { if (this.removed) return; const visible = shell.isWindowVisible(COMPASS_WINDOW_ID); if (visible === this.enabled) return; this.enabled = visible; setCompassEnabled(visible); - this.status = visible ? "Waiting for compass data…" : "Compass paused"; + this.firmwareStatus = null; this.requestRender(); } private onCompassEvent(event: CompassEvent): void { if (this.removed) return; if (event.command === COMPASS_CHANGED && event.headingDegrees >= 0) { - this.heading = normalizeHeading(event.headingDegrees); - this.status = "Magnetic heading"; + this.rawHeading = normalizeHeading(event.headingDegrees); + this.firmwareStatus = null; } else if (event.command === COMPASS_CALIBRATION_STARTED) { - this.status = "Calibrating — move the glasses"; + this.firmwareStatus = "Calibrating — move the glasses"; } else if (event.command === COMPASS_CALIBRATION_COMPLETE) { - this.status = "Calibration complete"; + this.firmwareStatus = "Calibration complete"; } this.requestRender(); } + private statusText(): string { + if (this.firmwareStatus !== null) return this.firmwareStatus; + if (!this.enabled) return "Compass paused"; + if (this.rawHeading === null) return "Waiting for compass data…"; + return isCompassCalibrated() ? "Magnetic heading" : "Uncalibrated - Tap to calibrate"; + } + paint(ctx: LayerContext): GrayImage { const { width, height } = ctx.stack.getBaseSize(); const image = new GrayImage(width, height, 0); const small = getDefaultSmallFont(); - const medium = getDefaultMediumFont(); const large = getDefaultLargeFont(); - const cx = Math.round(width * 0.28); - const cy = Math.round(height * 0.51); - const radius = Math.min(94, Math.round(height * 0.34)); + const heading = this.rawHeading === null ? null : calibrateHeading(this.rawHeading); + const radius = Math.min(63, Math.round(height * 0.227)); + const headingText = heading === null ? "--°" : `${Math.round(heading)}° ${cardinalDirection(heading)}`; + const statusLines = wrapText(small, this.statusText(), width - STACK_GAP * 2); + const smallStep = lineStep(small); - drawCompassRose(image, cx, cy, radius, this.heading); + // One column centred on the display's true centre, so the rose's centre + // dot sits where the wearer is looking rather than 32px right of it. + const cx = screenCenterInViewportX(); + const stackHeight = radius * 2 + STACK_GAP + large.lineHeight + STACK_GAP + statusLines.length * smallStep; + const cy = Math.max(0, Math.round((height - stackHeight) / 2)) + radius; - if (this.heading !== null) { - const headingText = `${Math.round(this.heading)}°`; - const direction = cardinalDirection(this.heading); - const textX = Math.round(width * 0.57); - image.drawText(large, textX, 72, headingText, 255); - image.drawText(large, textX, 108, direction, 210); - } else { - image.drawText(medium, Math.round(width * 0.56), 84, "--°", 150); - image.drawText(small, Math.round(width * 0.56), 116, "No heading yet", 130); + drawCompassRose(image, cx, cy, radius, heading); + + let y = cy + radius + STACK_GAP; + image.drawText(large, Math.round(cx - large.measureText(headingText) / 2), y, headingText, heading === null ? 150 : 255); + y += large.lineHeight + STACK_GAP; + for (const line of statusLines) { + image.drawText(small, Math.round(cx - small.measureText(line) / 2), y, line, 125); + y += smallStep; } - image.drawText(small, Math.round(width * 0.56), 158, this.status, 125); return image; } - handleInput(_event: DashboardInputEvent, _ctx: LayerContext): void {} + // A tap opens calibration from either state: it is the affordance the + // "Uncalibrated" prompt advertises, and re-calibrating is a normal thing to + // want once the glasses have been taken off and put back on. + handleInput(event: DashboardInputEvent, ctx: LayerContext): void { + if (event.type === "click") this.openCalibration(ctx); + } } export function createCompassAppWindow(options: InProcessAppOptions): InProcessWindow { @@ -116,6 +146,15 @@ export function createCompassAppWindow(options: InProcessAppOptions): InProcessW icon: "compass", closeable: true, actions: options.actions, + menuItems: () => [ + { + label: "Calibrate", + onSelect: (ctx) => { + ctx.stack.pop(); + layer.openCalibration(ctx); + }, + }, + ], baseLayer: new YieldAtRootLayer(layer), submitFrame: options.submitFrame, setSurfaceVisible: options.setSurfaceVisible, @@ -130,10 +169,6 @@ export function createCompassAppWindow(options: InProcessAppOptions): InProcessW return app; } -function normalizeHeading(value: number): number { - return ((value % 360) + 360) % 360; -} - function cardinalDirection(heading: number): string { const names = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]; return names[Math.round(normalizeHeading(heading) / 45) % names.length]!; @@ -147,24 +182,27 @@ function drawCompassRose(image: GrayImage, cx: number, cy: number, radius: numbe const cardinals: Array<[string, number]> = [["N", -90], ["E", 0], ["S", 90], ["W", 180]]; for (const [label, degrees] of cardinals) { const angle = (degrees - (heading ?? 0)) * Math.PI / 180; - const x = cx + Math.cos(angle) * (radius - 14) - medium.measureText(label) / 2; - const y = cy + Math.sin(angle) * (radius - 14) - medium.lineHeight / 2; + const x = cx + Math.cos(angle) * (radius - LABEL_INSET) - medium.measureText(label) / 2; + const y = cy + Math.sin(angle) * (radius - LABEL_INSET) - medium.lineHeight / 2; image.drawText(medium, Math.round(x), Math.round(y), label, label === "N" ? 230 : 105); } const intercardinals: Array<[string, number]> = [["NE", -45], ["SE", 45], ["SW", 135], ["NW", -135]]; for (const [label, degrees] of intercardinals) { const angle = (degrees - (heading ?? 0)) * Math.PI / 180; - const x = cx + Math.cos(angle) * (radius - 14) - small.measureText(label) / 2; - const y = cy + Math.sin(angle) * (radius - 14) - small.lineHeight / 2; + const x = cx + Math.cos(angle) * (radius - LABEL_INSET) - small.measureText(label) / 2; + const y = cy + Math.sin(angle) * (radius - LABEL_INSET) - small.lineHeight / 2; image.drawText(small, Math.round(x), Math.round(y), label, 85); } image.fillRect(cx - 2, cy - 2, 5, 5, 180); if (heading === null) return; const northAngle = (-90 - heading) * Math.PI / 180; - const nx = cx + Math.cos(northAngle) * (radius - 30); - const ny = cy + Math.sin(northAngle) * (radius - 30); - const sx = cx - Math.cos(northAngle) * (radius - 38); - const sy = cy - Math.sin(northAngle) * (radius - 38); + // Stop the needle just inside the label ring. The labels keep their font + // size as the rose shrinks, so a fixed inset would run the needle into them. + const needle = Math.max(8, radius - LABEL_INSET - medium.lineHeight / 2 - 4); + const nx = cx + Math.cos(northAngle) * needle; + const ny = cy + Math.sin(northAngle) * needle; + const sx = cx - Math.cos(northAngle) * (needle - 8); + const sy = cy - Math.sin(northAngle) * (needle - 8); drawThickLine(image, cx, cy, nx, ny, 255); image.drawLine(cx, cy, sx, sy, 75); } diff --git a/app/ui/shell/geometry.ts b/app/ui/shell/geometry.ts index 67d4f9b8..0417312c 100644 --- a/app/ui/shell/geometry.ts +++ b/app/ui/shell/geometry.ts @@ -10,6 +10,16 @@ export const TOP_BAR_HEIGHT = 28; */ export const SIDEBAR_WIDTH = 64; +/** + * X of the display's true horizontal centre, in app-viewport coordinates. The + * sidebar pushes the viewport to the right, so UI the wearer physically aims + * with — a compass rose, a calibration crosshair — has to offset by it rather + * than use the viewport's own centre. + */ +export function screenCenterInViewportX(): number { + return Math.round(G2_LENS_WIDTH / 2) - SIDEBAR_WIDTH; +} + /** * On the color-key shell surface, pixel value 0 is transparent; 1 is the * darkest opaque shade (identical to 0 after 4bpp quantization). Shell