Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(agents): Fortnite-style minimap, compass and full map; people no longer walk through each other

rubenluetke10-beep2842fe4bfff6
diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeAgents.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeAgents.tsx
index 04abbd6eb7..c2ae6c54c6 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeAgents.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeAgents.tsx
@@ -25,10 +25,10 @@ import { findPath, isWalkable, type NavGrid } from "./officeNav";
import { AgentFollower } from "../companion/AgentFollower";
import { resolveCompanion } from "../companion/appearance";
import type { TrailPoint } from "../companion/trail";
-import { stepMover, turnToward, WALK_SPEED, type Mover } from "./officeMotion";
+import { stepMover, stepMoverAvoiding, turnToward, WALK_SPEED, type Mover } from "./officeMotion";
import { createRng, planFor, type ActivityKind, type Plan, type Pose, type SpotBook } from "./officeBehavior";
-import { useOfficeStore } from "./officeStore";
-import { agentPositions, seatedAtDesk } from "./walkerRegistry";
+import { player, useOfficeStore } from "./officeStore";
+import { agentPositions, bodiesExcept, floatingAgents, seatedAtDesk } from "./walkerRegistry";
/** The agent's symbol walks behind it as a little pet, about a fifth of its height. */
export const PET_SIZE_M = 0.26;
@@ -135,6 +135,7 @@ function Walker({ agent, desk, ctx, arrivesByElevator, awake, reduced, selected,
ctx.book.release(agent.agentId);
agentPositions.delete(agent.agentId);
seatedAtDesk.delete(agent.agentId);
+ floatingAgents.delete(agent.agentId);
}, [ctx.book, agent.agentId]);
const pet = useMemo(() => ({ ...resolveCompanion(agent.agentId, agent.figure?.companion), sizeM: PET_SIZE_M, followDistanceM: PET_FOLLOW_M }),
[agent.agentId, agent.figure?.companion]);
@@ -181,7 +182,10 @@ function Walker({ agent, desk, ctx, arrivesByElevator, awake, reduced, selected,
}
const p = plan.current!;
if (phase.current === "travel") {
- const { moved, arrived } = awake ? stepMover(m, WALK_SPEED, dt) : { moved: 0, arrived: false };
+ // Walkers steer around other people instead of through them; Gigi flies over everyone.
+ const { moved, arrived } = !awake ? { moved: 0, arrived: false }
+ : isGigi ? stepMover(m, WALK_SPEED, dt)
+ : stepMoverAvoiding(m, WALK_SPEED, dt, Array.from(bodiesExcept(agent.agentId, player)), (q) => isWalkable(ctx.grid, q));
drive.current.mode = "walk";
drive.current.speed = moved / Math.max(dt, 1e-3);
if (arrived) {
@@ -195,6 +199,7 @@ function Walker({ agent, desk, ctx, arrivesByElevator, awake, reduced, selected,
drive.current.speed = 0;
}
agentPositions.set(agent.agentId, { x: m.x, z: m.z });
+ if (isGigi) floatingAgents.add(agent.agentId);
if (phase.current === "dwell" && (p.kind === "work" || p.kind === "desk")) seatedAtDesk.add(agent.agentId);
else seatedAtDesk.delete(agent.agentId);
if (group.current) group.current.position.set(m.x, 0, m.z);
diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeCompass.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeCompass.tsx
new file mode 100644
index 0000000000..a1c45474b2
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeCompass.tsx
@@ -0,0 +1,158 @@
+/**
+ * The compass bar, game style: a strip at the top centre of the stage that
+ * shows where the camera faces (N/NE/E/… letters, a tick every 15°, a centre
+ * marker and the heading in degrees), plus small pips for the selected agent
+ * and the checkpoints at their bearing from the person's character.
+ *
+ * Drawn on a canvas at ≤ 20 Hz from the per-frame module state (`cameraView`,
+ * `player`, `agentPositions`); colours come from theme tokens, so light and
+ * dark mode both work. Pauses while the document is hidden.
+ */
+import { useCallback, useEffect, useRef } from "react";
+import { useT } from "@/i18n";
+import type { OfficeLayout } from "./officeLayout";
+import { cameraView, player } from "./officeStore";
+import { agentPositions } from "./walkerRegistry";
+import { MAP_PAINT, bearingOf, compassPosition, compassTicks, relativeBearing, yawToBearing, type CompassPoint } from "./minimap";
+import { agentColour, context2d, tokenColour, useElementSize, usePixelRatio, useThemeVersion, useThrottledFrames, type OfficeMapAgent } from "./mapHooks";
+
+export interface OfficeCompassProps {
+ layout: OfficeLayout;
+ agents: ReadonlyMap<string, OfficeMapAgent>;
+ selectedId: string | null;
+}
+
+/** Degrees visible across the bar. */
+const SPAN_DEG = 150;
+const FRAME_MS = 50;
+
+interface CompassColours { ink: string; muted: string; tick: string; marker: string; rim: string }
+
+export function OfficeCompass({ layout, agents, selectedId }: OfficeCompassProps) {
+ const t = useT();
+ const rootRef = useRef<HTMLDivElement>(null);
+ const canvasRef = useRef<HTMLCanvasElement>(null);
+ const readoutRef = useRef<HTMLSpanElement>(null);
+ const coloursRef = useRef<CompassColours | null>(null);
+ const size = useElementSize(canvasRef);
+ const dpr = usePixelRatio();
+ const themeVersion = useThemeVersion();
+
+ const letters: Record<CompassPoint, string> = {
+ n: t("society.office.compass_n"), ne: t("society.office.compass_ne"), e: t("society.office.compass_e"),
+ se: t("society.office.compass_se"), s: t("society.office.compass_s"), sw: t("society.office.compass_sw"),
+ w: t("society.office.compass_w"), nw: t("society.office.compass_nw"),
+ };
+
+ const live = useRef({ layout, agents, selectedId, size, letters });
+ live.current = { layout, agents, selectedId, size, letters };
+
+ useEffect(() => {
+ const root = rootRef.current;
+ const style = root ? getComputedStyle(root) : null;
+ coloursRef.current = {
+ ink: tokenColour(style, "--popover-foreground", "#111827"),
+ muted: tokenColour(style, "--muted-foreground", "#6b7280"),
+ tick: tokenColour(style, "--muted-foreground", "#6b7280", 0.7),
+ marker: MAP_PAINT.checkpoint,
+ rim: tokenColour(style, "--popover", "#ffffff"),
+ };
+ }, [themeVersion]);
+
+ const draw = useCallback(() => {
+ const canvas = canvasRef.current;
+ const ctx = context2d(canvas);
+ const colours = coloursRef.current;
+ const { layout: lay, agents: roster, selectedId: sel, size: box, letters: names } = live.current;
+ if (!canvas || !ctx || !colours || box.width <= 0 || box.height <= 0) return;
+ const w = box.width;
+ const h = box.height;
+ const ratio = canvas.width / w;
+ ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
+ ctx.clearRect(0, 0, w, h);
+ const heading = cameraView.ready ? yawToBearing(cameraView.yaw) : yawToBearing(player.heading);
+ if (readoutRef.current) readoutRef.current.textContent = `${Math.round(heading) % 360}°`;
+
+ ctx.textAlign = "center";
+ ctx.textBaseline = "middle";
+ for (const tick of compassTicks(heading, SPAN_DEG, 15)) {
+ const x = Math.round(tick.at * w) + 0.5;
+ if (tick.point) {
+ const main = tick.point.length === 1;
+ ctx.fillStyle = tick.point === "n" ? MAP_PAINT.checkpointDeep : colours.ink;
+ ctx.font = `${main ? 800 : 700} ${main ? 14 : 11}px system-ui, -apple-system, "Segoe UI", sans-serif`;
+ ctx.fillText(names[tick.point], x, h * 0.42);
+ ctx.fillStyle = colours.tick;
+ ctx.fillRect(x - 0.5, h - 7, 1, 5);
+ } else {
+ ctx.fillStyle = colours.tick;
+ ctx.fillRect(x - 0.5, h - 6, 1, 4);
+ ctx.fillStyle = colours.muted;
+ ctx.font = `600 9px system-ui, -apple-system, "Segoe UI", sans-serif`;
+ ctx.fillText(String(Math.round(tick.deg)), x, h * 0.42);
+ }
+ }
+
+ // Checkpoint pips: small gold diamonds on the bottom edge.
+ for (const cp of lay.checkpoints) {
+ const at = compassPosition(bearingOf(cp.x - player.x, cp.z - player.z), heading, SPAN_DEG);
+ if (at === null) continue;
+ const x = at * w;
+ ctx.beginPath();
+ ctx.moveTo(x, h - 9);
+ ctx.lineTo(x + 3.2, h - 5.5);
+ ctx.lineTo(x, h - 2);
+ ctx.lineTo(x - 3.2, h - 5.5);
+ ctx.closePath();
+ ctx.fillStyle = MAP_PAINT.checkpoint;
+ ctx.fill();
+ }
+
+ // The selected agent: a pip in its colour, pinned to the nearer end when out of view.
+ const agent = sel ? roster.get(sel) : undefined;
+ const pos = sel ? agentPositions.get(sel) : undefined;
+ if (agent && pos) {
+ const bearing = bearingOf(pos.x - player.x, pos.z - player.z);
+ const inView = compassPosition(bearing, heading, SPAN_DEG);
+ const at = inView ?? (relativeBearing(bearing, heading) < 0 ? 0.02 : 0.98);
+ const x = at * w;
+ ctx.globalAlpha = inView === null ? 0.6 : 1;
+ ctx.beginPath();
+ ctx.arc(x, h - 6, 4.2, 0, Math.PI * 2);
+ ctx.fillStyle = agentColour(agent);
+ ctx.fill();
+ ctx.strokeStyle = colours.rim;
+ ctx.lineWidth = 1.5;
+ ctx.stroke();
+ ctx.globalAlpha = 1;
+ }
+
+ // Centre marker: a gold notch at the top.
+ ctx.beginPath();
+ ctx.moveTo(w / 2 - 5, 0);
+ ctx.lineTo(w / 2 + 5, 0);
+ ctx.lineTo(w / 2, 6);
+ ctx.closePath();
+ ctx.fillStyle = colours.marker;
+ ctx.fill();
+ }, []);
+
+ // Size the backing store to the measured CSS size and pixel ratio.
+ useEffect(() => {
+ const canvas = canvasRef.current;
+ if (!canvas || size.width <= 0 || size.height <= 0) return;
+ canvas.width = Math.round(size.width * dpr);
+ canvas.height = Math.round(size.height * dpr);
+ draw();
+ }, [size, dpr, themeVersion, draw]);
+
+ useThrottledFrames(draw, FRAME_MS, size.width > 0);
+
+ return (
+ <div ref={rootRef} className="office-hud office-compass" data-office-ui role="img"
+ aria-label={t("society.office.compass_label")}>
+ <canvas ref={canvasRef} className="office-compass-canvas" aria-hidden />
+ <span ref={readoutRef} className="office-compass-readout" aria-hidden />
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeFullMap.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeFullMap.tsx
new file mode 100644
index 0000000000..60e227e034
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeFullMap.tsx
@@ -0,0 +1,302 @@
+/**
+ * The full office map, game style: "M" (or the minimap's Map button) opens a
+ * dialog over most of the stage with the whole floor fitted north-up, a light
+ * lettered grid (columns A–H, rows 1–N), room and checkpoint names, every
+ * agent with its name, and the person's arrow. A click anywhere sets a
+ * waypoint (the character walks there) and closes the map; Escape or M closes.
+ *
+ * The painted floor, grid and labels are drawn once per size/layout/theme into
+ * an offscreen canvas; the agents and the arrow repaint at ≤ 20 Hz while open.
+ * The chrome (header, grid letters, readout) uses theme tokens.
+ */
+import { useCallback, useEffect, useId, useMemo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type MouseEvent as ReactMouseEvent, type PointerEvent as ReactPointerEvent } from "react";
+import { X } from "lucide-react";
+import { useReducedMotion } from "framer-motion";
+import { useT } from "@/i18n";
+import type { CheckpointKind, OfficeLayout, Rect, RoomKind } from "./officeLayout";
+import { cameraView, player, useOfficeStore } from "./officeStore";
+import { agentPositions } from "./walkerRegistry";
+import { ownsKeyboard } from "./OfficePlayer";
+import {
+ MAP_PAINT, clampToRect, columnLabel, drawAgentToken, drawCheckpointBadge, drawFloorArt, drawMapLabel, drawPlayerArrow,
+ drawViewCone, fitTransform, gridLabel, mapGrid, mapToWorld, placeAt, worldToMap, type AgentToken, type MapPoint, type MapTransform,
+} from "./minimap";
+import {
+ agentColour, context2d, offscreenLayer, useElementSize, usePixelRatio, useThemeVersion, useThrottledFrames, type OfficeMapAgent,
+} from "./mapHooks";
+
+export interface OfficeFullMapProps {
+ open: boolean;
+ onOpen: () => void;
+ onClose: () => void;
+ layout: OfficeLayout;
+ agents: ReadonlyMap<string, OfficeMapAgent>;
+ selectedId: string | null;
+}
+
+const FRAME_MS = 50;
+/** Room around the grid for the column letters and row numbers (CSS px). */
+const GRID_PAD = 30;
+const GRID_COLUMNS = 8;
+
+function typingIn(target: EventTarget | null): boolean {
+ if (!(target instanceof HTMLElement)) return false;
+ const tag = target.tagName;
+ return target.isContentEditable || tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT";
+}
+
+/** M toggles the map; Escape closes it before the office (or the view behind it) sees the key. */
+function useMapKeys(open: boolean, onOpen: () => void, onClose: () => void): void {
+ const live = useRef({ open, onOpen, onClose });
+ live.current = { open, onOpen, onClose };
+ useEffect(() => {
+ const onKey = (event: KeyboardEvent) => {
+ if (event.ctrlKey || event.metaKey || event.altKey) return;
+ const { open: isOpen, onOpen: show, onClose: hide } = live.current;
+ if (isOpen) {
+ if (event.key === "Escape" || (event.code === "KeyM" && !typingIn(event.target))) {
+ event.preventDefault();
+ event.stopPropagation();
+ hide();
+ }
+ return;
+ }
+ if (event.code !== "KeyM" || event.repeat || ownsKeyboard(event.target)) return;
+ event.preventDefault();
+ show();
+ };
+ // Window capture runs before the office's and the workspace's document listeners.
+ window.addEventListener("keydown", onKey, true);
+ return () => window.removeEventListener("keydown", onKey, true);
+ }, []);
+}
+
+export function OfficeFullMap({ open, onOpen, onClose, layout, agents, selectedId }: OfficeFullMapProps) {
+ useMapKeys(open, onOpen, onClose);
+ if (!open) return null;
+ return <FullMapDialog onClose={onClose} layout={layout} agents={agents} selectedId={selectedId} />;
+}
+
+interface Readout { cell: string; place: string }
+
+function FullMapDialog({ onClose, layout, agents, selectedId }: Omit<OfficeFullMapProps, "open" | "onOpen">) {
+ const t = useT();
+ const reduced = useReducedMotion() ?? false;
+ const titleId = useId();
+ const hintId = useId();
+ const dialogRef = useRef<HTMLDivElement>(null);
+ const closeRef = useRef<HTMLButtonElement>(null);
+ const bodyRef = useRef<HTMLDivElement>(null);
+ const canvasRef = useRef<HTMLCanvasElement>(null);
+ const layerRef = useRef<HTMLCanvasElement | null>(null);
+ const [readout, setReadout] = useState<Readout | null>(null);
+ const size = useElementSize(bodyRef);
+ const dpr = usePixelRatio();
+ const themeVersion = useThemeVersion();
+
+ const grid = useMemo(() => mapGrid(layout.bounds, GRID_COLUMNS), [layout]);
+ const gridRect = useMemo<Rect>(() => ({
+ minX: grid.originX, maxX: grid.originX + grid.columns * grid.cell, minZ: grid.originZ, maxZ: grid.originZ + grid.rows * grid.cell,
+ }), [grid]);
+ const transform = useMemo<MapTransform | null>(
+ () => (size.width > GRID_PAD * 2 && size.height > GRID_PAD * 2 ? fitTransform(gridRect, size.width, size.height, GRID_PAD) : null),
+ [gridRect, size],
+ );
+
+ const checkpointLabels: Record<CheckpointKind, string> = {
+ create: t("society.office.cp_create"),
+ manage: t("society.office.cp_manage"),
+ team: t("society.office.cp_team"),
+ wardrobe: t("society.office.cp_wardrobe"),
+ lead: t("society.office.cp_lead"),
+ break: t("society.office.cp_break"),
+ };
+ const roomLabels: Record<RoomKind, string> = {
+ lead: t("society.office.room_lead"),
+ team: t("society.office.room_team"),
+ wardrobe: t("society.office.room_wardrobe"),
+ reception: t("society.office.room_reception"),
+ break: t("society.office.room_break"),
+ };
+ const openSpace = t("society.office.open_space");
+ const youLabel = t("society.office.minimap_you");
+ const labelKey = JSON.stringify([checkpointLabels, roomLabels, openSpace]);
+ const labels = useRef({ checkpointLabels, roomLabels, openSpace, youLabel });
+ labels.current = { checkpointLabels, roomLabels, openSpace, youLabel };
+
+ // Focus moves into the dialog and returns to where it was on close.
+ useEffect(() => {
+ const previous = document.activeElement instanceof HTMLElement ? document.activeElement : null;
+ closeRef.current?.focus();
+ return () => { if (previous && previous.isConnected) previous.focus(); };
+ }, []);
+
+ const live = useRef({ agents, selectedId, transform, reduced });
+ live.current = { agents, selectedId, transform, reduced };
+
+ const draw = useCallback((now: number) => {
+ const canvas = canvasRef.current;
+ const ctx = context2d(canvas);
+ const { agents: roster, selectedId: sel, transform: tr, reduced: still } = live.current;
+ if (!canvas || !ctx || !tr) return;
+ const ratio = canvas.width / tr.width;
+ ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
+ ctx.globalAlpha = 1;
+ ctx.fillStyle = MAP_PAINT.space;
+ ctx.fillRect(0, 0, tr.width, tr.height);
+ if (layerRef.current) ctx.drawImage(layerRef.current, 0, 0, tr.width, tr.height);
+
+ const me = worldToMap(tr, player);
+ if (cameraView.ready) drawViewCone(ctx, me, cameraView.yaw, cameraView.halfWidth, Math.max(40, tr.scale * 9));
+ const radius = Math.max(6, Math.min(9, tr.scale * 0.5));
+ const pulse = still ? null : (now % 1400) / 1400;
+ let selected: AgentToken | null = null;
+ const tokens: AgentToken[] = [];
+ for (const agent of roster.values()) {
+ const pos = agentPositions.get(agent.agentId);
+ if (!pos) continue;
+ const token: AgentToken = {
+ id: agent.agentId, name: agent.name, state: agent.state, colour: agentColour(agent), selected: agent.agentId === sel,
+ ...worldToMap(tr, pos),
+ };
+ if (token.selected) selected = token; else tokens.push(token);
+ }
+ if (selected) tokens.push(selected);
+ for (const token of tokens) {
+ drawAgentToken(ctx, token, radius, token.selected ? pulse : null);
+ drawMapLabel(ctx, token.name, token.x, token.y + radius * (token.selected ? 1.3 : 1) + 11, 10, 700);
+ }
+ drawPlayerArrow(ctx, me.x, me.y, player.heading, 11);
+ drawMapLabel(ctx, labels.current.youLabel, me.x, me.y + 18, 10, 800);
+ }, []);
+
+ // Static layer: painted floor, grid, room/department names and checkpoints.
+ useEffect(() => {
+ const canvas = canvasRef.current;
+ if (!canvas || !transform) return;
+ canvas.width = Math.round(transform.width * dpr);
+ canvas.height = Math.round(transform.height * dpr);
+ const off = offscreenLayer(transform.width, transform.height, dpr);
+ if (!off) {
+ layerRef.current = null;
+ return;
+ }
+ const ctx = off.ctx;
+ const nw = mapToWorld(transform, { x: 0, y: 0 });
+ const se = mapToWorld(transform, { x: transform.width, y: transform.height });
+ drawFloorArt(ctx, layout, transform, { minX: nw.x, maxX: se.x, minZ: nw.z, maxZ: se.z });
+
+ // The lettered grid: light lines over the painting, like a game's big map.
+ const g0 = worldToMap(transform, { x: gridRect.minX, z: gridRect.minZ });
+ const g1 = worldToMap(transform, { x: gridRect.maxX, z: gridRect.maxZ });
+ ctx.strokeStyle = "rgba(255,255,255,0.38)";
+ ctx.lineWidth = 1;
+ ctx.beginPath();
+ for (let c = 0; c <= grid.columns; c += 1) {
+ const x = Math.round(g0.x + c * grid.cell * transform.scale) + 0.5;
+ ctx.moveTo(x, g0.y);
+ ctx.lineTo(x, g1.y);
+ }
+ for (let r = 0; r <= grid.rows; r += 1) {
+ const y = Math.round(g0.y + r * grid.cell * transform.scale) + 0.5;
+ ctx.moveTo(g0.x, y);
+ ctx.lineTo(g1.x, y);
+ }
+ ctx.stroke();
+
+ const { roomLabels: rooms, checkpointLabels: cps, openSpace: spare } = labels.current;
+ const roomPx = Math.max(11, Math.min(15, transform.scale * 0.75));
+ for (const room of layout.rooms) {
+ const c = worldToMap(transform, { x: (room.minX + room.maxX) / 2, z: room.minZ + 1.1 });
+ drawMapLabel(ctx, rooms[room.kind].toLocaleUpperCase(), c.x, c.y, roomPx, 800);
+ }
+ for (const dept of layout.departments) {
+ const c = worldToMap(transform, { x: (dept.minX + dept.maxX) / 2, z: dept.minZ + 0.9 });
+ drawMapLabel(ctx, (dept.label || spare).toLocaleUpperCase(), c.x, c.y, roomPx * 0.85, 800);
+ }
+ const badge = Math.max(14, Math.min(22, transform.scale * 1.1));
+ for (const cp of layout.checkpoints) {
+ const m = worldToMap(transform, cp);
+ drawCheckpointBadge(ctx, m.x, m.y, badge, cp.id);
+ drawMapLabel(ctx, cps[cp.id], m.x, m.y - badge / 2 - 8, 10, 700);
+ }
+ layerRef.current = off.canvas;
+ draw(performance.now());
+ // labelKey stands in for the translated names (read through a ref), which are new objects every render.
+ }, [layout, transform, grid, gridRect, dpr, themeVersion, labelKey, draw]);
+
+ useThrottledFrames(draw, FRAME_MS, transform !== null);
+
+ const mapPoint = (event: { clientX: number; clientY: number }): MapPoint | null => {
+ const canvas = canvasRef.current;
+ if (!canvas || !transform) return null;
+ const rect = canvas.getBoundingClientRect();
+ if (rect.width <= 0 || rect.height <= 0) return null;
+ return { x: ((event.clientX - rect.left) / rect.width) * transform.width, y: ((event.clientY - rect.top) / rect.height) * transform.height };
+ };
+
+ const onClick = (event: ReactMouseEvent<HTMLCanvasElement>) => {
+ const at = mapPoint(event);
+ if (!at || !transform) return;
+ useOfficeStore.getState().requestWalk(clampToRect(mapToWorld(transform, at), layout.floor));
+ onClose();
+ };
+
+ const onPointerMove = (event: ReactPointerEvent<HTMLCanvasElement>) => {
+ const at = mapPoint(event);
+ if (!at || !transform) return;
+ const world = mapToWorld(transform, at);
+ const place = placeAt(layout, world);
+ const name = place?.kind === "checkpoint" ? checkpointLabels[place.id]
+ : place?.kind === "room" ? roomLabels[place.id]
+ : place?.kind === "department" ? place.label || openSpace : "";
+ const next = { cell: gridLabel(grid, world), place: name };
+ setReadout((prev) => (prev && prev.cell === next.cell && prev.place === next.place ? prev : next));
+ };
+
+ // Tab stays inside the dialog: the close button is its only control.
+ const onKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
+ if (event.key !== "Tab") return;
+ event.preventDefault();
+ closeRef.current?.focus();
+ };
+
+ const g0 = transform ? worldToMap(transform, { x: gridRect.minX, z: gridRect.minZ }) : null;
+ const cellPx = transform ? grid.cell * transform.scale : 0;
+
+ return (
+ <div className="office-fullmap-backdrop" data-office-ui onMouseDown={(event) => { if (event.target === event.currentTarget) onClose(); }}>
+ <div ref={dialogRef} className="office-card office-fullmap" role="dialog" aria-modal="true" data-state="open"
+ aria-labelledby={titleId} aria-describedby={hintId} onKeyDown={onKeyDown}>
+ <header className="office-fullmap-head">
+ <div className="office-fullmap-heading">
+ <h2 id={titleId}>{t("society.office.map_title")}</h2>
+ <span id={hintId}>{t("society.office.map_hint")}</span>
+ </div>
+ <span className="office-fullmap-readout" aria-live="off">
+ {readout ? (readout.place ? `${readout.cell} · ${readout.place}` : readout.cell) : ""}
+ </span>
+ <button ref={closeRef} type="button" className="office-icon-button office-fullmap-close" onClick={onClose}
+ aria-label={t("society.office.map_close")} title={t("society.office.map_close")} aria-keyshortcuts="Escape M">
+ <X aria-hidden size={16} />
+ </button>
+ </header>
+ <div ref={bodyRef} className="office-fullmap-body">
+ <canvas ref={canvasRef} className="office-fullmap-canvas" aria-label={t("society.office.map_aria")} role="img"
+ style={transform ? { width: transform.width, height: transform.height } : undefined}
+ onClick={onClick} onPointerMove={onPointerMove} onPointerLeave={() => setReadout(null)} />
+ {g0 && Array.from({ length: grid.columns }, (_, c) => (
+ <span key={`c${c}`} className="office-fullmap-axis" aria-hidden style={{ left: g0.x + (c + 0.5) * cellPx, top: g0.y - 14 }}>
+ {columnLabel(c)}
+ </span>
+ ))}
+ {g0 && Array.from({ length: grid.rows }, (_, r) => (
+ <span key={`r${r}`} className="office-fullmap-axis" aria-hidden style={{ left: g0.x - 14, top: g0.y + (r + 0.5) * cellPx }}>
+ {r + 1}
+ </span>
+ ))}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeMinimap.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeMinimap.tsx
index 3d64ad0bd6..b5914aecaf 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeMinimap.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeMinimap.tsx
@@ -1,225 +1,213 @@
/**
- * The office minimap: a north-up floor plan in the bottom-right corner.
+ * The office minimap, game style: a square card in the top-right corner that
+ * follows the person's character (player-centred, north-up, zoomable), with
+ * the camera's view as a soft cone, agents as portrait tokens with a status
+ * ring, off-screen agents as arrows on the card edge, and gold checkpoint icons.
*
- * The static floor is drawn once into an offscreen canvas and only redrawn
- * when the layout, the size, the pixel ratio or the theme changes. The moving
- * layer (agents, the person's character, the camera's view) is painted over
- * it at ~10 Hz from the per-frame module state (`agentPositions`, `player`),
- * never from React state, and pauses while collapsed or the document is hidden.
+ * The painted floor (with a margin of sky around it) is drawn once into an
+ * offscreen canvas and only redrawn when the layout, the zoom, the pixel ratio
+ * or the theme changes. Every frame (≤ 20 Hz, paused while the document is
+ * hidden) just blits that layer at the player's offset and paints the moving
+ * markers from the per-frame module state (`player`, `agentPositions`,
+ * `cameraView`), never from React state.
*
* Click focuses the camera on a spot (or selects the agent under the pointer),
- * double-click walks the character there.
+ * double-click walks the character there, the wheel zooms.
*/
import { useCallback, useEffect, useMemo, useRef, useState, type MouseEvent as ReactMouseEvent, type PointerEvent as ReactPointerEvent } from "react";
-import { ChevronDown, ChevronUp } from "lucide-react";
+import { Map as MapIcon, Minus, Plus } from "lucide-react";
+import { useReducedMotion } from "framer-motion";
import { useT } from "@/i18n";
-import type { CheckpointKind, OfficeLayout, RoomKind } from "./officeLayout";
-import { player, useOfficeStore } from "./officeStore";
+import type { CheckpointKind, OfficeLayout, Point, Rect, RoomKind } from "./officeLayout";
+import { cameraView, player, useOfficeStore } from "./officeStore";
import { agentPositions } from "./walkerRegistry";
import {
- agentAt, clampToRect, drawMinimapBase, drawMinimapDynamic, mapToWorld, minimapHeightFor, minimapTransform, placeAt,
- resolveMinimapColours, worldToMap, type MapPoint, type MinimapAgentDot, type MinimapAgentState, type MinimapCamera,
- type MinimapColours,
+ MAP_PAINT, ZOOM_DEFAULT_M, ZOOM_MAX_M, ZOOM_MIN_M, centredTransform, clampToEdge, clampToRect, clampZoom, drawAgentToken, drawCheckpoints,
+ drawEdgeArrow, drawFloorArt, drawPlayerArrow, drawViewCone, mapToWorld, pickNearest, placeAt, worldToMap, zoomStep,
+ type AgentToken, type MapPoint, type MapTransform,
} from "./minimap";
+import {
+ agentColour, context2d, offscreenLayer, usePixelRatio, useThemeVersion, useThrottledFrames, type OfficeMapAgent,
+} from "./mapHooks";
-export interface OfficeMinimapAgent { agentId: string; name: string; state: MinimapAgentState }
+export type OfficeMinimapAgent = OfficeMapAgent;
export interface OfficeMinimapProps {
layout: OfficeLayout;
- agents: ReadonlyMap<string, OfficeMinimapAgent>;
+ agents: ReadonlyMap<string, OfficeMapAgent>;
selectedId: string | null;
- /** Optional live camera view (read at ~10 Hz); omit to hide the view wedge. */
- camera?: () => MinimapCamera | null;
+ /** Opens the full map (the "Map (M)" button). */
+ onOpenMap: () => void;
}
-const MAP_WIDTH = 220;
-const PADDING = 6;
-const FRAME_MS = 100;
-const HIT_PX = 8;
-const STORAGE_KEY = "jarvis.office.minimap.collapsed";
+/** Card edge in CSS px (square). */
+export const MINIMAP_SIZE = 200;
+const FRAME_MS = 50;
+const HIT_PX = 10;
+const EDGE_INSET = 12;
+const TOKEN_R = 6.5;
+const CHECKPOINT_PX = 14;
+const STORAGE_KEY = "jarvis.office.minimap.zoom";
-function readCollapsed(): boolean {
+function readZoom(): number {
try {
- return window.localStorage.getItem(STORAGE_KEY) === "1";
+ const raw = window.localStorage.getItem(STORAGE_KEY);
+ return raw ? clampZoom(Number(raw)) : ZOOM_DEFAULT_M;
} catch {
- // Storage blocked (private mode, sandboxed WebView): the map just starts expanded.
- return false;
+ // Storage blocked (private mode, sandboxed WebView): start at the default zoom.
+ return ZOOM_DEFAULT_M;
}
}
-function writeCollapsed(collapsed: boolean): void {
+function writeZoom(metres: number): void {
try {
- window.localStorage.setItem(STORAGE_KEY, collapsed ? "1" : "0");
+ window.localStorage.setItem(STORAGE_KEY, String(metres));
} catch {
- // Storage blocked: the choice lasts for this session only, which is harmless.
+ // Storage blocked: the zoom lasts for this visit only, which is harmless.
}
}
-function pixelRatio(): number {
- return typeof window !== "undefined" && window.devicePixelRatio > 0 ? window.devicePixelRatio : 1;
-}
+interface Layer { canvas: HTMLCanvasElement; area: Rect; scale: number; cssW: number; cssH: number }
-/** Bumps whenever light/dark mode may have changed: OS preference, or the app's class/data-theme on <html>. */
-function useThemeVersion(): number {
- const [version, setVersion] = useState(0);
- useEffect(() => {
- const bump = () => setVersion((v) => v + 1);
- const media = typeof window.matchMedia === "function" ? window.matchMedia("(prefers-color-scheme: dark)") : null;
- media?.addEventListener?.("change", bump);
- const observer = typeof MutationObserver === "function" ? new MutationObserver(bump) : null;
- observer?.observe(document.documentElement, { attributes: true, attributeFilter: ["class", "data-theme"] });
- return () => {
- media?.removeEventListener?.("change", bump);
- observer?.disconnect();
- };
- }, []);
- return version;
-}
-
-/** The device pixel ratio, refreshed when the window moves to another screen or zooms. */
-function usePixelRatio(): number {
- const [dpr, setDpr] = useState(pixelRatio);
- useEffect(() => {
- const check = () => setDpr((prev) => (prev === pixelRatio() ? prev : pixelRatio()));
- window.addEventListener("resize", check);
- return () => window.removeEventListener("resize", check);
- }, []);
- return dpr;
-}
+interface Hit extends MapPoint { id: string; world: Point }
interface Tooltip { x: number; y: number; text: string }
-export function OfficeMinimap({ layout, agents, selectedId, camera }: OfficeMinimapProps) {
+export function OfficeMinimap({ layout, agents, selectedId, onOpenMap }: OfficeMinimapProps) {
const t = useT();
- const [collapsed, setCollapsed] = useState(readCollapsed);
+ const reduced = useReducedMotion() ?? false;
+ const [zoom, setZoom] = useState(readZoom);
const [tooltip, setTooltip] = useState<Tooltip | null>(null);
- const cardRef = useRef<HTMLDivElement>(null);
+ const mapRef = useRef<HTMLDivElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
- const baseRef = useRef<HTMLCanvasElement | null>(null);
- const coloursRef = useRef<MinimapColours | null>(null);
+ const layerRef = useRef<Layer | null>(null);
+ const hitsRef = useRef<Hit[]>([]);
+ const transformRef = useRef<MapTransform>(centredTransform(player, zoom, MINIMAP_SIZE, MINIMAP_SIZE));
const themeVersion = useThemeVersion();
const dpr = usePixelRatio();
- const height = useMemo(() => minimapHeightFor(layout.bounds, MAP_WIDTH, PADDING), [layout]);
- const transform = useMemo(() => minimapTransform(layout.bounds, MAP_WIDTH, height, PADDING), [layout, height]);
+ // The render loop reads these through a ref, so a roster refetch never restarts it.
+ const live = useRef({ agents, selectedId, zoom, reduced });
+ live.current = { agents, selectedId, zoom, reduced };
- // The render loop reads these through refs, so a roster refetch never restarts it.
- const live = useRef({ agents, selectedId, camera, transform });
- live.current = { agents, selectedId, camera, transform };
+ const draw = useCallback((now: number) => {
+ const canvas = canvasRef.current;
+ const ctx = context2d(canvas);
+ if (!canvas || !ctx) return;
+ const { agents: roster, selectedId: sel, zoom: metres, reduced: still } = live.current;
+ const size = MINIMAP_SIZE;
+ const tr = centredTransform(player, metres, size, size);
+ transformRef.current = tr;
+ const ratio = canvas.width / size;
+ ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
+ ctx.globalAlpha = 1;
+ ctx.fillStyle = MAP_PAINT.space;
+ ctx.fillRect(0, 0, size, size);
+ const layer = layerRef.current;
+ if (layer) {
+ const origin = worldToMap(tr, { x: layer.area.minX, z: layer.area.minZ });
+ ctx.drawImage(layer.canvas, origin.x, origin.y, layer.cssW, layer.cssH);
+ }
+ const centre = worldToMap(tr, player);
+ if (cameraView.ready) drawViewCone(ctx, centre, cameraView.yaw, cameraView.halfWidth, size * 0.5);
- const dots = useCallback((): MinimapAgentDot[] => {
- const out: MinimapAgentDot[] = [];
- const { agents: roster, selectedId: sel } = live.current;
+ const hits: Hit[] = [];
+ const pulse = still ? null : (now % 1400) / 1400;
+ let selected: { token: AgentToken; edge: ReturnType<typeof clampToEdge> } | null = null;
for (const agent of roster.values()) {
const pos = agentPositions.get(agent.agentId);
if (!pos) continue;
- out.push({ id: agent.agentId, x: pos.x, z: pos.z, state: agent.state, selected: agent.agentId === sel });
+ const token: AgentToken = {
+ id: agent.agentId, name: agent.name, state: agent.state, colour: agentColour(agent), selected: agent.agentId === sel,
+ ...worldToMap(tr, pos),
+ };
+ const edge = clampToEdge(token, size, size, EDGE_INSET);
+ hits.push({ id: token.id, x: edge.x, y: edge.y, world: { x: pos.x, z: pos.z } });
+ if (token.selected) { selected = { token, edge }; continue; }
+ if (edge.clamped) drawEdgeArrow(ctx, edge.x, edge.y, edge.angle, token);
+ else drawAgentToken(ctx, token, TOKEN_R, null);
+ }
+ // The selected agent last, so it sits on top of its neighbours.
+ if (selected) {
+ if (selected.edge.clamped) drawEdgeArrow(ctx, selected.edge.x, selected.edge.y, selected.edge.angle, selected.token);
+ else drawAgentToken(ctx, selected.token, TOKEN_R, pulse);
}
- return out;
+ hitsRef.current = hits;
+ drawPlayerArrow(ctx, centre.x, centre.y, player.heading, 9);
}, []);
- const draw = useCallback(() => {
- const canvas = canvasRef.current;
- const base = baseRef.current;
- const colours = coloursRef.current;
- const ctx = canvas?.getContext("2d");
- if (!canvas || !ctx || !colours) return;
- const { transform: tr, camera: cam } = live.current;
- ctx.setTransform(1, 0, 0, 1, 0, 0);
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- if (base) ctx.drawImage(base, 0, 0);
- const ratio = canvas.width / tr.width;
- ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
- drawMinimapDynamic(ctx, tr, {
- agents: dots(),
- player: { x: player.x, z: player.z, heading: player.heading },
- camera: cam ? cam() : null,
- colours,
- clear: false,
- });
- }, [dots]);
-
- // Static layer: layout, size, pixel ratio or theme changed (or the map was just expanded).
+ // Static layer: layout, zoom, pixel ratio or theme changed.
useEffect(() => {
- if (collapsed) return;
const canvas = canvasRef.current;
- const card = cardRef.current;
- if (!canvas || !card) return;
- canvas.width = Math.round(MAP_WIDTH * dpr);
- canvas.height = Math.round(height * dpr);
- const style = getComputedStyle(card);
- const colours = resolveMinimapColours((name) => style.getPropertyValue(name));
- coloursRef.current = colours;
- const base = document.createElement("canvas");
- base.width = canvas.width;
- base.height = canvas.height;
- const ctx = base.getContext("2d");
- if (!ctx) {
- // No 2D canvas (headless test DOM): the card still renders, just without a picture.
- baseRef.current = null;
+ if (!canvas) return;
+ canvas.width = Math.round(MINIMAP_SIZE * dpr);
+ canvas.height = Math.round(MINIMAP_SIZE * dpr);
+ const scale = MINIMAP_SIZE / zoom;
+ // Enough sky around the floor that the card is never empty at the railing.
+ const margin = zoom / 2 + 2;
+ const b = layout.bounds;
+ const area: Rect = { minX: b.minX - margin, maxX: b.maxX + margin, minZ: b.minZ - margin, maxZ: b.maxZ + margin };
+ const cssW = (area.maxX - area.minX) * scale;
+ const cssH = (area.maxZ - area.minZ) * scale;
+ const off = offscreenLayer(cssW, cssH, dpr);
+ if (!off) {
+ layerRef.current = null;
return;
}
- ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
- drawMinimapBase(ctx, layout, transform, colours);
- baseRef.current = base;
- draw();
- }, [collapsed, layout, transform, height, dpr, themeVersion, draw]);
+ const lt: MapTransform = { scale, offsetX: -area.minX * scale, offsetY: -area.minZ * scale, width: cssW, height: cssH };
+ drawFloorArt(off.ctx, layout, lt, area);
+ drawCheckpoints(off.ctx, layout, lt, CHECKPOINT_PX);
+ layerRef.current = { canvas: off.canvas, area, scale, cssW, cssH };
+ draw(performance.now());
+ }, [layout, zoom, dpr, themeVersion, draw]);
- // Moving layer at ~10 Hz; stops while collapsed or while the document is hidden.
- useEffect(() => {
- if (collapsed) return;
- let raf = 0;
- let last = 0;
- const tick = (now: number) => {
- raf = requestAnimationFrame(tick);
- if (now - last < FRAME_MS) return;
- last = now;
- draw();
- };
- const start = () => { if (!raf && !document.hidden) raf = requestAnimationFrame(tick); };
- const stop = () => { cancelAnimationFrame(raf); raf = 0; };
- const onVisibility = () => (document.hidden ? stop() : start());
- document.addEventListener("visibilitychange", onVisibility);
- start();
- return () => {
- stop();
- document.removeEventListener("visibilitychange", onVisibility);
- };
- }, [collapsed, draw]);
+ useThrottledFrames(draw, FRAME_MS, true);
- const toggle = () => {
- setCollapsed((prev) => {
- writeCollapsed(!prev);
- return !prev;
+ const changeZoom = useCallback((direction: number) => {
+ setZoom((prev) => {
+ const next = zoomStep(prev, direction);
+ if (next !== prev) writeZoom(next);
+ return next;
});
- setTooltip(null);
- };
+ }, []);
+
+ // The wheel zooms the map instead of scrolling or zooming anything behind it.
+ useEffect(() => {
+ const el = mapRef.current;
+ if (!el) return;
+ const onWheel = (event: WheelEvent) => {
+ event.preventDefault();
+ if (event.deltaY !== 0) changeZoom(event.deltaY < 0 ? 1 : -1);
+ };
+ el.addEventListener("wheel", onWheel, { passive: false });
+ return () => el.removeEventListener("wheel", onWheel);
+ }, [changeZoom]);
const mapPoint = (event: { clientX: number; clientY: number }): MapPoint | null => {
const canvas = canvasRef.current;
if (!canvas) return null;
const rect = canvas.getBoundingClientRect();
if (rect.width <= 0 || rect.height <= 0) return null;
- return { x: ((event.clientX - rect.left) / rect.width) * MAP_WIDTH, y: ((event.clientY - rect.top) / rect.height) * height };
+ return { x: ((event.clientX - rect.left) / rect.width) * MINIMAP_SIZE, y: ((event.clientY - rect.top) / rect.height) * MINIMAP_SIZE };
};
const onClick = (event: ReactMouseEvent<HTMLCanvasElement>) => {
const at = mapPoint(event);
if (!at) return;
const store = useOfficeStore.getState();
- const hit = agentAt(transform, dots(), at, HIT_PX);
+ const hit = pickNearest(hitsRef.current, at, HIT_PX);
if (hit) {
store.select({ kind: "agent", id: hit.id });
- store.focusOn({ x: hit.x, z: hit.z });
+ store.focusOn(hit.world);
return;
}
- store.focusOn(clampToRect(mapToWorld(transform, at), layout.floor));
+ store.focusOn(clampToRect(mapToWorld(transformRef.current, at), layout.floor));
};
const onDoubleClick = (event: ReactMouseEvent<HTMLCanvasElement>) => {
const at = mapPoint(event);
if (!at) return;
- useOfficeStore.getState().requestWalk(clampToRect(mapToWorld(transform, at), layout.floor));
+ useOfficeStore.getState().requestWalk(clampToRect(mapToWorld(transformRef.current, at), layout.floor));
};
const checkpointLabels: Record<CheckpointKind, string> = {
@@ -244,19 +232,16 @@ export function OfficeMinimap({ layout, agents, selectedId, camera }: OfficeMini
const at = mapPoint(event);
if (!at) return;
let text: string | null = null;
- const hit = agentAt(transform, dots(), at, HIT_PX);
+ const hit = pickNearest(hitsRef.current, at, HIT_PX);
if (hit) {
text = agents.get(hit.id)?.name ?? null;
+ } else if ((at.x - MINIMAP_SIZE / 2) ** 2 + (at.y - MINIMAP_SIZE / 2) ** 2 <= HIT_PX * HIT_PX) {
+ text = youLabel;
} else {
- const me = worldToMap(transform, player);
- if ((me.x - at.x) ** 2 + (me.y - at.y) ** 2 <= HIT_PX * HIT_PX) {
- text = youLabel;
- } else {
- const place = placeAt(layout, mapToWorld(transform, at));
- if (place?.kind === "checkpoint") text = checkpointLabels[place.id];
- else if (place?.kind === "room") text = roomLabels[place.id];
- else if (place?.kind === "department") text = place.label || openSpace;
- }
+ const place = placeAt(layout, mapToWorld(transformRef.current, at));
+ if (place?.kind === "checkpoint") text = checkpointLabels[place.id];
+ else if (place?.kind === "room") text = roomLabels[place.id];
+ else if (place?.kind === "department") text = place.label || openSpace;
}
setTooltip((prev) => {
if (!text) return null;
@@ -265,35 +250,45 @@ export function OfficeMinimap({ layout, agents, selectedId, camera }: OfficeMini
});
};
- let working = 0;
- for (const agent of agents.values()) if (agent.state === "working") working += 1;
+ const working = useMemo(() => {
+ let n = 0;
+ for (const agent of agents.values()) if (agent.state === "working") n += 1;
+ return n;
+ }, [agents]);
const summary = t("society.office.minimap_aria").replace("{0}", String(agents.size)).replace("{1}", String(working));
- const title = t("society.office.minimap_title");
+ const zoomLabel = t("society.office.minimap_zoom").replace("{0}", String(Math.round(zoom)));
return (
- <div ref={cardRef} className="office-hud office-card office-minimap" data-office-ui data-collapsed={collapsed ? "true" : "false"}>
- <div className="office-minimap-head">
- <span className="office-minimap-title">{title}</span>
- <button type="button" className="office-icon-button office-minimap-toggle" onClick={toggle} aria-expanded={!collapsed}
- aria-label={collapsed ? t("society.office.minimap_expand") : t("society.office.minimap_collapse")}
- title={collapsed ? t("society.office.minimap_expand") : t("society.office.minimap_collapse")}>
- {collapsed ? <ChevronUp aria-hidden size={14} /> : <ChevronDown aria-hidden size={14} />}
+ <div className="office-hud office-minimap" data-office-ui role="group" aria-label={t("society.office.minimap_title")}>
+ <div ref={mapRef} className="office-minimap-map" style={{ width: MINIMAP_SIZE, height: MINIMAP_SIZE }}>
+ <canvas ref={canvasRef} className="office-minimap-canvas" role="img" aria-label={summary}
+ style={{ width: MINIMAP_SIZE, height: MINIMAP_SIZE }}
+ onClick={onClick} onDoubleClick={onDoubleClick} onPointerMove={onPointerMove} onPointerLeave={() => setTooltip(null)} />
+ <span className="office-minimap-north" aria-hidden>{t("society.office.compass_n")}</span>
+ {tooltip && (
+ // Flip to the pointer's left on the right half so the label never runs off the card.
+ <span className="office-minimap-tooltip" role="presentation" data-side={tooltip.x > MINIMAP_SIZE / 2 ? "left" : "right"}
+ style={{ left: tooltip.x > MINIMAP_SIZE / 2 ? tooltip.x - 10 : tooltip.x + 10, top: Math.max(tooltip.y - 8, 22) }}>
+ {tooltip.text}
+ </span>
+ )}
+ </div>
+ <div className="office-minimap-bar">
+ <button type="button" className="office-minimap-btn" onClick={() => changeZoom(-1)} disabled={zoom >= ZOOM_MAX_M}
+ aria-label={t("society.office.minimap_zoom_out")} title={t("society.office.minimap_zoom_out")}>
+ <Minus aria-hidden size={13} />
+ </button>
+ <span className="office-minimap-zoom" aria-live="polite">{zoomLabel}</span>
+ <button type="button" className="office-minimap-btn" onClick={() => changeZoom(1)} disabled={zoom <= ZOOM_MIN_M}
+ aria-label={t("society.office.minimap_zoom_in")} title={t("society.office.minimap_zoom_in")}>
+ <Plus aria-hidden size={13} />
+ </button>
+ <button type="button" className="office-minimap-btn office-minimap-open" onClick={onOpenMap}
+ aria-keyshortcuts="M" title={t("society.office.minimap_open_map_label")}>
+ <MapIcon aria-hidden size={13} />
+ <span>{t("society.office.minimap_open_map")}</span>
</button>
</div>
- {!collapsed && (
- <div className="office-minimap-map" style={{ width: MAP_WIDTH, height }}>
- <canvas ref={canvasRef} className="office-minimap-canvas" role="img" aria-label={summary}
- style={{ width: MAP_WIDTH, height }}
- onClick={onClick} onDoubleClick={onDoubleClick} onPointerMove={onPointerMove} onPointerLeave={() => setTooltip(null)} />
- {tooltip && (
- // Flip to the pointer's left on the right half so the label never runs off the card.
- <span className="office-minimap-tooltip" role="presentation" data-side={tooltip.x > MAP_WIDTH / 2 ? "left" : "right"}
- style={{ left: tooltip.x > MAP_WIDTH / 2 ? tooltip.x - 10 : tooltip.x + 10, top: Math.max(tooltip.y - 8, 4) }}>
- {tooltip.text}
- </span>
- )}
- </div>
- )}
</div>
);
}
diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficePlayer.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficePlayer.tsx
index 59266c6cbd..834474573a 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/OfficePlayer.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficePlayer.tsx
@@ -11,9 +11,9 @@ import type { FigureDrive } from "../figures/FigureRig";
import { ToyFigure } from "./ToyFigure";
import type { ToyLook } from "./toyFigureModel";
import { findPath, isWalkable, nearestWalkable, type NavGrid } from "./officeNav";
-import { stepMover, turnToward } from "./officeMotion";
+import { applySeparation, clearOfBodies, separation, stepMover, turnToward } from "./officeMotion";
import { player, sameSelection, useOfficeStore, type Selection } from "./officeStore";
-import { agentPositions } from "./walkerRegistry";
+import { agentPositions, bodiesExcept } from "./walkerRegistry";
import { OFFICE_FIGURE_HEIGHT_M } from "./OfficeAgents";
import type { OfficeLayout } from "./officeLayout";
@@ -39,6 +39,14 @@ export function ownsKeyboard(target: EventTarget | null): boolean {
return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || !!target.closest("[role='dialog']");
}
+/** Would stepping to `next` bring the character closer to any agent than it is now at `from`? */
+function closerToAnyone(next: { x: number; z: number }, from: { x: number; z: number }): boolean {
+ for (const p of bodiesExcept(null, null)) {
+ if (Math.hypot(next.x - p.x, next.z - p.z) < Math.hypot(from.x - p.x, from.z - p.z)) return true;
+ }
+ return false;
+}
+
/** Pressed movement keys, tracked on the window while the office is awake. */
function useMoveKeys(enabled: boolean, onInteract: () => void) {
const pressed = useRef(new Set<string>());
@@ -52,19 +60,18 @@ function useMoveKeys(enabled: boolean, onInteract: () => void) {
else if (event.code === "KeyE" && !event.repeat) { onInteract(); event.preventDefault(); }
};
const up = (event: KeyboardEvent) => { pressed.current.delete(event.code); run.current = event.shiftKey; };
- // A key held while the window loses focus or gets hidden never sees its
- // keyup; forget everything then, or the character walks on by itself.
+ // A key held while the window loses focus never sees its keyup; forget
+ // everything then, or the character walks on by itself. (Not on
+ // visibilitychange: the desktop WebView reports visible windows as hidden.)
const release = () => pressed.current.clear();
window.addEventListener("keydown", down);
window.addEventListener("keyup", up);
window.addEventListener("blur", release);
- document.addEventListener("visibilitychange", release);
return () => {
release();
window.removeEventListener("keydown", down);
window.removeEventListener("keyup", up);
window.removeEventListener("blur", release);
- document.removeEventListener("visibilitychange", release);
};
}, [enabled, onInteract]);
return { pressed, run };
@@ -132,15 +139,19 @@ export function OfficePlayer({ layout, grid, look, name, awake, reduced }: {
dx /= len; dz /= len;
const step = speed * dt;
const nx = player.x + dx * step, nz = player.z + dz * step;
- // Slide along walls: full move, else each axis alone.
- if (isWalkable(grid, { x: nx, z: nz })) { player.x = nx; player.z = nz; moved = step; }
- else if (isWalkable(grid, { x: nx, z: player.z })) { player.x = nx; moved = Math.abs(dx * step); }
- else if (isWalkable(grid, { x: player.x, z: nz })) { player.z = nz; moved = Math.abs(dz * step); }
+ // Slide along walls and around people: full move, else each axis alone.
+ // Moving away from someone you already touch is always allowed, so nobody gets stuck.
+ const free = (p: { x: number; z: number }) => isWalkable(grid, p)
+ && (clearOfBodies(p, bodiesExcept(null, null)) || !closerToAnyone(p, player));
+ if (free({ x: nx, z: nz })) { player.x = nx; player.z = nz; moved = step; }
+ else if (free({ x: nx, z: player.z })) { player.x = nx; moved = Math.abs(dx * step); }
+ else if (free({ x: player.x, z: nz })) { player.z = nz; moved = Math.abs(dz * step); }
player.heading = turnToward(player.heading, Math.atan2(dx, dz), 12 * dt);
if (!store.follow) store.setFollow(true);
} else if (player.path.length > 0) {
const result = stepMover(player, speed, dt);
moved = result.moved;
+ applySeparation(player, separation(player, player.heading, bodiesExcept(null, null)), dt, (q) => isWalkable(grid, q));
}
player.moving = moved > 0;
drive.current.mode = moved > 0 ? "walk" : "idle";
diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx
index 5db41a1f96..d92f2c73be 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx
@@ -21,7 +21,7 @@ import { CAMERA_FOV } from "./officeCamera";
import { ZOOM_SECONDS } from "./OfficeCameraRig";
import { useDeskChats } from "./useDeskChats";
import type { Point } from "./officeLayout";
-import { cameraView, player, useOfficeStore } from "./officeStore";
+import { player, useOfficeStore } from "./officeStore";
import { agentPositions, knownAgents, seatedAtDesk } from "./walkerRegistry";
import { loadProfile, playerLook, saveProfile, type PlayerProfile } from "./playerProfile";
import { AgentPanel, CheckpointPanel, type OfficeActions } from "./OfficePanels";
@@ -31,6 +31,8 @@ import "./office.css";
import "./officeHud.css";
import "./officeMinimap.css";
import { OfficeMinimap } from "./OfficeMinimap";
+import { OfficeCompass } from "./OfficeCompass";
+import { OfficeFullMap } from "./OfficeFullMap";
// Dev-only handles for runtime checks of walking and panels.
if (import.meta.env.DEV && typeof window !== "undefined") Object.assign(window, { __officeStore: useOfficeStore, __officePlayer: player, __officeAgents: agentPositions, __officeSeated: seatedAtDesk,
@@ -100,6 +102,7 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
const roster = useSocietyRoster();
useRosterRefresh(awake);
const [overview, setOverview] = useState(0);
+ const [mapOpen, setMapOpen] = useState(false);
const [profile, setProfile] = useState<PlayerProfile>(loadProfile);
const selection = useOfficeStore((s) => s.selection);
const nearby = useOfficeStore((s) => s.nearby);
@@ -244,8 +247,11 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
<kbd>E</kbd>{nearbyLabel}
</button>
)}
+ <OfficeCompass layout={layout} agents={agents} selectedId={selection?.kind === "agent" ? selection.id : null} />
<OfficeMinimap layout={layout} agents={agents} selectedId={selection?.kind === "agent" ? selection.id : null}
- camera={() => (cameraView.ready ? cameraView : null)} />
+ onOpenMap={() => setMapOpen(true)} />
+ <OfficeFullMap open={mapOpen} onOpen={() => setMapOpen(true)} onClose={() => setMapOpen(false)}
+ layout={layout} agents={agents} selectedId={selection?.kind === "agent" ? selection.id : null} />
<p className="office-hud office-help" data-office-ui>{t("society.office.help")}</p>
</section>
);
diff --git a/jarvis/ui/web/frontend/src/components/society/office/ToyFigure.tsx b/jarvis/ui/web/frontend/src/components/society/office/ToyFigure.tsx
index bb5446c933..65884c69c8 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/ToyFigure.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/ToyFigure.tsx
@@ -46,6 +46,8 @@ const GEO = {
smile: new TorusGeometry(0.042, 0.009, 6, 14, Math.PI),
spike: new ConeGeometry(0.065, 0.16, 6),
brim: new RoundedBoxGeometry(0.3, 0.022, 0.17, 2, 0.01),
+ /** A band of hair around the back and sides, from just above the equator down: the hair a hat leaves visible. */
+ hairBand: new SphereGeometry(1, 40, 14, Math.PI * 0.92, Math.PI * 1.16, Math.PI * 0.46, Math.PI * 0.3),
};
const materials = new Map<string, MeshStandardMaterial>();
@@ -139,11 +141,15 @@ function HairCap({ color, grow = 0, fringe = true }: { color: string; grow?: num
{/* Tilted back just enough to free the forehead; further and the crown shows skin. */}
<mesh geometry={GEO.dome} material={material} position={[0, HD.y + 0.01, -0.005]} rotation={[-0.5, 0, 0]}
scale={[HD.rx + 0.018 + grow, HD.ry + 0.03 + grow, HD.rz + 0.03 + grow]} castShadow />
+ {/* Hair reaches down the back of the head to the nape, not just over the crown. */}
+ <mesh geometry={GEO.hairBand} material={material} position={[0, HD.y - 0.005, -0.004]}
+ scale={[HD.rx + 0.009 + grow, HD.ry + 0.008 + grow, HD.rz + 0.012 + grow]} castShadow />
{fringe && FRINGE.map(([x, dy, rz], i) => {
const y = HD.y + dy;
return (
- <mesh key={i} geometry={GEO.sphere} material={material} position={[x, y, faceZ(x, y, -0.012)]}
- rotation={[0.35, 0, rz]} scale={[0.085, 0.05, 0.045]} castShadow />
+ // Sunk into the head and flat, so from the side the fringe hugs the forehead instead of jutting out.
+ <mesh key={i} geometry={GEO.sphere} material={material} position={[x, y, faceZ(x, y, 0.012)]}
+ rotation={[0.35, 0, rz]} scale={[0.085, 0.05, 0.036]} castShadow />
);
})}
</group>
@@ -172,6 +178,17 @@ const CURLS: Array<[number, number, number]> = (() => {
return out;
})();
+/**
+ * Hair under a hat: only the band below the hat's rim, and slightly smaller
+ * than the hat shell, so no strand can ever poke through the crown.
+ */
+function HairUnderHat({ color }: { color: string }) {
+ return (
+ <mesh geometry={GEO.hairBand} material={matte(color)} position={[0, HD.y - 0.005, -0.004]}
+ scale={[HD.rx + 0.016, HD.ry + 0.014, HD.rz + 0.016]} castShadow />
+ );
+}
+
function Hair({ style, look }: { style: HairStyle; look: ToyLook }) {
const hair = matte(look.hair);
switch (style) {
@@ -219,6 +236,7 @@ function Hair({ style, look }: { style: HairStyle; look: ToyLook }) {
const knit = matte(look.shirtAccent, 0.95);
return (
<group>
+ <HairUnderHat color={look.hair} />
<mesh geometry={GEO.dome} material={knit} position={[0, HD.y + 0.01, 0]} rotation={[-0.15, 0, 0]}
scale={[HD.rx + 0.025, HD.ry + 0.045, HD.rz + 0.028]} castShadow />
<mesh geometry={GEO.lowSphere} material={knit} position={[0, HD.y + HD.ry + 0.07, -0.03]} scale={0.06} castShadow />
@@ -232,8 +250,8 @@ function Hair({ style, look }: { style: HairStyle; look: ToyLook }) {
const cap = matte(look.shirtAccent, 0.7);
return (
<group>
- <HairCap color={look.hair} />
- {/* Clearly larger than the hair cap underneath: equal shells z-fight and the hair flickers through. */}
+ <HairUnderHat color={look.hair} />
+ {/* Clearly larger than the hair band underneath: equal shells z-fight and the hair flickers through. */}
<mesh geometry={GEO.dome} material={cap} position={[0, HD.y + 0.03, 0]} rotation={[-0.12, 0, 0]}
scale={[HD.rx + 0.045, HD.ry + 0.0, HD.rz + 0.05]} castShadow />
<mesh geometry={GEO.brim} material={cap} position={[0, HD.y + 0.07, HD.rz + 0.06]} rotation={[0.14, 0, 0]} castShadow />
diff --git a/jarvis/ui/web/frontend/src/components/society/office/mapHooks.ts b/jarvis/ui/web/frontend/src/components/society/office/mapHooks.ts
new file mode 100644
index 0000000000..241188e63e
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/office/mapHooks.ts
@@ -0,0 +1,141 @@
+/**
+ * Small hooks shared by the minimap, the compass bar and the full map:
+ * theme and pixel-ratio change signals, element size, and a throttled
+ * requestAnimationFrame loop.
+ */
+import { useEffect, useRef, useState, type RefObject } from "react";
+import type { MinimapAgentState } from "./minimap";
+
+/** What the maps need to know about an agent; `SocietyAgent` satisfies it. */
+export interface OfficeMapAgent {
+ agentId: string;
+ name: string;
+ state: MinimapAgentState;
+ palette?: { primary?: string } | null;
+}
+
+/** Token colour of an agent: its palette's primary colour, or a neutral slate. */
+export function agentColour(agent: OfficeMapAgent): string {
+ const primary = agent.palette?.primary?.trim();
+ return primary ? primary : "#7c8aa5";
+}
+
+function pixelRatio(): number {
+ return typeof window !== "undefined" && window.devicePixelRatio > 0 ? window.devicePixelRatio : 1;
+}
+
+/** Bumps whenever light/dark mode may have changed: OS preference, or the app's class/data-theme on <html>. */
+export function useThemeVersion(): number {
+ const [version, setVersion] = useState(0);
+ useEffect(() => {
+ const bump = () => setVersion((v) => v + 1);
+ const media = typeof window.matchMedia === "function" ? window.matchMedia("(prefers-color-scheme: dark)") : null;
+ media?.addEventListener?.("change", bump);
+ const observer = typeof MutationObserver === "function" ? new MutationObserver(bump) : null;
+ observer?.observe(document.documentElement, { attributes: true, attributeFilter: ["class", "data-theme", "style"] });
+ return () => {
+ media?.removeEventListener?.("change", bump);
+ observer?.disconnect();
+ };
+ }, []);
+ return version;
+}
+
+/** The device pixel ratio, refreshed when the window moves to another screen or zooms. */
+export function usePixelRatio(): number {
+ const [dpr, setDpr] = useState(pixelRatio);
+ useEffect(() => {
+ const check = () => setDpr((prev) => (prev === pixelRatio() ? prev : pixelRatio()));
+ window.addEventListener("resize", check);
+ return () => window.removeEventListener("resize", check);
+ }, []);
+ return dpr;
+}
+
+/** CSS size of an element, rounded to whole pixels; {0, 0} until measured. */
+export function useElementSize(ref: RefObject<HTMLElement>, enabled = true): { width: number; height: number } {
+ const [size, setSize] = useState({ width: 0, height: 0 });
+ useEffect(() => {
+ const el = ref.current;
+ if (!enabled || !el) return;
+ const measure = () => {
+ const rect = el.getBoundingClientRect();
+ const next = { width: Math.round(rect.width), height: Math.round(rect.height) };
+ setSize((prev) => (prev.width === next.width && prev.height === next.height ? prev : next));
+ };
+ measure();
+ if (typeof ResizeObserver !== "function") {
+ window.addEventListener("resize", measure);
+ return () => window.removeEventListener("resize", measure);
+ }
+ const observer = new ResizeObserver(measure);
+ observer.observe(el);
+ return () => observer.disconnect();
+ }, [ref, enabled]);
+ return size;
+}
+
+/**
+ * Calls `draw(now)` at most once per `frameMs` from requestAnimationFrame while
+ * `enabled`. The latest `draw` is read through a ref, so a re-render never
+ * restarts the loop.
+ *
+ * Deliberately NOT gated on `document.hidden`: the desktop WebView reports an
+ * on-screen window as hidden for minutes at a time (see useCanvasAwake), which
+ * froze the minimap and compass. requestAnimationFrame already stops by itself
+ * for a window that is really hidden.
+ */
+export function useThrottledFrames(draw: (now: number) => void, frameMs: number, enabled: boolean): void {
+ const drawRef = useRef(draw);
+ drawRef.current = draw;
+ useEffect(() => {
+ if (!enabled || typeof requestAnimationFrame !== "function") return;
+ let last = 0;
+ const tick = (now: number) => {
+ raf = requestAnimationFrame(tick);
+ if (now - last < frameMs) return;
+ last = now;
+ drawRef.current(now);
+ };
+ let raf = requestAnimationFrame(tick);
+ return () => cancelAnimationFrame(raf);
+ }, [frameMs, enabled]);
+}
+
+/** A theme token (raw "H S% L%") as a CSS colour, or the fallback when the token is missing. */
+export function tokenColour(style: CSSStyleDeclaration | null, name: string, fallback: string, alpha?: number): string {
+ const raw = style?.getPropertyValue(name).trim() ?? "";
+ if (!raw) return fallback;
+ return alpha === undefined ? `hsl(${raw})` : `hsl(${raw} / ${alpha})`;
+}
+
+/** An offscreen canvas of `cssW × cssH` CSS px at `ratio`, or null without a 2D canvas (headless test DOM). */
+export function offscreenLayer(cssW: number, cssH: number, ratio: number): { canvas: HTMLCanvasElement; ctx: CanvasRenderingContext2D; ratio: number } | null {
+ if (typeof document === "undefined" || cssW <= 0 || cssH <= 0) return null;
+ // Keep a layer under ~4k px per side even on very dense screens.
+ const k = Math.max(0.5, Math.min(ratio, 4096 / Math.max(cssW, cssH)));
+ const canvas = document.createElement("canvas");
+ canvas.width = Math.max(1, Math.round(cssW * k));
+ canvas.height = Math.max(1, Math.round(cssH * k));
+ let ctx: CanvasRenderingContext2D | null = null;
+ try {
+ ctx = canvas.getContext("2d");
+ } catch {
+ // jsdom without the canvas package throws "not implemented": no picture, the chrome still renders.
+ ctx = null;
+ }
+ if (!ctx) return null;
+ ctx.setTransform(k, 0, 0, k, 0, 0);
+ return { canvas, ctx, ratio: k };
+}
+
+/** The 2D context of a visible canvas, or null (headless test DOM). */
+export function context2d(canvas: HTMLCanvasElement | null): CanvasRenderingContext2D | null {
+ if (!canvas) return null;
+ try {
+ return canvas.getContext("2d");
+ } catch {
+ // jsdom without the canvas package: nothing to paint on.
+ return null;
+ }
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/office/minimap.test.ts b/jarvis/ui/web/frontend/src/components/society/office/minimap.test.ts
index 6e9976e959..65474a3c77 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/minimap.test.ts
+++ b/jarvis/ui/web/frontend/src/components/society/office/minimap.test.ts
@@ -1,8 +1,10 @@
import { describe, expect, it } from "vitest";
import { buildOfficeLayout, type OfficeAgentInput } from "./officeLayout";
import {
- agentAt, clampToRect, drawMinimapBase, drawMinimapDynamic, mapToWorld, minimapHeightFor, minimapTransform, placeAt,
- resolveMinimapColours, worldToMap,
+ MAP_PAINT, STATE_RING, ZOOM_DEFAULT_M, ZOOM_MAX_M, ZOOM_MIN_M, bearingOf, centredTransform, clampToEdge, clampToRect,
+ clampZoom, columnLabel, compassPosition, compassTicks, drawAgentToken, drawEdgeArrow, drawFloorArt, drawPlayerArrow,
+ fitTransform, gridLabel, initialOf, inkOn, mapGrid, mapToWorld, pickNearest, placeAt, relativeBearing, shade,
+ worldToMap, yawToBearing, zoomStep,
} from "./minimap";
const agent = (id: string, provider: string, extra: Partial<OfficeAgentInput> = {}): OfficeAgentInput => ({
@@ -16,6 +18,7 @@ function recorder(): { ctx: CanvasRenderingContext2D; log: string[] } {
const ctx = new Proxy(state, {
get(target, prop: string) {
if (prop in target) return target[prop];
+ if (prop === "createRadialGradient" || prop === "createLinearGradient") return undefined;
return (...args: unknown[]) => { log.push(`${prop}(${args.map((a) => (typeof a === "number" ? a.toFixed(1) : String(a))).join(",")})`); };
},
set(target, prop: string, value) {
@@ -27,33 +30,30 @@ function recorder(): { ctx: CanvasRenderingContext2D; log: string[] } {
return { ctx: ctx as unknown as CanvasRenderingContext2D, log };
}
-const colours = resolveMinimapColours((name) => ({ "--success": "142 70% 45%", "--warning": "32 95% 34%" } as Record<string, string>)[name] ?? "");
-
-describe("minimap transform", () => {
+describe("map transforms", () => {
const bounds = { minX: -10, maxX: 10, minZ: -20, maxZ: 20 };
- it("keeps the aspect and centres the floor inside the padding", () => {
- const t = minimapTransform(bounds, 220, 300, 10);
- // Height limits: (300 - 20) / 40 = 7 px/m; width would allow 10 px/m.
- expect(t.scale).toBeCloseTo(7);
+ it("fits a rect keeping the aspect and centring it inside the padding", () => {
+ const t = fitTransform(bounds, 220, 300, 10);
+ expect(t.scale).toBeCloseTo(7); // (300 - 20) / 40
const nw = worldToMap(t, { x: -10, z: -20 });
const se = worldToMap(t, { x: 10, z: 20 });
expect(nw.y).toBeCloseTo(10);
expect(se.y).toBeCloseTo(290);
- expect(nw.x + se.x).toBeCloseTo(220); // centred horizontally
- expect(se.x - nw.x).toBeCloseTo(140);
+ expect(nw.x + se.x).toBeCloseTo(220);
});
- it("is north-up: +x goes right and +z (south) goes down", () => {
- const t = minimapTransform(bounds, 200, 200);
- const origin = worldToMap(t, { x: 0, z: 0 });
- expect(worldToMap(t, { x: 1, z: 0 }).x).toBeGreaterThan(origin.x);
- expect(worldToMap(t, { x: 0, z: 1 }).y).toBeGreaterThan(origin.y);
- expect(origin).toEqual({ x: 100, y: 100 });
+ it("centres the player and shows the zoom's metres across the shorter side", () => {
+ const t = centredTransform({ x: 12, z: -4 }, 26, 200, 200);
+ expect(worldToMap(t, { x: 12, z: -4 })).toEqual({ x: 100, y: 100 });
+ expect(t.scale).toBeCloseTo(200 / 26);
+ // 13 m east of the player is the right edge; north (−z) is up.
+ expect(worldToMap(t, { x: 25, z: -4 }).x).toBeCloseTo(200);
+ expect(worldToMap(t, { x: 12, z: -5 }).y).toBeLessThan(100);
});
it("round-trips between world and map", () => {
- const t = minimapTransform(bounds, 220, 260, 6);
+ const t = centredTransform({ x: 3, z: 7 }, 40, 200, 160);
for (const p of [{ x: 3.5, z: -7.25 }, { x: -10, z: 20 }, { x: 0, z: 0 }]) {
const back = mapToWorld(t, worldToMap(t, p));
expect(back.x).toBeCloseTo(p.x);
@@ -61,29 +61,128 @@ describe("minimap transform", () => {
}
});
- it("sizes the map height by the floor aspect within limits", () => {
- expect(minimapHeightFor(bounds, 220, 10)).toBe(300); // natural 420 clamps down
- expect(minimapHeightFor({ minX: 0, maxX: 40, minZ: 0, maxZ: 30 }, 220, 10)).toBe(170);
- expect(minimapHeightFor({ minX: 0, maxX: 100, minZ: 0, maxZ: 1 }, 220, 10)).toBe(110);
- });
-
it("clamps a click on the railing onto the walkable floor", () => {
expect(clampToRect({ x: 50, z: -50 }, bounds)).toEqual({ x: 10, z: -20 });
});
+
+ it("zooms within 16–60 m", () => {
+ expect(clampZoom(5)).toBe(ZOOM_MIN_M);
+ expect(clampZoom(500)).toBe(ZOOM_MAX_M);
+ expect(clampZoom(Number.NaN)).toBe(ZOOM_DEFAULT_M);
+ expect(zoomStep(26, 1)).toBeLessThan(26);
+ expect(zoomStep(26, -1)).toBeGreaterThan(26);
+ expect(zoomStep(ZOOM_MIN_M, 1)).toBe(ZOOM_MIN_M);
+ expect(zoomStep(ZOOM_MAX_M, -1)).toBe(ZOOM_MAX_M);
+ });
+});
+
+describe("edge clamping of off-screen agents", () => {
+ it("leaves a point inside the inset area alone", () => {
+ const m = clampToEdge({ x: 120, y: 80 }, 200, 200, 12);
+ expect(m).toMatchObject({ x: 120, y: 80, clamped: false });
+ });
+
+ it("pulls a point far east onto the right edge, arrow pointing right", () => {
+ const m = clampToEdge({ x: 900, y: 100 }, 200, 200, 12);
+ expect(m.clamped).toBe(true);
+ expect(m.x).toBeCloseTo(188);
+ expect(m.y).toBeCloseTo(100);
+ expect(m.angle).toBeCloseTo(0);
+ });
+
+ it("keeps the direction for a diagonal point and hits the nearer edge", () => {
+ // Far south-west, steeper than 45°: the bottom edge is reached first.
+ const m = clampToEdge({ x: 100 - 300, y: 100 + 600 }, 200, 200, 10);
+ expect(m.clamped).toBe(true);
+ expect(m.y).toBeCloseTo(190);
+ expect(m.x).toBeCloseTo(100 - 45);
+ expect(m.angle).toBeCloseTo(Math.atan2(600, -300));
+ // Straight north: top edge, arrow pointing up.
+ const up = clampToEdge({ x: 100, y: -500 }, 200, 200, 10);
+ expect(up.y).toBeCloseTo(10);
+ expect(up.angle).toBeCloseTo(-Math.PI / 2);
+ });
+});
+
+describe("compass", () => {
+ it("measures bearings clockwise from north (−z)", () => {
+ expect(bearingOf(0, -1)).toBeCloseTo(0);
+ expect(bearingOf(1, 0)).toBeCloseTo(90);
+ expect(bearingOf(0, 1)).toBeCloseTo(180);
+ expect(bearingOf(-1, 0)).toBeCloseTo(270);
+ expect(bearingOf(-1, -1)).toBeCloseTo(315);
+ });
+
+ it("reads yaw 0 as facing south and yaw π as facing north", () => {
+ expect(yawToBearing(0)).toBeCloseTo(180);
+ expect(yawToBearing(Math.PI) % 360).toBeCloseTo(0);
+ expect(yawToBearing(Math.PI / 2)).toBeCloseTo(90);
+ });
+
+ it("wraps relative bearings around north", () => {
+ expect(relativeBearing(10, 350)).toBeCloseTo(20);
+ expect(relativeBearing(350, 10)).toBeCloseTo(-20);
+ expect(relativeBearing(180, 0)).toBeCloseTo(-180);
+ expect(relativeBearing(90, 90)).toBeCloseTo(0);
+ });
+
+ it("lays out ticks every 15° with the winds on the 45s, across north", () => {
+ const ticks = compassTicks(350, 90, 15);
+ expect(ticks.map((t) => t.deg)).toEqual([315, 330, 345, 0, 15, 30]);
+ expect(ticks.find((t) => t.deg === 0)?.point).toBe("n");
+ expect(ticks.find((t) => t.deg === 315)?.point).toBe("nw");
+ expect(ticks.find((t) => t.deg === 330)?.point).toBeUndefined();
+ const north = ticks.find((t) => t.deg === 0)!;
+ expect(north.at).toBeCloseTo(0.5 + 10 / 90);
+ for (const t of ticks) {
+ expect(t.at).toBeGreaterThanOrEqual(0);
+ expect(t.at).toBeLessThanOrEqual(1);
+ }
+ });
+
+ it("places pips by bearing and hides those outside the span", () => {
+ expect(compassPosition(0, 0, 150)).toBeCloseTo(0.5);
+ expect(compassPosition(5, 355, 150)).toBeCloseTo(0.5 + 10 / 150);
+ expect(compassPosition(180, 0, 150)).toBeNull();
+ });
});
-describe("minimap hit testing", () => {
- const t = minimapTransform({ minX: -10, maxX: 10, minZ: -10, maxZ: 10 }, 200, 200, 0); // 10 px/m
- const agents = [{ id: "a", x: 0, z: 0 }, { id: "b", x: 0.5, z: 0 }, { id: "c", x: 5, z: 5 }];
+describe("full-map grid", () => {
+ const bounds = { minX: -20, maxX: 20, minZ: -30, maxZ: 31 };
- it("picks the closest dot within the radius", () => {
- expect(agentAt(t, agents, { x: 104, y: 100 })?.id).toBe("b");
- expect(agentAt(t, agents, { x: 101, y: 101 })?.id).toBe("a");
- expect(agentAt(t, agents, { x: 150, y: 157 }, 8)?.id).toBe("c");
+ it("uses square cells: 8 lettered columns and as many rows as the depth needs", () => {
+ const grid = mapGrid(bounds, 8);
+ expect(grid.cell).toBeCloseTo(5);
+ expect(grid.columns).toBe(8);
+ expect(grid.rows).toBe(13); // 61 m / 5 m → 12.2 → 13
});
- it("returns null when nothing is within the radius", () => {
- expect(agentAt(t, agents, { x: 150, y: 170 }, 8)).toBeNull();
+ it("labels columns A… and rows 1…", () => {
+ expect([0, 1, 7, 25, 26, 27].map(columnLabel)).toEqual(["A", "B", "H", "Z", "AA", "AB"]);
+ const grid = mapGrid(bounds, 8);
+ expect(gridLabel(grid, { x: -19.9, z: -29.9 })).toBe("A1");
+ expect(gridLabel(grid, { x: 0.1, z: 0.1 })).toBe("E7");
+ expect(gridLabel(grid, { x: 19.99, z: 30.9 })).toBe("H13");
+ // Points off the grid clamp onto its edge cells.
+ expect(gridLabel(grid, { x: 999, z: -999 })).toBe("H1");
+ });
+});
+
+describe("hit testing", () => {
+ const items = [{ id: "a", x: 100, y: 100 }, { id: "b", x: 104, y: 100 }, { id: "c", x: 150, y: 150 }];
+
+ it("picks the closest marker within the radius", () => {
+ expect(pickNearest(items, { x: 103, y: 100 }, 10)?.id).toBe("b");
+ expect(pickNearest(items, { x: 101, y: 101 }, 10)?.id).toBe("a");
+ expect(pickNearest(items, { x: 150, y: 157 }, 8)?.id).toBe("c");
+ expect(pickNearest(items, { x: 150, y: 170 }, 8)).toBeNull();
+ });
+
+ it("hits an off-screen agent at its clamped edge position", () => {
+ const t = centredTransform({ x: 0, z: 0 }, 20, 200, 200);
+ const far = worldToMap(t, { x: 80, z: 0 });
+ const edge = clampToEdge(far, 200, 200, 12);
+ expect(pickNearest([{ id: "far", x: edge.x, y: edge.y }], { x: 186, y: 101 }, 10)?.id).toBe("far");
});
it("names the place under a point: checkpoint, then room, then department", () => {
@@ -98,58 +197,65 @@ describe("minimap hit testing", () => {
});
});
-describe("minimap drawing", () => {
- const layout = buildOfficeLayout([agent("a1", "codex"), agent("a2", "codex", { state: "working" }), agent("l", "", { tier: "lead" })]);
- const t = minimapTransform(layout.bounds, 220, minimapHeightFor(layout.bounds, 220));
+describe("colour helpers", () => {
+ it("shades hex colours and passes anything else through", () => {
+ expect(shade("#808080", -1)).toBe("#000000");
+ expect(shade("#808080", 1)).toBe("#ffffff");
+ expect(shade("#fff", -0.5)).toBe("#808080");
+ expect(shade("hsl(1 2% 3%)", -0.3)).toBe("hsl(1 2% 3%)");
+ });
- it("reads theme tokens as hsl() colours with fallbacks", () => {
- expect(colours.working).toBe("hsl(142 70% 45%)");
- expect(colours.floor).toMatch(/^#/);
- expect(colours.rooms.break).toMatch(/^#/);
+ it("picks readable ink and initials", () => {
+ expect(inkOn("#ffffff")).not.toBe("#ffffff");
+ expect(inkOn("#1b1f2a")).toBe("#ffffff");
+ expect(initialOf(" ada")).toBe("A");
+ expect(initialOf("")).toBe("?");
});
+});
- it("draws the floor, every wall segment and one hexagon per checkpoint", () => {
+describe("drawing", () => {
+ const layout = buildOfficeLayout([agent("a1", "codex"), agent("a2", "codex", { state: "working" }), agent("l", "", { tier: "lead" })]);
+
+ it("paints the floor art with every wall segment", () => {
const { ctx, log } = recorder();
- drawMinimapBase(ctx, layout, t, colours);
- expect(log[0]).toMatch(/^clearRect/);
- expect(log.filter((l) => l.startsWith("moveTo")).length).toBe(layout.walls.length + layout.checkpoints.length);
- expect(log.filter((l) => l.startsWith("closePath")).length).toBe(layout.checkpoints.length);
- expect(log).toContain(`fillStyle=${colours.checkpoint}`);
- expect(log).toContain(`fillStyle=${colours.rooms.lead}`);
+ const t = fitTransform(layout.bounds, 220, 300);
+ drawFloorArt(ctx, layout, t, layout.bounds);
+ expect(log[0]).toBe("globalAlpha=1");
+ expect(log).toContain(`fillStyle=${MAP_PAINT.space}`);
+ expect(log).toContain(`fillStyle=${MAP_PAINT.floor}`);
+ expect(log).toContain(`strokeStyle=${MAP_PAINT.wall}`);
+ // Walls are the only straight segments started with moveTo after the planks; at least one per wall.
+ expect(log.filter((l) => l.startsWith("moveTo")).length).toBeGreaterThanOrEqual(layout.walls.length);
expect(log[log.length - 1]).not.toMatch(/^globalAlpha=0/);
});
- it("colours agents by state, rings the selected one and draws the player", () => {
+ it("rings tokens by state, dashes the paused one and prints the initial", () => {
const { ctx, log } = recorder();
- drawMinimapDynamic(ctx, t, {
- agents: [
- { id: "w", x: 0, z: 0, state: "working", selected: false },
- { id: "q", x: 1, z: 0, state: "waiting", selected: true },
- { id: "i", x: 2, z: 0, state: "idle", selected: false },
- { id: "p", x: 3, z: 0, state: "paused", selected: false },
- ],
- player: { x: 0, z: 2, heading: Math.PI },
- camera: null,
- colours,
- });
- expect(log).toContain(`fillStyle=${colours.working}`);
- expect(log).toContain(`fillStyle=${colours.waiting}`);
- expect(log).toContain(`fillStyle=${colours.idle}`);
- expect(log).toContain(`strokeStyle=${colours.paused}`);
- expect(log).toContain(`strokeStyle=${colours.selected}`);
- expect(log).toContain(`fillStyle=${colours.player}`);
- expect(log).not.toContain("clip()");
- // Heading π looks north: the arrow tip lies above the player on the map.
- const p = worldToMap(t, { x: 0, z: 2 });
- const tip = log.filter((l) => l.startsWith("moveTo")).pop()!;
- const [, y] = tip.slice("moveTo(".length, -1).split(",").map(Number);
- expect(y).toBeLessThan(p.y);
+ const base = { x: 50, y: 50, colour: "#336699", selected: false };
+ drawAgentToken(ctx, { ...base, id: "w", name: "Wes", state: "working" }, 6, null);
+ drawAgentToken(ctx, { ...base, id: "q", name: "quinn", state: "waiting", selected: true }, 6, 0.5);
+ drawAgentToken(ctx, { ...base, id: "p", name: "Pia", state: "paused" }, 6, null);
+ expect(log).toContain(`strokeStyle=${STATE_RING.working}`);
+ expect(log).toContain(`strokeStyle=${STATE_RING.waiting}`);
+ expect(log.some((l) => l.startsWith("setLineDash(2,2"))).toBe(true);
+ expect(log.some((l) => l.startsWith("fillText(W,"))).toBe(true);
+ expect(log.some((l) => l.startsWith("fillText(Q,"))).toBe(true);
+ // The selected token gets a halo ring with a pulse-dependent alpha.
+ expect(log).toContain("strokeStyle=rgba(255,255,255,0.450)");
});
- it("draws the camera wedge clipped to the slab when a camera is given", () => {
+ it("points the player arrow and the edge arrow the right way", () => {
const { ctx, log } = recorder();
- drawMinimapDynamic(ctx, t, { agents: [], player: { x: 0, z: 0, heading: 0 }, camera: { x: 5, z: 5, yaw: -Math.PI * 0.75, halfWidth: 0.4 }, colours });
- expect(log).toContain("clip()");
- expect(log).toContain(`fillStyle=${colours.camera}`);
+ // Heading π looks north: the arrow tip lies above the player.
+ drawPlayerArrow(ctx, 100, 100, Math.PI, 9);
+ const tip = log.find((l) => l.startsWith("moveTo"))!;
+ const [, y] = tip.slice("moveTo(".length, -1).split(",").map(Number);
+ expect(y).toBeLessThan(100);
+
+ const edge = recorder();
+ drawEdgeArrow(edge.ctx, 188, 100, 0, { colour: "#336699", state: "idle", selected: false });
+ const edgeTip = edge.log.find((l) => l.startsWith("moveTo"))!;
+ const [ex] = edgeTip.slice("moveTo(".length, -1).split(",").map(Number);
+ expect(ex).toBeGreaterThan(188);
});
});
diff --git a/jarvis/ui/web/frontend/src/components/society/office/minimap.ts b/jarvis/ui/web/frontend/src/components/society/office/minimap.ts
index 2499534002..c93f74794a 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/minimap.ts
+++ b/jarvis/ui/web/frontend/src/components/society/office/minimap.ts
@@ -1,19 +1,24 @@
/**
- * The office minimap as pure drawing code: a north-up plan of the floor with
- * the agents, the person's character and (optionally) the camera's view.
+ * The office maps as pure math and drawing code: the player-centred minimap,
+ * the compass bar and the full map share one world → map transform and one
+ * painted art style (a game-style map: warm floor, coloured rooms with soft
+ * outlines, carpets, tiny desks, crisp walls, gold checkpoint icons).
*
- * Map space is CSS pixels on the minimap canvas: +x right (east), +y down
- * (south). The 3D camera looks from the south-east, but the map stays
- * north-up so it reads like a floor plan. Nothing here touches the DOM, so
- * the transform and hit-testing are unit-tested and the drawing takes any
- * 2D context (the component's offscreen base canvas, or a test recorder).
+ * Map space is CSS pixels on a canvas: +x right (east), +y down (south), so
+ * every map is north-up. World north is −z. Compass bearings are degrees
+ * clockwise from north (east = 90). Nothing here touches the DOM, so the
+ * transforms, clamping, bearings, grid labels and hit-testing are unit-tested
+ * and the drawing takes any 2D context (an offscreen layer or a test recorder).
*/
-import { DEPARTMENT_TINTS, ROOM_FLOOR_COLOURS, CHECKPOINT_GOLD } from "./officePalette";
-import { DESK_SIZE, allDesks, roomAt, type CheckpointKind, type OfficeLayout, type Point, type Rect, type RoomKind } from "./officeLayout";
+import { CHECKPOINT_GOLD, DEPARTMENT_TINTS, ROOM_FLOOR_COLOURS } from "./officePalette";
+import {
+ DESK_SIZE, FURNITURE_SIZE, allDesks, footprint, roomAt,
+ type CheckpointKind, type FurnitureKind, type OfficeLayout, type Point, type Rect, type RoomKind,
+} from "./officeLayout";
export type MinimapAgentState = "idle" | "working" | "waiting" | "paused";
-export interface MinimapTransform {
+export interface MapTransform {
/** Map pixels per metre. */
scale: number;
/** Map position of the world origin. */
@@ -21,56 +26,14 @@ export interface MinimapTransform {
offsetY: number;
width: number;
height: number;
- bounds: Rect;
}
export interface MapPoint { x: number; y: number }
-export interface MinimapColours {
- /** The slab outside the walkable floor (railing edge). */
- slab: string;
- floor: string;
- outline: string;
- wall: string;
- desk: string;
- /** Room fills per kind, drawn at `roomAlpha` over the floor. */
- rooms: Record<RoomKind, string>;
- roomAlpha: number;
- /** Department carpet tints, indexed by `Department.tint` (wraps). */
- carpets: readonly string[];
- carpetAlpha: number;
- checkpoint: string;
- checkpointRim: string;
- working: string;
- waiting: string;
- idle: string;
- paused: string;
- selected: string;
- player: string;
- playerRim: string;
- camera: string;
-}
-
-export interface MinimapAgentDot extends Point { id: string; state: MinimapAgentState; selected: boolean }
-
-/**
- * The camera's view on the floor: its ground position, the heading it looks
- * along (same convention as the player: direction = (sin yaw, cos yaw), so
- * 0 looks south) and the half-angle of the view in radians.
- */
-export interface MinimapCamera extends Point { yaw: number; halfWidth: number }
-
-export interface MinimapDynamic {
- agents: readonly MinimapAgentDot[];
- player: Point & { heading: number };
- camera: MinimapCamera | null;
- colours: MinimapColours;
- /** Clear the canvas first (default). Pass false to paint over a base already blitted into the same canvas. */
- clear?: boolean;
-}
+// ---------------------------------------------------------------- transforms
/** Fit `bounds` into a widthPx × heightPx map with `padding` on every side, keeping the aspect and centring. */
-export function minimapTransform(bounds: Rect, widthPx: number, heightPx: number, padding = 6): MinimapTransform {
+export function fitTransform(bounds: Rect, widthPx: number, heightPx: number, padding = 6): MapTransform {
const bw = Math.max(1e-6, bounds.maxX - bounds.minX);
const bh = Math.max(1e-6, bounds.maxZ - bounds.minZ);
const innerW = Math.max(1, widthPx - padding * 2);
@@ -78,22 +41,20 @@ export function minimapTransform(bounds: Rect, widthPx: number, heightPx: number
const scale = Math.min(innerW / bw, innerH / bh);
const offsetX = (widthPx - bw * scale) / 2 - bounds.minX * scale;
const offsetY = (heightPx - bh * scale) / 2 - bounds.minZ * scale;
- return { scale, offsetX, offsetY, width: widthPx, height: heightPx, bounds };
+ return { scale, offsetX, offsetY, width: widthPx, height: heightPx };
}
-/** Map height (CSS px) for a given width that keeps the floor's aspect, clamped to [minPx, maxPx]. */
-export function minimapHeightFor(bounds: Rect, widthPx: number, padding = 6, minPx = 110, maxPx = 300): number {
- const bw = Math.max(1e-6, bounds.maxX - bounds.minX);
- const bh = Math.max(1e-6, bounds.maxZ - bounds.minZ);
- const natural = (widthPx - padding * 2) * (bh / bw) + padding * 2;
- return Math.round(Math.min(maxPx, Math.max(minPx, natural)));
+/** A north-up map `metresAcross` wide (along its shorter side) with `centre` in the middle of the canvas. */
+export function centredTransform(centre: Point, metresAcross: number, widthPx: number, heightPx: number): MapTransform {
+ const scale = Math.min(widthPx, heightPx) / Math.max(1e-6, metresAcross);
+ return { scale, offsetX: widthPx / 2 - centre.x * scale, offsetY: heightPx / 2 - centre.z * scale, width: widthPx, height: heightPx };
}
-export function worldToMap(t: MinimapTransform, p: Point): MapPoint {
+export function worldToMap(t: MapTransform, p: Point): MapPoint {
return { x: t.offsetX + p.x * t.scale, y: t.offsetY + p.z * t.scale };
}
-export function mapToWorld(t: MinimapTransform, p: MapPoint): Point {
+export function mapToWorld(t: MapTransform, p: MapPoint): Point {
return { x: (p.x - t.offsetX) / t.scale, z: (p.y - t.offsetY) / t.scale };
}
@@ -102,14 +63,160 @@ export function clampToRect(p: Point, r: Rect): Point {
return { x: Math.min(r.maxX, Math.max(r.minX, p.x)), z: Math.min(r.maxZ, Math.max(r.minZ, p.z)) };
}
-/** The agent whose dot is closest to `at` (map px) within `radiusPx`, or null. */
-export function agentAt<T extends Point & { id: string }>(t: MinimapTransform, agents: readonly T[], at: MapPoint, radiusPx = 8): T | null {
+// ---------------------------------------------------------------------- zoom
+
+/** Minimap zoom: metres across the card. */
+export const ZOOM_MIN_M = 16;
+export const ZOOM_MAX_M = 60;
+export const ZOOM_DEFAULT_M = 26;
+
+export function clampZoom(metres: number): number {
+ if (!Number.isFinite(metres)) return ZOOM_DEFAULT_M;
+ return Math.min(ZOOM_MAX_M, Math.max(ZOOM_MIN_M, metres));
+}
+
+/** One zoom step: `direction` > 0 zooms in (fewer metres), < 0 zooms out. */
+export function zoomStep(metres: number, direction: number): number {
+ if (direction === 0) return clampZoom(metres);
+ return clampZoom(Math.round(metres * (direction > 0 ? 1 / 1.25 : 1.25)));
+}
+
+// ------------------------------------------------------------- edge clamping
+
+export interface EdgeMarker extends MapPoint {
+ /** True when the point lay outside the inset area and was pulled onto its edge. */
+ clamped: boolean;
+ /** Direction from the map centre to the real point, radians, canvas convention (0 = right, π/2 = down). */
+ angle: number;
+}
+
+/**
+ * Keep a marker inside a width × height map with `inset` px of margin. A point
+ * outside is pulled towards the centre onto the inset edge (like an off-screen
+ * teammate on a game minimap), keeping its direction.
+ */
+export function clampToEdge(p: MapPoint, width: number, height: number, inset: number): EdgeMarker {
+ const cx = width / 2;
+ const cy = height / 2;
+ const dx = p.x - cx;
+ const dy = p.y - cy;
+ const angle = Math.atan2(dy, dx);
+ const hw = Math.max(0, cx - inset);
+ const hh = Math.max(0, cy - inset);
+ if (Math.abs(dx) <= hw && Math.abs(dy) <= hh) return { x: p.x, y: p.y, clamped: false, angle };
+ const k = Math.min(Math.abs(dx) > 1e-9 ? hw / Math.abs(dx) : Infinity, Math.abs(dy) > 1e-9 ? hh / Math.abs(dy) : Infinity);
+ return { x: cx + dx * k, y: cy + dy * k, clamped: true, angle };
+}
+
+// ------------------------------------------------------------------- compass
+
+function wrap360(deg: number): number {
+ const d = deg % 360;
+ return d < 0 ? d + 360 : d;
+}
+
+/** Compass bearing (degrees clockwise from north, [0, 360)) of a world direction; north is −z. */
+export function bearingOf(dx: number, dz: number): number {
+ if (Math.abs(dx) < 1e-12 && Math.abs(dz) < 1e-12) return 0;
+ return wrap360((Math.atan2(dx, -dz) * 180) / Math.PI);
+}
+
+/** Bearing of a yaw/heading (direction = (sin yaw, cos yaw), so yaw 0 looks south = 180°). */
+export function yawToBearing(yaw: number): number {
+ return bearingOf(Math.sin(yaw), Math.cos(yaw));
+}
+
+/** Signed angle from `heading` to `bearing`, in [-180, 180): negative = to the left. */
+export function relativeBearing(bearing: number, heading: number): number {
+ return wrap360(bearing - heading + 180) - 180;
+}
+
+/** Compass point keys (8 winds) in bearing order; labels come from i18n. */
+export const COMPASS_POINTS = ["n", "ne", "e", "se", "s", "sw", "w", "nw"] as const;
+export type CompassPoint = (typeof COMPASS_POINTS)[number];
+
+export interface CompassTick {
+ /** Bearing of the tick, [0, 360). */
+ deg: number;
+ /** Horizontal position as a fraction of the bar width, 0 = left edge, 1 = right edge. */
+ at: number;
+ /** Set on the eight winds (every 45°). */
+ point?: CompassPoint;
+ major: boolean;
+}
+
+/** Ticks every `stepDeg` visible on a bar that spans `spanDeg` centred on `heading`. */
+export function compassTicks(heading: number, spanDeg: number, stepDeg = 15): CompassTick[] {
+ const out: CompassTick[] = [];
+ const half = spanDeg / 2;
+ const first = Math.ceil((heading - half) / stepDeg) * stepDeg;
+ for (let raw = first; raw <= heading + half + 1e-9; raw += stepDeg) {
+ const deg = wrap360(raw);
+ const rounded = Math.round(deg * 1000) / 1000;
+ const isWind = Math.abs(rounded % 45) < 1e-6;
+ out.push({
+ deg: rounded,
+ at: (raw - (heading - half)) / spanDeg,
+ point: isWind ? COMPASS_POINTS[Math.round(rounded / 45) % 8] : undefined,
+ major: isWind,
+ });
+ }
+ return out;
+}
+
+/** Where a bearing sits on the bar (fraction of the width), or null when it lies outside the span. */
+export function compassPosition(bearing: number, heading: number, spanDeg: number): number | null {
+ const rel = relativeBearing(bearing, heading);
+ if (Math.abs(rel) > spanDeg / 2) return null;
+ return 0.5 + rel / spanDeg;
+}
+
+// ---------------------------------------------------------------------- grid
+
+export interface MapGrid {
+ columns: number;
+ rows: number;
+ /** Cell edge in metres (square cells). */
+ cell: number;
+ originX: number;
+ originZ: number;
+}
+
+/** A square grid over `bounds`: `columns` letters across, as many numbered rows as the depth needs. */
+export function mapGrid(bounds: Rect, columns = 8): MapGrid {
+ const width = Math.max(1e-6, bounds.maxX - bounds.minX);
+ const depth = Math.max(1e-6, bounds.maxZ - bounds.minZ);
+ const cell = width / Math.max(1, columns);
+ return { columns: Math.max(1, columns), rows: Math.max(1, Math.ceil(depth / cell - 1e-6)), cell, originX: bounds.minX, originZ: bounds.minZ };
+}
+
+/** Column letters A, B, … Z, AA, AB, … */
+export function columnLabel(index: number): string {
+ let n = Math.max(0, Math.floor(index));
+ let out = "";
+ do {
+ out = String.fromCharCode(65 + (n % 26)) + out;
+ n = Math.floor(n / 26) - 1;
+ } while (n >= 0);
+ return out;
+}
+
+/** The grid cell of a world point, like "C4", clamped onto the grid. */
+export function gridLabel(grid: MapGrid, p: Point): string {
+ const col = Math.min(grid.columns - 1, Math.max(0, Math.floor((p.x - grid.originX) / grid.cell)));
+ const row = Math.min(grid.rows - 1, Math.max(0, Math.floor((p.z - grid.originZ) / grid.cell)));
+ return `${columnLabel(col)}${row + 1}`;
+}
+
+// --------------------------------------------------------------- hit testing
+
+/** The item whose map point is closest to `at` within `radiusPx`, or null. */
+export function pickNearest<T extends MapPoint>(items: readonly T[], at: MapPoint, radiusPx: number): T | null {
let best: T | null = null;
let bestD = radiusPx * radiusPx;
- for (const agent of agents) {
- const m = worldToMap(t, agent);
- const d = (m.x - at.x) ** 2 + (m.y - at.y) ** 2;
- if (d <= bestD) { best = agent; bestD = d; }
+ for (const item of items) {
+ const d = (item.x - at.x) ** 2 + (item.y - at.y) ** 2;
+ if (d <= bestD) { best = item; bestD = d; }
}
return best;
}
@@ -130,93 +237,272 @@ export function placeAt(layout: OfficeLayout, p: Point): MinimapPlace | null {
return dept ? { kind: "department", label: dept.label } : null;
}
-/** Theme colours for the map. `token(name)` returns a CSS custom property's raw value ("H S% L%"), or "". */
-export function resolveMinimapColours(token: (name: string) => string): MinimapColours {
- const hsl = (name: string, fallback: string, alpha?: number): string => {
- const raw = token(name).trim();
- if (!raw) return fallback;
- return alpha === undefined ? `hsl(${raw})` : `hsl(${raw} / ${alpha})`;
- };
- return {
- slab: hsl("--muted", "#e5e7eb"),
- floor: hsl("--card", "#ffffff"),
- outline: hsl("--border", "#d4d4d8"),
- wall: hsl("--foreground", "#171717", 0.7),
- desk: hsl("--muted-foreground", "#737373", 0.75),
- rooms: {
- lead: ROOM_FLOOR_COLOURS.lead.base,
- team: ROOM_FLOOR_COLOURS.team.base,
- wardrobe: ROOM_FLOOR_COLOURS.wardrobe.base,
- reception: ROOM_FLOOR_COLOURS.reception.base,
- break: ROOM_FLOOR_COLOURS.break.base,
- },
- roomAlpha: 0.45,
- carpets: DEPARTMENT_TINTS,
- carpetAlpha: 0.35,
- checkpoint: CHECKPOINT_GOLD.face,
- checkpointRim: CHECKPOINT_GOLD.faceDeep,
- working: hsl("--success", "#16a34a"),
- waiting: hsl("--warning", "#d97706"),
- idle: hsl("--muted-foreground", "#737373"),
- paused: hsl("--muted-foreground", "#737373"),
- selected: hsl("--accent", "#2563eb"),
- player: CHECKPOINT_GOLD.ring,
- playerRim: hsl("--background", "#ffffff"),
- camera: hsl("--accent", "#2563eb", 0.16),
- };
+// -------------------------------------------------------------------- colour
+
+function parseHex(hex: string): [number, number, number] | null {
+ const m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(hex.trim());
+ if (!m) return null;
+ const h = m[1].length === 3 ? m[1].split("").map((c) => c + c).join("") : m[1];
+ return [parseInt(h.slice(0, 2), 16), parseInt(h.slice(2, 4), 16), parseInt(h.slice(4, 6), 16)];
}
-function fillRect(ctx: CanvasRenderingContext2D, t: MinimapTransform, r: Rect): void {
- const a = worldToMap(t, { x: r.minX, z: r.minZ });
- ctx.fillRect(a.x, a.y, (r.maxX - r.minX) * t.scale, (r.maxZ - r.minZ) * t.scale);
+/** Lighten (amount > 0) or darken (< 0) a hex colour by mixing with white or black. Non-hex passes through. */
+export function shade(hex: string, amount: number): string {
+ const rgb = parseHex(hex);
+ if (!rgb) return hex;
+ const target = amount >= 0 ? 255 : 0;
+ const k = Math.min(1, Math.abs(amount));
+ const out = rgb.map((c) => Math.round(c + (target - c) * k));
+ return `#${out.map((c) => c.toString(16).padStart(2, "0")).join("")}`;
+}
+
+/** Dark or white ink for text on a hex background (white for anything that is not hex). */
+export function inkOn(hex: string): string {
+ const rgb = parseHex(hex);
+ if (!rgb) return "#ffffff";
+ const [r, g, b] = rgb.map((c) => {
+ const s = c / 255;
+ return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
+ });
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b > 0.45 ? "#1b1f2a" : "#ffffff";
}
-function hexagon(ctx: CanvasRenderingContext2D, cx: number, cy: number, r: number): void {
+/** First letter of a name for a portrait token ("?" when empty). */
+export function initialOf(name: string): string {
+ const ch = name.trim().charAt(0);
+ return ch ? ch.toLocaleUpperCase() : "?";
+}
+
+// ------------------------------------------------------------ painted palette
+
+/**
+ * The map art's own colours. Like the 3D diorama the painted map looks the
+ * same in light and dark mode; only the chrome around it reads theme tokens.
+ */
+export const MAP_PAINT = {
+ space: "#121833",
+ star: "#e8ecff",
+ slab: "#474d5c",
+ slabEdge: "#2c303b",
+ railing: "#c9ced6",
+ floor: "#e9d3ad",
+ plank: "#b98a5e",
+ deskTop: "#fbf3e2",
+ deskEdge: "#9c7b58",
+ monitor: "#2a2d35",
+ wall: "#2b2f3a",
+ glass: "#d9f0ff",
+ furniture: "#8d7a66",
+ plant: "#5fa35a",
+ rug: "#d8c8ae",
+ checkpoint: CHECKPOINT_GOLD.face,
+ checkpointDeep: CHECKPOINT_GOLD.faceDeep,
+ checkpointIcon: CHECKPOINT_GOLD.icon,
+ working: "#4ade80",
+ waiting: "#fbbf24",
+ idle: "#aab3c2",
+ paused: "#aab3c2",
+ tokenRim: "#1b1f2a",
+ player: "#ffd23f",
+ playerRim: "#1b1f2a",
+ label: "#ffffff",
+ labelHalo: "rgba(20,24,40,0.85)",
+} as const;
+
+const FURNITURE_PAINT: Partial<Record<FurnitureKind, string>> = {
+ couch: "#4a5366", coffeeTable: "#c89f74", meetingTable: "#c89f74", teamBoard: "#f4f4f0", receptionDesk: "#f2eee6",
+ kiosk: "#3a3f4b", lockers: "#5fa8a0", mirror: "#d6ecf8", coffeeBar: "#8a6240", waterCooler: "#6fb7ea", arcade: "#6a58b0",
+ beanbag: "#e27d60", bookshelf: "#8a6240", plant: MAP_PAINT.plant, rug: MAP_PAINT.rug, elevator: "#c9ced6",
+};
+
+export const STATE_RING: Record<MinimapAgentState, string> = {
+ working: MAP_PAINT.working, waiting: MAP_PAINT.waiting, idle: MAP_PAINT.idle, paused: MAP_PAINT.paused,
+};
+
+/** Checkpoint icon per checkpoint kind; the same pictures as the 3D tokens (CheckpointMarker). */
+export const CHECKPOINT_ICON_KEYS: Record<CheckpointKind, "plus" | "list" | "team" | "shirt" | "star" | "coffee"> = {
+ create: "plus", manage: "list", team: "team", wardrobe: "shirt", lead: "star", break: "coffee",
+};
+
+/** Stroke-only icons in a 24 × 24 box; kept in sync with CheckpointMarker's paths. */
+const ICON_PATHS: Record<(typeof CHECKPOINT_ICON_KEYS)[CheckpointKind], string> = {
+ plus: "M12 5v14M5 12h14",
+ list: "M9 6h11M9 12h11M9 18h11M4.5 6h.01M4.5 12h.01M4.5 18h.01",
+ team: "M9 11a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM3 20c0-3.3 2.7-5.5 6-5.5s6 2.2 6 5.5M16.5 11a2.5 2.5 0 1 0 0-5M18 14.5c2 .6 3.5 2.4 3.5 5",
+ shirt: "M8 3L3 6l2 4 2.5-1v12h9V9l2.5 1 2-4-5-3c-.5 1.5-2 2.5-4 2.5S8.5 4.5 8 3z",
+ star: "M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1-4.4-4.3 6.1-.9z",
+ coffee: "M4 9h12v5a5 5 0 0 1-5 5H9a5 5 0 0 1-5-5V9zM16 10h1.5a2.5 2.5 0 0 1 0 5H16M8 3.5c0 1 1 1 1 2M12 3.5c0 1 1 1 1 2",
+};
+
+// ------------------------------------------------------------------ drawing
+
+type Ctx = CanvasRenderingContext2D;
+
+function roundRectPath(ctx: Ctx, x: number, y: number, w: number, h: number, r: number): void {
+ const rr = Math.max(0, Math.min(r, w / 2, h / 2));
ctx.beginPath();
- for (let i = 0; i < 6; i += 1) {
- const a = (Math.PI / 3) * i;
- const x = cx + Math.cos(a) * r;
- const y = cy + Math.sin(a) * r;
- if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
- }
+ ctx.moveTo(x + rr, y);
+ ctx.lineTo(x + w - rr, y);
+ ctx.arcTo(x + w, y, x + w, y + rr, rr);
+ ctx.lineTo(x + w, y + h - rr);
+ ctx.arcTo(x + w, y + h, x + w - rr, y + h, rr);
+ ctx.lineTo(x + rr, y + h);
+ ctx.arcTo(x, y + h, x, y + h - rr, rr);
+ ctx.lineTo(x, y + rr);
+ ctx.arcTo(x, y, x + rr, y, rr);
ctx.closePath();
}
-/** The static floor: slab, floor, room fills, department carpets, desks, walls (with door gaps) and checkpoints. */
-export function drawMinimapBase(ctx: CanvasRenderingContext2D, layout: OfficeLayout, t: MinimapTransform, colours: MinimapColours): void {
- ctx.clearRect(0, 0, t.width, t.height);
+function rectPath(ctx: Ctx, t: MapTransform, r: Rect, radiusM = 0): { x: number; y: number; w: number; h: number } {
+ const a = worldToMap(t, { x: r.minX, z: r.minZ });
+ const w = (r.maxX - r.minX) * t.scale;
+ const h = (r.maxZ - r.minZ) * t.scale;
+ roundRectPath(ctx, a.x, a.y, w, h, radiusM * t.scale);
+ return { x: a.x, y: a.y, w, h };
+}
+
+/** Small deterministic pseudo-random sequence (stars must not flicker between rebuilds). */
+function seeded(seed: number): () => number {
+ let s = seed >>> 0;
+ return () => {
+ s = (s * 1664525 + 1013904223) >>> 0;
+ return s / 4294967296;
+ };
+}
+
+/**
+ * The painted floor: night sky with stars, slab and railing, warm planks,
+ * department carpets, rooms, furniture, desks and crisp walls. `area` is the
+ * world rectangle to cover (the layout bounds plus any margin the caller wants).
+ */
+export function drawFloorArt(ctx: Ctx, layout: OfficeLayout, t: MapTransform, area: Rect): void {
ctx.globalAlpha = 1;
- ctx.fillStyle = colours.slab;
- fillRect(ctx, t, layout.bounds);
- ctx.fillStyle = colours.floor;
- fillRect(ctx, t, layout.floor);
+ ctx.fillStyle = MAP_PAINT.space;
+ const sky = worldToMap(t, { x: area.minX, z: area.minZ });
+ ctx.fillRect(sky.x, sky.y, (area.maxX - area.minX) * t.scale, (area.maxZ - area.minZ) * t.scale);
- ctx.globalAlpha = colours.roomAlpha;
- for (const room of layout.rooms) {
- ctx.fillStyle = colours.rooms[room.kind];
- fillRect(ctx, t, room);
+ // Stars: about one per 14 m², deterministic per layout size.
+ const rand = seeded(Math.round((area.maxX - area.minX) * 131 + (area.maxZ - area.minZ) * 17));
+ const count = Math.min(900, Math.round(((area.maxX - area.minX) * (area.maxZ - area.minZ)) / 14));
+ ctx.fillStyle = MAP_PAINT.star;
+ for (let i = 0; i < count; i += 1) {
+ const p = worldToMap(t, { x: area.minX + rand() * (area.maxX - area.minX), z: area.minZ + rand() * (area.maxZ - area.minZ) });
+ ctx.globalAlpha = 0.25 + rand() * 0.55;
+ const r = 0.4 + rand() * 0.8;
+ ctx.fillRect(p.x - r / 2, p.y - r / 2, r, r);
}
- ctx.globalAlpha = colours.carpetAlpha;
+ ctx.globalAlpha = 1;
+
+ // Slab with a soft shadow, then the railing line and the warm plank floor.
+ ctx.save();
+ ctx.shadowColor = "rgba(0,0,0,0.45)";
+ ctx.shadowBlur = Math.max(4, t.scale * 0.8);
+ ctx.fillStyle = MAP_PAINT.slab;
+ rectPath(ctx, t, layout.bounds, 0.8);
+ ctx.fill();
+ ctx.restore();
+ ctx.strokeStyle = MAP_PAINT.slabEdge;
+ ctx.lineWidth = 1.5;
+ ctx.stroke();
+
+ ctx.fillStyle = MAP_PAINT.floor;
+ rectPath(ctx, t, layout.floor, 0.4);
+ ctx.fill();
+ ctx.strokeStyle = MAP_PAINT.railing;
+ ctx.lineWidth = 1;
+ ctx.stroke();
+
+ if (t.scale >= 4) {
+ // Faint plank seams, every 0.9 m, running east-west.
+ ctx.save();
+ rectPath(ctx, t, layout.floor, 0.4);
+ ctx.clip();
+ ctx.strokeStyle = MAP_PAINT.plank;
+ ctx.globalAlpha = 0.14;
+ ctx.lineWidth = 1;
+ ctx.beginPath();
+ const left = worldToMap(t, { x: layout.floor.minX, z: 0 }).x;
+ const right = worldToMap(t, { x: layout.floor.maxX, z: 0 }).x;
+ for (let z = layout.floor.minZ; z <= layout.floor.maxZ; z += 0.9) {
+ const y = Math.round(worldToMap(t, { x: 0, z }).y) + 0.5;
+ ctx.moveTo(left, y);
+ ctx.lineTo(right, y);
+ }
+ ctx.stroke();
+ ctx.restore();
+ ctx.globalAlpha = 1;
+ }
+
+ // Department carpets and rooms: painted areas with soft darker outlines.
+ ctx.lineWidth = Math.max(1, Math.min(2, t.scale * 0.12));
for (const dept of layout.departments) {
- ctx.fillStyle = colours.carpets[dept.tint % Math.max(1, colours.carpets.length)] ?? colours.slab;
- fillRect(ctx, t, dept);
+ const tint = DEPARTMENT_TINTS[dept.tint % DEPARTMENT_TINTS.length];
+ rectPath(ctx, t, dept, 0.5);
+ ctx.globalAlpha = 0.85;
+ ctx.fillStyle = tint;
+ ctx.fill();
+ ctx.globalAlpha = 1;
+ ctx.strokeStyle = shade(tint, -0.3);
+ ctx.stroke();
+ }
+ for (const room of layout.rooms) {
+ const base = ROOM_FLOOR_COLOURS[room.kind].base;
+ rectPath(ctx, t, room, room.walled ? 0.15 : 0.5);
+ ctx.globalAlpha = 0.92;
+ ctx.fillStyle = base;
+ ctx.fill();
+ ctx.globalAlpha = 1;
+ ctx.strokeStyle = shade(base, -0.32);
+ ctx.stroke();
}
- ctx.globalAlpha = 1;
- ctx.fillStyle = colours.desk;
- for (const desk of allDesks(layout)) {
- fillRect(ctx, t, { minX: desk.x - DESK_SIZE.w / 2, maxX: desk.x + DESK_SIZE.w / 2, minZ: desk.z - DESK_SIZE.d / 2, maxZ: desk.z + DESK_SIZE.d / 2 });
+ // Furniture: rugs first, then solid pieces; plants and beanbags are round.
+ for (const pass of ["rug", "solid"] as const) {
+ for (const item of layout.furniture) {
+ const isRug = item.kind === "rug";
+ if ((pass === "rug") !== isRug) continue;
+ const colour = FURNITURE_PAINT[item.kind] ?? MAP_PAINT.furniture;
+ const fp = footprint(item);
+ if (item.kind === "plant" || item.kind === "beanbag") {
+ const c = worldToMap(t, item);
+ ctx.beginPath();
+ ctx.arc(c.x, c.y, Math.max(1.2, (FURNITURE_SIZE[item.kind].w / 2) * t.scale * 0.85), 0, Math.PI * 2);
+ } else {
+ rectPath(ctx, t, fp, isRug ? 0.3 : 0.08);
+ }
+ ctx.fillStyle = colour;
+ ctx.fill();
+ if (!isRug) {
+ ctx.strokeStyle = shade(colour, -0.35);
+ ctx.lineWidth = 0.8;
+ ctx.stroke();
+ }
+ }
}
- ctx.strokeStyle = colours.outline;
- ctx.lineWidth = 1;
- const f = worldToMap(t, { x: layout.floor.minX, z: layout.floor.minZ });
- ctx.strokeRect(f.x + 0.5, f.y + 0.5, (layout.floor.maxX - layout.floor.minX) * t.scale - 1, (layout.floor.maxZ - layout.floor.minZ) * t.scale - 1);
+ // Desks: tiny light blocks with the monitor on the far side from the chair.
+ const deskW = DESK_SIZE.w * t.scale;
+ const deskD = DESK_SIZE.d * t.scale;
+ for (const desk of allDesks(layout)) {
+ const c = worldToMap(t, desk);
+ roundRectPath(ctx, c.x - deskW / 2, c.y - deskD / 2, deskW, deskD, Math.min(2, deskD * 0.2));
+ ctx.fillStyle = MAP_PAINT.deskTop;
+ ctx.fill();
+ ctx.strokeStyle = MAP_PAINT.deskEdge;
+ ctx.lineWidth = 0.8;
+ ctx.stroke();
+ if (t.scale >= 5) {
+ const mh = Math.max(1, deskD * 0.18);
+ // A north-facing agent looks at a monitor on the desk's north edge.
+ const my = desk.facing === "north" ? c.y - deskD / 2 + mh * 0.6 : c.y + deskD / 2 - mh * 1.6;
+ ctx.fillStyle = MAP_PAINT.monitor;
+ ctx.fillRect(c.x - deskW * 0.28, my, deskW * 0.56, mh);
+ }
+ }
- // Walls come pre-split around their doors, so the gaps are simply not drawn.
- ctx.strokeStyle = colours.wall;
- ctx.lineWidth = Math.max(1, Math.min(2, t.scale * 0.2));
- ctx.lineCap = "butt";
+ // Walls: crisp dark lines with a thin glass highlight; door gaps are simply not drawn.
+ const wallW = Math.max(1.5, Math.min(3.5, t.scale * 0.2));
+ ctx.lineCap = "round";
ctx.beginPath();
for (const w of layout.walls) {
const a = worldToMap(t, { x: w.x1, z: w.z1 });
@@ -224,91 +510,192 @@ export function drawMinimapBase(ctx: CanvasRenderingContext2D, layout: OfficeLay
ctx.moveTo(a.x, a.y);
ctx.lineTo(b.x, b.y);
}
+ ctx.strokeStyle = MAP_PAINT.wall;
+ ctx.lineWidth = wallW;
+ ctx.stroke();
+ ctx.strokeStyle = MAP_PAINT.glass;
+ ctx.globalAlpha = 0.55;
+ ctx.lineWidth = Math.max(0.5, wallW * 0.3);
ctx.stroke();
+ ctx.globalAlpha = 1;
+ ctx.lineCap = "butt";
+}
- const hexR = Math.max(3, Math.min(5, t.scale * 0.55));
- ctx.lineWidth = 1;
+/** A gold checkpoint badge (hexagon) with its white icon, `size` px across. */
+export function drawCheckpointBadge(ctx: Ctx, x: number, y: number, size: number, kind: CheckpointKind): void {
+ const r = size / 2;
+ ctx.beginPath();
+ for (let i = 0; i < 6; i += 1) {
+ const a = (Math.PI / 3) * i;
+ const px = x + Math.cos(a) * r;
+ const py = y + Math.sin(a) * r;
+ if (i === 0) ctx.moveTo(px, py); else ctx.lineTo(px, py);
+ }
+ ctx.closePath();
+ ctx.fillStyle = MAP_PAINT.checkpoint;
+ ctx.fill();
+ ctx.strokeStyle = MAP_PAINT.checkpointDeep;
+ ctx.lineWidth = 1.2;
+ ctx.stroke();
+ if (typeof Path2D === "undefined") return;
+ const path = new Path2D(ICON_PATHS[CHECKPOINT_ICON_KEYS[kind]]);
+ const k = (size * 0.62) / 24;
+ ctx.save();
+ ctx.translate(x - 12 * k, y - 12 * k);
+ ctx.scale(k, k);
+ ctx.lineCap = "round";
+ ctx.lineJoin = "round";
+ ctx.strokeStyle = MAP_PAINT.checkpointIcon;
+ ctx.lineWidth = 2.6;
+ ctx.stroke(path);
+ ctx.restore();
+}
+
+/** Every checkpoint of the layout as a badge. */
+export function drawCheckpoints(ctx: Ctx, layout: OfficeLayout, t: MapTransform, size: number): void {
for (const cp of layout.checkpoints) {
const m = worldToMap(t, cp);
- hexagon(ctx, m.x, m.y, hexR);
- ctx.fillStyle = colours.checkpoint;
- ctx.fill();
- ctx.strokeStyle = colours.checkpointRim;
- ctx.stroke();
+ drawCheckpointBadge(ctx, m.x, m.y, size, cp.id);
}
}
-/** Radius (map px) of an agent dot. */
-export const AGENT_DOT_PX = 3.2;
+/** The camera's view as a soft white cone from `origin`, fading out towards `reach` px. */
+export function drawViewCone(ctx: Ctx, origin: MapPoint, yaw: number, halfWidth: number, reach: number): void {
+ const half = Math.max(0.12, Math.min(Math.PI / 2 - 0.05, halfWidth));
+ // World heading (sin, cos) maps straight onto map (x, y): +x east → right, +z south → down.
+ const centre = Math.atan2(Math.cos(yaw), Math.sin(yaw));
+ ctx.save();
+ const grad = typeof ctx.createRadialGradient === "function" ? ctx.createRadialGradient(origin.x, origin.y, 0, origin.x, origin.y, reach) : null;
+ if (grad) {
+ grad.addColorStop(0, "rgba(255,255,255,0.55)");
+ grad.addColorStop(1, "rgba(255,255,255,0)");
+ ctx.fillStyle = grad;
+ } else {
+ ctx.fillStyle = "rgba(255,255,255,0.3)";
+ }
+ ctx.beginPath();
+ ctx.moveTo(origin.x, origin.y);
+ ctx.arc(origin.x, origin.y, reach, centre - half, centre + half);
+ ctx.closePath();
+ ctx.fill();
+ ctx.restore();
+}
-/** The moving layer: camera wedge (under everything), agent dots, the selection ring and the player's arrow. */
-export function drawMinimapDynamic(ctx: CanvasRenderingContext2D, t: MinimapTransform, scene: MinimapDynamic): void {
- const { colours } = scene;
- if (scene.clear !== false) ctx.clearRect(0, 0, t.width, t.height);
- ctx.globalAlpha = 1;
+/** The person: a bright arrow pointing along `heading` (same convention as the player body). */
+export function drawPlayerArrow(ctx: Ctx, x: number, y: number, heading: number, size = 9): void {
+ const dx = Math.sin(heading);
+ const dy = Math.cos(heading);
+ const len = size;
+ const wing = size * 0.68;
+ ctx.save();
+ ctx.shadowColor = "rgba(0,0,0,0.45)";
+ ctx.shadowBlur = 3;
+ ctx.beginPath();
+ ctx.moveTo(x + dx * len, y + dy * len);
+ ctx.lineTo(x - dx * len * 0.62 + dy * wing, y - dy * len * 0.62 - dx * wing);
+ ctx.lineTo(x - dx * len * 0.22, y - dy * len * 0.22);
+ ctx.lineTo(x - dx * len * 0.62 - dy * wing, y - dy * len * 0.62 + dx * wing);
+ ctx.closePath();
+ ctx.fillStyle = MAP_PAINT.player;
+ ctx.fill();
+ ctx.restore();
+ ctx.strokeStyle = MAP_PAINT.playerRim;
+ ctx.lineWidth = 1.4;
+ ctx.lineJoin = "round";
+ ctx.stroke();
+}
- if (scene.camera) {
- const c = scene.camera;
- const origin = worldToMap(t, c);
- const reach = Math.hypot(t.width, t.height) * 1.5;
- const half = Math.max(0.05, Math.min(Math.PI / 2 - 0.05, c.halfWidth));
- // World heading (sin, cos) maps onto map (x, y) directly: +x east → right, +z south → down.
- const edge = (angle: number): MapPoint => ({ x: origin.x + Math.sin(angle) * reach, y: origin.y + Math.cos(angle) * reach });
- const left = edge(c.yaw - half);
- const right = edge(c.yaw + half);
- ctx.save();
- const b = worldToMap(t, { x: t.bounds.minX, z: t.bounds.minZ });
- ctx.beginPath();
- ctx.rect(b.x, b.y, (t.bounds.maxX - t.bounds.minX) * t.scale, (t.bounds.maxZ - t.bounds.minZ) * t.scale);
- ctx.clip();
- ctx.beginPath();
- ctx.moveTo(origin.x, origin.y);
- ctx.lineTo(left.x, left.y);
- ctx.lineTo(right.x, right.y);
- ctx.closePath();
- ctx.fillStyle = colours.camera;
- ctx.fill();
- ctx.restore();
- }
+export interface AgentToken extends MapPoint {
+ id: string;
+ name: string;
+ state: MinimapAgentState;
+ /** The agent's palette colour (token fill). */
+ colour: string;
+ selected: boolean;
+}
- ctx.lineWidth = 1.5;
- let selected: MapPoint | null = null;
- for (const agent of scene.agents) {
- const m = worldToMap(t, agent);
- ctx.beginPath();
- ctx.arc(m.x, m.y, AGENT_DOT_PX, 0, Math.PI * 2);
- if (agent.state === "paused") {
- ctx.strokeStyle = colours.paused;
- ctx.stroke();
- } else {
- ctx.fillStyle = agent.state === "working" ? colours.working : agent.state === "waiting" ? colours.waiting : colours.idle;
- ctx.fill();
- }
- if (agent.selected) selected = m;
- }
- if (selected) {
+/**
+ * A round portrait-like token: the agent's initial on its palette colour
+ * inside a status ring (working green, waiting amber, idle grey, paused a
+ * hollow dashed ring). `pulse` in [0, 1) animates the selected agent's halo.
+ */
+export function drawAgentToken(ctx: Ctx, token: AgentToken, radius: number, pulse: number | null): void {
+ const { x, y } = token;
+ const r = token.selected ? radius * 1.3 : radius;
+ if (token.selected) {
+ const phase = pulse ?? 0.35;
ctx.beginPath();
- ctx.arc(selected.x, selected.y, AGENT_DOT_PX + 3, 0, Math.PI * 2);
- ctx.strokeStyle = colours.selected;
+ ctx.arc(x, y, r + 3 + phase * 6, 0, Math.PI * 2);
+ ctx.strokeStyle = `rgba(255,255,255,${(0.9 * (1 - phase)).toFixed(3)})`;
ctx.lineWidth = 2;
ctx.stroke();
}
+ // Dark rim for contrast on any floor colour.
+ ctx.beginPath();
+ ctx.arc(x, y, r + 2.6, 0, Math.PI * 2);
+ ctx.fillStyle = MAP_PAINT.tokenRim;
+ ctx.fill();
+ const ring = STATE_RING[token.state];
+ ctx.beginPath();
+ ctx.arc(x, y, r + 1.4, 0, Math.PI * 2);
+ if (token.state === "paused") {
+ ctx.setLineDash?.([2, 2]);
+ ctx.strokeStyle = ring;
+ ctx.lineWidth = 1.4;
+ ctx.stroke();
+ ctx.setLineDash?.([]);
+ } else {
+ ctx.strokeStyle = ring;
+ ctx.lineWidth = 2.2;
+ ctx.stroke();
+ }
+ ctx.beginPath();
+ ctx.arc(x, y, r - 0.2, 0, Math.PI * 2);
+ ctx.globalAlpha = token.state === "paused" ? 0.55 : 1;
+ ctx.fillStyle = token.colour;
+ ctx.fill();
+ ctx.globalAlpha = 1;
+ ctx.fillStyle = inkOn(token.colour);
+ ctx.font = `800 ${Math.round(r * 1.25)}px system-ui, -apple-system, "Segoe UI", sans-serif`;
+ ctx.textAlign = "center";
+ ctx.textBaseline = "middle";
+ ctx.fillText(initialOf(token.name), x, y + 0.5);
+}
- // The player: a gold arrow pointing along its heading.
- const p = worldToMap(t, scene.player);
- const dx = Math.sin(scene.player.heading);
- const dy = Math.cos(scene.player.heading);
- const len = 7;
- const wing = 4.5;
+/** An off-screen agent on the card edge: a small arrow in its status colour pointing towards it. */
+export function drawEdgeArrow(ctx: Ctx, x: number, y: number, angle: number, token: Pick<AgentToken, "colour" | "state" | "selected">): void {
+ const size = token.selected ? 8 : 6;
+ const cos = Math.cos(angle);
+ const sin = Math.sin(angle);
+ const pt = (along: number, across: number): MapPoint => ({ x: x + cos * along - sin * across, y: y + sin * along + cos * across });
+ const tip = pt(size, 0);
+ const l = pt(-size * 0.7, size * 0.75);
+ const back = pt(-size * 0.25, 0);
+ const r = pt(-size * 0.7, -size * 0.75);
ctx.beginPath();
- ctx.moveTo(p.x + dx * len, p.y + dy * len);
- ctx.lineTo(p.x - dx * len * 0.5 + dy * wing, p.y - dy * len * 0.5 - dx * wing);
- ctx.lineTo(p.x - dx * len * 0.15, p.y - dy * len * 0.15);
- ctx.lineTo(p.x - dx * len * 0.5 - dy * wing, p.y - dy * len * 0.5 + dx * wing);
+ ctx.moveTo(tip.x, tip.y);
+ ctx.lineTo(l.x, l.y);
+ ctx.lineTo(back.x, back.y);
+ ctx.lineTo(r.x, r.y);
ctx.closePath();
- ctx.fillStyle = colours.player;
+ ctx.fillStyle = token.colour;
ctx.fill();
- ctx.strokeStyle = colours.playerRim;
- ctx.lineWidth = 1;
+ ctx.strokeStyle = STATE_RING[token.state];
+ ctx.lineWidth = token.selected ? 2 : 1.5;
+ ctx.lineJoin = "round";
ctx.stroke();
}
+
+/** A game-map label: white text with a dark halo, centred on (x, y). */
+export function drawMapLabel(ctx: Ctx, text: string, x: number, y: number, px: number, weight = 700): void {
+ if (!text) return;
+ ctx.font = `${weight} ${px}px system-ui, -apple-system, "Segoe UI", sans-serif`;
+ ctx.textAlign = "center";
+ ctx.textBaseline = "middle";
+ ctx.lineJoin = "round";
+ ctx.strokeStyle = MAP_PAINT.labelHalo;
+ ctx.lineWidth = Math.max(2.5, px * 0.32);
+ ctx.strokeText(text, x, y);
+ ctx.fillStyle = MAP_PAINT.label;
+ ctx.fillText(text, x, y);
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/office/office.css b/jarvis/ui/web/frontend/src/components/society/office/office.css
index 106c3e7cca..ea841da91b 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/office.css
+++ b/jarvis/ui/web/frontend/src/components/society/office/office.css
@@ -5,8 +5,12 @@
.office-fallback { display:flex; align-items:center; justify-content:center; height:100%; padding:24px; font-size:13px; color:hsl(var(--muted-foreground)); background:hsl(var(--background)); }
.office-hud { position:absolute; z-index:30; }
.office-hud-left { left:14px; top:14px; display:flex; flex-direction:column; align-items:flex-start; gap:8px; max-width:min(320px, calc(100% - 28px)); }
-/* Wraps (right-aligned) before it can run under the left cards or off the edge. */
-.office-hud-right { right:14px; top:14px; display:flex; flex-wrap:wrap; justify-content:flex-end; gap:6px; max-width:max(180px, calc(100% - 370px)); }
+/* A column to the left of the minimap (top-right, 204 px wide + 8 px gap). */
+.office-hud-right { right:226px; top:14px; display:flex; flex-direction:column; align-items:flex-end; gap:6px; }
+/* Narrow: under the minimap, wrapping within its width. */
+@media (max-width:760px) { .office-hud-right { right:14px; top:256px; flex-direction:row; flex-wrap:wrap; justify-content:flex-end; max-width:204px; } }
+/* No minimap (short or very narrow window): back to a wrapping row in the corner. */
+@media (max-height:520px), (max-width:600px) { .office-hud-right { right:14px; top:14px; flex-direction:row; flex-wrap:wrap; justify-content:flex-end; max-width:max(180px, calc(100% - 370px)); } }
.office-card { border:1px solid hsl(var(--border)); border-radius:12px; background:hsl(var(--popover) / .92); color:hsl(var(--popover-foreground)); box-shadow:0 4px 18px rgb(0 0 0 / .25); backdrop-filter:blur(6px); }
.office-title { display:flex; flex-direction:column; gap:2px; padding:8px 12px; font-size:14px; }
.office-title span { font-size:11px; color:hsl(var(--muted-foreground)); }
diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeHud.css b/jarvis/ui/web/frontend/src/components/society/office/officeHud.css
index b9f63c954d..84984ab27c 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/officeHud.css
+++ b/jarvis/ui/web/frontend/src/components/society/office/officeHud.css
@@ -1,5 +1,6 @@
/* Office HUD panels and prompts: theme tokens only, so light and dark mode both work. */
-.office-panel-slot { position:absolute; z-index:35; right:14px; top:60px; width:min(340px, calc(100% - 28px)); max-height:calc(100% - 120px); display:flex; }
+/* Opens below the minimap card (14 + 236 px) in the top-right corner. */
+.office-panel-slot { position:absolute; z-index:35; right:14px; top:258px; width:min(340px, calc(100% - 28px)); max-height:calc(100% - 310px); display:flex; }
.office-panel { display:flex; flex-direction:column; width:100%; min-height:0; overflow:hidden; }
.office-panel-head { display:flex; align-items:flex-start; justify-content:space-between; gap:8px; padding:10px 12px 6px; }
.office-panel:focus { outline:none; }
@@ -53,6 +54,9 @@
.office-hud-right .office-button[aria-pressed="true"] { border-color:#f5b83d; background:hsl(var(--secondary)); }
.office-plate[data-selected] { box-shadow:0 0 0 2px #93c5fd, 0 2px 8px rgb(0 0 0 / .35); }
.office-plate-player { cursor:default; background:rgb(58 44 12 / .9); box-shadow:0 0 0 1.5px #f5b83d, 0 2px 8px rgb(0 0 0 / .35); }
-/* The right-hand buttons wrap onto a second row here; keep the panel below them. */
-@media (max-width:900px) { .office-panel-slot { top:96px; max-height:calc(100% - 150px); } .office-prompt { bottom:64px; } }
+@media (max-width:900px) { .office-prompt { bottom:64px; } }
+/* Narrow: the buttons sit under the minimap; the panel covers the map card while open. */
+@media (max-width:760px) { .office-panel-slot { top:14px; max-height:calc(100% - 80px); } }
+/* No minimap on short windows: the panel goes back under the corner buttons. */
+@media (max-height:520px) { .office-panel-slot { top:60px; max-height:calc(100% - 100px); } }
@media (max-width:600px) { .office-panel-slot { top:auto; bottom:12px; max-height:55%; } .office-hud-right { max-width:60%; } .office-prompt { bottom:48px; max-width:calc(100% - 28px); } }
diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeMinimap.css b/jarvis/ui/web/frontend/src/components/society/office/officeMinimap.css
index 8641f93bc0..b1652f855e 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/officeMinimap.css
+++ b/jarvis/ui/web/frontend/src/components/society/office/officeMinimap.css
@@ -1,13 +1,43 @@
-/* Office minimap card: theme tokens only, so light and dark mode both work. The map picture reads the same tokens. */
-.office-minimap { right:14px; bottom:44px; display:flex; flex-direction:column; padding:4px 6px 6px; user-select:none; }
-.office-minimap[data-collapsed="true"] { padding-bottom:4px; }
-.office-minimap-head { display:flex; align-items:center; justify-content:space-between; gap:8px; padding:0 0 4px 4px; }
-.office-minimap[data-collapsed="true"] .office-minimap-head { padding-bottom:0; }
-.office-minimap-title { font-size:11px; font-weight:600; color:hsl(var(--muted-foreground)); }
-.office-minimap-toggle { display:inline-flex; align-items:center; justify-content:center; width:22px; height:22px; padding:0; }
-.office-minimap-map { position:relative; border-radius:8px; overflow:hidden; border:1px solid hsl(var(--border)); background:hsl(var(--background)); }
+/* Office minimap, compass bar and full map. The painted map art keeps one
+ palette in both modes; every piece of chrome here reads theme tokens. */
+
+/* Minimap: square card in the top-right corner, a thin light frame and a soft shadow. */
+.office-minimap { right:14px; top:14px; display:flex; flex-direction:column; gap:4px; user-select:none; }
+.office-minimap-map { position:relative; overflow:hidden; border-radius:14px; border:2px solid hsl(var(--popover) / .92); background:#121833; box-shadow:0 0 0 1px hsl(var(--border)), 0 6px 22px rgb(0 0 0 / .35); }
+/* Inner shadow / vignette over the picture, like a game minimap's lens. */
+.office-minimap-map::after { content:""; position:absolute; inset:0; border-radius:12px; pointer-events:none; box-shadow:inset 0 0 18px 4px rgb(0 0 0 / .38), inset 0 0 0 1px rgb(255 255 255 / .12); }
.office-minimap-canvas { display:block; cursor:crosshair; touch-action:manipulation; }
-.office-minimap-tooltip { position:absolute; z-index:1; transform:translateY(-100%); padding:2px 7px; border-radius:6px; border:1px solid hsl(var(--border)); background:hsl(var(--popover)); color:hsl(var(--popover-foreground)); font-size:11px; font-weight:600; white-space:nowrap; max-width:180px; overflow:hidden; text-overflow:ellipsis; pointer-events:none; box-shadow:0 2px 8px rgb(0 0 0 / .2); }
+.office-minimap-north { position:absolute; z-index:1; top:3px; left:50%; transform:translateX(-50%); min-width:16px; padding:0 4px; border-radius:999px; background:hsl(var(--popover) / .92); color:hsl(var(--popover-foreground)); font-size:10px; font-weight:800; line-height:15px; text-align:center; pointer-events:none; box-shadow:0 1px 4px rgb(0 0 0 / .3); }
+.office-minimap-tooltip { position:absolute; z-index:2; transform:translateY(-100%); padding:2px 7px; border-radius:6px; border:1px solid hsl(var(--border)); background:hsl(var(--popover)); color:hsl(var(--popover-foreground)); font-size:11px; font-weight:600; white-space:nowrap; max-width:160px; overflow:hidden; text-overflow:ellipsis; pointer-events:none; box-shadow:0 2px 8px rgb(0 0 0 / .2); }
.office-minimap-tooltip[data-side="left"] { transform:translate(-100%, -100%); }
-@media (max-height:520px) { .office-minimap { display:none; } }
-@media (max-width:600px) { .office-minimap { display:none; } }
+.office-minimap-bar { display:flex; align-items:center; gap:4px; padding:2px; border:1px solid hsl(var(--border)); border-radius:10px; background:hsl(var(--popover) / .92); color:hsl(var(--popover-foreground)); backdrop-filter:blur(6px); box-shadow:0 2px 10px rgb(0 0 0 / .2); }
+.office-minimap-btn { display:inline-flex; align-items:center; justify-content:center; gap:4px; height:22px; min-width:22px; padding:0 5px; border:0; border-radius:7px; background:none; color:hsl(var(--popover-foreground)); font-size:11px; font-weight:600; cursor:pointer; }
+.office-minimap-btn:hover:not(:disabled) { background:hsl(var(--secondary)); }
+.office-minimap-btn:disabled { opacity:.4; cursor:default; }
+.office-minimap-btn:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:1px; }
+.office-minimap-zoom { min-width:34px; text-align:center; font-size:10px; font-variant-numeric:tabular-nums; color:hsl(var(--muted-foreground)); }
+.office-minimap-open { margin-left:auto; padding:0 8px; border:1px solid hsl(var(--border)); }
+
+/* Compass bar: top centre, clear of the window caption above the stage and the side HUD. */
+.office-compass { left:50%; top:8px; transform:translateX(-50%); width:min(440px, calc(100% - 720px)); height:34px; border:1px solid hsl(var(--border)); border-radius:10px; background:hsl(var(--popover) / .88); box-shadow:0 4px 16px rgb(0 0 0 / .25); backdrop-filter:blur(6px); pointer-events:none; }
+.office-compass-canvas { display:block; width:100%; height:100%; -webkit-mask-image:linear-gradient(90deg, transparent, #000 14%, #000 86%, transparent); mask-image:linear-gradient(90deg, transparent, #000 14%, #000 86%, transparent); }
+.office-compass-readout { position:absolute; top:100%; left:50%; transform:translate(-50%, 3px); padding:0 6px; border-radius:6px; border:1px solid hsl(var(--border)); background:hsl(var(--popover) / .92); color:hsl(var(--popover-foreground)); font-size:10px; font-weight:700; line-height:16px; font-variant-numeric:tabular-nums; }
+.office-compass-readout:empty { display:none; }
+
+/* Full map: a dialog over most of the stage. */
+.office-fullmap-backdrop { position:absolute; inset:0; z-index:60; display:flex; align-items:center; justify-content:center; padding:3%; background:hsl(var(--background) / .55); backdrop-filter:blur(3px); }
+.office-fullmap { display:flex; flex-direction:column; width:100%; height:100%; max-width:1200px; min-height:0; overflow:hidden; }
+.office-fullmap:focus { outline:none; }
+.office-fullmap-head { display:flex; align-items:center; gap:12px; padding:8px 10px 8px 14px; border-bottom:1px solid hsl(var(--border)); }
+.office-fullmap-heading { display:flex; flex-direction:column; min-width:0; }
+.office-fullmap-heading h2 { margin:0; font-size:14px; font-weight:700; }
+.office-fullmap-heading span { font-size:11px; color:hsl(var(--muted-foreground)); }
+.office-fullmap-readout { margin-left:auto; font-size:12px; font-weight:600; font-variant-numeric:tabular-nums; color:hsl(var(--muted-foreground)); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
+.office-fullmap-close { display:inline-flex; align-items:center; justify-content:center; width:28px; height:28px; }
+.office-fullmap-body { position:relative; flex:1; min-height:0; overflow:hidden; background:hsl(var(--muted)); }
+.office-fullmap-canvas { display:block; cursor:crosshair; }
+.office-fullmap-axis { position:absolute; transform:translate(-50%, -50%); font-size:11px; font-weight:800; color:hsl(var(--foreground)); pointer-events:none; }
+
+@media (max-width:960px) { .office-compass { display:none; } }
+@media (max-height:520px), (max-width:600px) { .office-minimap { display:none; } }
+@media (prefers-reduced-motion:reduce) { .office-fullmap-backdrop { backdrop-filter:none; } }
diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeMotion.test.ts b/jarvis/ui/web/frontend/src/components/society/office/officeMotion.test.ts
index fc2346563a..258025c235 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/officeMotion.test.ts
+++ b/jarvis/ui/web/frontend/src/components/society/office/officeMotion.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { stepMover, turnToward, WALK_SPEED, wrapAngle, type Mover } from "./officeMotion";
+import { BODY_SPACING, WALK_SPEED, applySeparation, clearOfBodies, separation, stepMover, stepMoverAvoiding, turnToward, type Mover, wrapAngle } from "./officeMotion";
describe("office motion", () => {
it("turns the short way and clamps the step", () => {
@@ -49,3 +49,39 @@ describe("office motion", () => {
expect(m.z).toBeCloseTo(2.5);
});
});
+
+describe("separation", () => {
+ it("is zero when nobody is near and pushes away from a close body", () => {
+ expect(separation({ x: 0, z: 0 }, 0, [{ x: 5, z: 5 }])).toEqual({ x: 0, z: 0 });
+ const push = separation({ x: 0, z: 0 }, Math.PI / 2, [{ x: 0.3, z: 0 }]);
+ expect(push.x).toBeLessThan(0);
+ });
+ it("adds a sidestep when someone stands straight ahead", () => {
+ // Walking towards +z, someone 0.5 m ahead: the push has a sideways component.
+ const push = separation({ x: 0, z: 0 }, 0, [{ x: 0, z: 0.5 }]);
+ expect(Math.abs(push.x)).toBeGreaterThan(0.1);
+ });
+ it("only nudges onto walkable ground and reports spacing", () => {
+ const m = { x: 0, z: 0, heading: 0, path: [] };
+ applySeparation(m, { x: 1, z: 0 }, 0.1, () => false);
+ expect(m.x).toBe(0);
+ applySeparation(m, { x: 1, z: 0 }, 0.1, () => true);
+ expect(m.x).toBeGreaterThan(0);
+ expect(clearOfBodies({ x: 0, z: 0 }, [{ x: BODY_SPACING / 2, z: 0 }])).toBe(false);
+ expect(clearOfBodies({ x: 0, z: 0 }, [{ x: BODY_SPACING * 2, z: 0 }])).toBe(true);
+ });
+ it("keeps two walkers crossing head-on apart", () => {
+ const a = { x: 0, z: -3, heading: 0, path: [{ x: 0, z: 3 }] };
+ const b = { x: 0.02, z: 3, heading: Math.PI, path: [{ x: 0.02, z: -3 }] };
+ let closest = Infinity;
+ for (let i = 0; i < 600; i += 1) {
+ stepMoverAvoiding(a, 1.35, 1 / 60, [b], () => true);
+ stepMoverAvoiding(b, 1.35, 1 / 60, [a], () => true);
+ closest = Math.min(closest, Math.hypot(a.x - b.x, a.z - b.z));
+ }
+ expect(closest).toBeGreaterThan(0.45);
+ // Both still reach their goals.
+ expect(a.path).toHaveLength(0);
+ expect(b.path).toHaveLength(0);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeMotion.ts b/jarvis/ui/web/frontend/src/components/society/office/officeMotion.ts
index f3bbcf151c..63083469f2 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/officeMotion.ts
+++ b/jarvis/ui/web/frontend/src/components/society/office/officeMotion.ts
@@ -63,3 +63,77 @@ export function stepMover(m: Mover, speed: number, dt: number): { moved: number;
if (dirX !== 0 || dirZ !== 0) m.heading = turnToward(m.heading, Math.atan2(dirX, dirZ), TURN_RATE * dt);
return { moved, arrived: m.path.length === 0 };
}
+
+/** Two bodies never come closer than this (centre to centre), in metres. */
+export const BODY_SPACING = 0.62;
+
+/**
+ * Local avoidance: a sideways-biased push away from nearby bodies, strongest
+ * when they touch. Zero when nobody is within `radius`. Pure.
+ */
+export function separation(self: Point, heading: number, others: Iterable<Point>, radius = BODY_SPACING * 1.4): Point {
+ let x = 0, z = 0;
+ const fx = Math.sin(heading), fz = Math.cos(heading);
+ for (const o of others) {
+ const dx = self.x - o.x, dz = self.z - o.z;
+ const d = Math.hypot(dx, dz);
+ if (d < 1e-6 || d >= radius) continue;
+ const w = (radius - d) / radius;
+ x += (dx / d) * w; z += (dz / d) * w;
+ // Someone straight ahead: add a sidestep to the right so two walkers pass instead of pushing head-on.
+ const ahead = -(dx * fx + dz * fz) / d;
+ if (ahead > 0.6) { x += fz * w * 0.8; z += -fx * w * 0.8; }
+ }
+ return { x, z };
+}
+
+/** True when a point keeps the spacing from every other body. */
+export function clearOfBodies(p: Point, others: Iterable<Point>, spacing = BODY_SPACING): boolean {
+ for (const o of others) if (Math.hypot(p.x - o.x, p.z - o.z) < spacing) return false;
+ return true;
+}
+
+/**
+ * Nudge a mover sideways out of others' way, only onto walkable ground.
+ * Called after `stepMover`; the path pulls it back on the next frames.
+ */
+export function applySeparation(m: Mover, push: Point, dt: number, walkable: (p: Point) => boolean, maxSpeed = 0.9): void {
+ const len = Math.hypot(push.x, push.z);
+ if (len < 1e-6) return;
+ const step = Math.min(len, 1) * maxSpeed * dt;
+ const nx = m.x + (push.x / len) * step, nz = m.z + (push.z / len) * step;
+ if (walkable({ x: nx, z: nz })) { m.x = nx; m.z = nz; }
+}
+
+/**
+ * Walk the path while steering around other bodies: the heading blends the
+ * next waypoint with a push away from anyone close, and the walker slows when
+ * someone stands right ahead. Falls back to plain path following whenever the
+ * steered step would leave walkable ground.
+ */
+export function stepMoverAvoiding(m: Mover, speed: number, dt: number, others: readonly Point[], walkable: (p: Point) => boolean): { moved: number; arrived: boolean } {
+ if (m.path.length === 0) return { moved: 0, arrived: true };
+ const next = m.path[0];
+ const dx = next.x - m.x, dz = next.z - m.z;
+ const dist = Math.hypot(dx, dz);
+ const push = separation(m, m.heading, others, 1.2);
+ const pushLen = Math.hypot(push.x, push.z);
+ if (pushLen < 1e-3 || dist < 0.2) return stepMover(m, speed, dt);
+ let ax = dx / dist + push.x * 1.6, az = dz / dist + push.z * 1.6;
+ const len = Math.hypot(ax, az) || 1;
+ ax /= len; az /= len;
+ // Slow down while someone blocks the way ahead.
+ let slow = 1;
+ for (const o of others) {
+ const ox = o.x - m.x, oz = o.z - m.z;
+ const d = Math.hypot(ox, oz);
+ if (d < 0.95 && d > 1e-6 && (ox * dx + oz * dz) / (d * dist) > 0.7) slow = Math.min(slow, Math.max(0.25, (d - BODY_SPACING) / 0.4));
+ }
+ const step = Math.min(speed * slow * dt, dist);
+ const cand = { x: m.x + ax * step, z: m.z + az * step };
+ if (!walkable(cand)) return stepMover(m, speed, dt);
+ m.x = cand.x; m.z = cand.z;
+ if (Math.hypot(next.x - m.x, next.z - m.z) < 0.12) m.path.shift();
+ m.heading = turnToward(m.heading, Math.atan2(ax, az), TURN_RATE * dt);
+ return { moved: step, arrived: m.path.length === 0 };
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/office/walkerRegistry.ts b/jarvis/ui/web/frontend/src/components/society/office/walkerRegistry.ts
index e27bdb4ec7..ad7bb0662b 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/walkerRegistry.ts
+++ b/jarvis/ui/web/frontend/src/components/society/office/walkerRegistry.ts
@@ -12,3 +12,12 @@ export const knownAgents = new Set<string>();
/** Agents sitting at their own desk right now — their monitor shows their chat. */
export const seatedAtDesk = new Set<string>();
+
+/** Agents that fly (Gigi) instead of walking: nobody has to step around them. */
+export const floatingAgents = new Set<string>();
+
+/** Every walking body except `selfId`: the agents on foot plus, optionally, the person's character. */
+export function* bodiesExcept(selfId: string | null, player: Point | null): Generator<Point> {
+ for (const [id, p] of agentPositions) if (id !== selfId && !floatingAgents.has(id)) yield p;
+ if (player) yield player;
+}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json b/jarvis/ui/web/frontend/src/i18n/locales/society/de.json
index 70e1fc24e1..9eb8aa8bdb 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/de.json
@@ -735,7 +735,7 @@
"open_agent": "{0} öffnen",
"overview": "Übersicht",
"ledger": "Agentenliste",
- "help": "WASD / Pfeile laufen · Shift rennt · Boden anklicken zum Hingehen · E interagiert · Ziehen dreht · Scrollen zoomt",
+ "help": "WASD / Pfeile laufen · Shift rennt · Boden anklicken zum Hingehen · E interagiert · Ziehen dreht · Scrollen zoomt · M öffnet die Karte",
"sample": "Beispiel-Agenten – das Backend ist noch nicht erreichbar.",
"overflow": "Nur die ersten {0} Agenten haben einen Schreibtisch; die Liste zeigt alle.",
"open_space": "Open Space",
@@ -825,10 +825,26 @@
"hair_bald": "Glatze",
"hair_label": "Frisur oder Kopfbedeckung",
"minimap_title": "Grundriss",
- "minimap_expand": "Grundriss einblenden",
- "minimap_collapse": "Grundriss ausblenden",
"minimap_aria": "Grundriss: {0} Agenten, {1} arbeiten",
- "minimap_you": "Du"
+ "minimap_you": "Du",
+ "minimap_zoom": "{0} m",
+ "minimap_zoom_in": "Hineinzoomen",
+ "minimap_zoom_out": "Herauszoomen",
+ "minimap_open_map": "Karte (M)",
+ "minimap_open_map_label": "Große Karte öffnen (M)",
+ "compass_label": "Kompass: die Richtung, in die die Kamera schaut",
+ "compass_n": "N",
+ "compass_ne": "NO",
+ "compass_e": "O",
+ "compass_se": "SO",
+ "compass_s": "S",
+ "compass_sw": "SW",
+ "compass_w": "W",
+ "compass_nw": "NW",
+ "map_title": "Büroplan",
+ "map_hint": "Klicke irgendwohin, um dorthin zu laufen. Esc oder M schließt die Karte.",
+ "map_close": "Karte schließen",
+ "map_aria": "Großer Büroplan. Klicke auf eine Stelle, um dorthin zu laufen."
}
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json b/jarvis/ui/web/frontend/src/i18n/locales/society/en.json
index d53b30529c..0a30de46b3 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/en.json
@@ -735,7 +735,7 @@
"open_agent": "Open {0}",
"overview": "Overview",
"ledger": "Agents list",
- "help": "WASD / arrows walk · Shift runs · Click the floor to walk there · E interacts · Drag rotates · Scroll zooms",
+ "help": "WASD / arrows walk · Shift runs · Click the floor to walk there · E interacts · Drag rotates · Scroll zooms · M opens the map",
"sample": "Sample agents — the backend is not reachable yet.",
"overflow": "Only the first {0} agents have a desk; the list shows everyone.",
"open_space": "Open space",
@@ -825,10 +825,26 @@
"hair_bald": "Bald",
"hair_label": "Hair or hat",
"minimap_title": "Floor map",
- "minimap_expand": "Show floor map",
- "minimap_collapse": "Hide floor map",
"minimap_aria": "Floor map: {0} agents, {1} working",
- "minimap_you": "You"
+ "minimap_you": "You",
+ "minimap_zoom": "{0} m",
+ "minimap_zoom_in": "Zoom in",
+ "minimap_zoom_out": "Zoom out",
+ "minimap_open_map": "Map (M)",
+ "minimap_open_map_label": "Open the full map (M)",
+ "compass_label": "Compass: the direction the camera faces",
+ "compass_n": "N",
+ "compass_ne": "NE",
+ "compass_e": "E",
+ "compass_se": "SE",
+ "compass_s": "S",
+ "compass_sw": "SW",
+ "compass_w": "W",
+ "compass_nw": "NW",
+ "map_title": "Office map",
+ "map_hint": "Click anywhere to walk there. Esc or M closes the map.",
+ "map_close": "Close map",
+ "map_aria": "Full office map. Click a spot to walk there."
}
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json b/jarvis/ui/web/frontend/src/i18n/locales/society/es.json
index 8ccd79dc3b..cf3bbf2bf2 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/es.json
@@ -735,7 +735,7 @@
"open_agent": "Abrir {0}",
"overview": "Vista general",
"ledger": "Lista de agentes",
- "help": "WASD / flechas para andar · Shift corre · Clic en el suelo para ir · E interactúa · Arrastrar gira · Rueda para zoom",
+ "help": "WASD / flechas para andar · Shift corre · Clic en el suelo para ir · E interactúa · Arrastrar gira · Rueda para zoom · M abre el mapa",
"sample": "Agentes de ejemplo: el backend aún no está disponible.",
"overflow": "Solo los primeros {0} agentes tienen escritorio; la lista muestra a todos.",
"open_space": "Espacio abierto",
@@ -825,10 +825,26 @@
"hair_bald": "Calvo",
"hair_label": "Peinado o sombrero",
"minimap_title": "Plano de la planta",
- "minimap_expand": "Mostrar plano",
- "minimap_collapse": "Ocultar plano",
"minimap_aria": "Plano de la planta: {0} agentes, {1} trabajando",
- "minimap_you": "Tú"
+ "minimap_you": "Tú",
+ "minimap_zoom": "{0} m",
+ "minimap_zoom_in": "Acercar",
+ "minimap_zoom_out": "Alejar",
+ "minimap_open_map": "Mapa (M)",
+ "minimap_open_map_label": "Abrir el mapa completo (M)",
+ "compass_label": "Brújula: la dirección a la que mira la cámara",
+ "compass_n": "N",
+ "compass_ne": "NE",
+ "compass_e": "E",
+ "compass_se": "SE",
+ "compass_s": "S",
+ "compass_sw": "SO",
+ "compass_w": "O",
+ "compass_nw": "NO",
+ "map_title": "Plano de la oficina",
+ "map_hint": "Haz clic en cualquier sitio para ir allí. Esc o M cierra el mapa.",
+ "map_close": "Cerrar mapa",
+ "map_aria": "Plano completo de la oficina. Haz clic en un sitio para ir allí."
}
}
}