Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(desktop): boot like a computer, then walk in as your avatar and sit down at the desktop

nirholasa8f48e99ce7f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c326155c5..dcd00ffef 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -25,9 +25,11 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Every 3D generation now writes a signed run receipt**: Each Studio run (avatars, rigged avatars, meshes, rigs, refinements) records stage by stage what was expected, what was observed, and a verdict: met, recovered by a named fallback, missed with its cause, or skipped. The rig is verified by reading the delivered file back, not by trusting the rigger. Receipts are ed25519-signed, linked from every result, browsable at /runs with stage-by-stage rates, and verifiable offline with one command. (`/runs`) `[feature]`
- **Menu bar panel for the desktop app**: Click the three.ws icon in your menu bar or tray and a small panel shows your agent alive in 3D, its Solana wallet balance, a start and stop button, anything waiting on your approval, unread alerts and a box to ask the agent something. Approvals still open the native confirmation window, so what you approve is exactly what you were shown. (`/desktop`) `[feature]`
- **The desktop behaves like a real computer**: Drag a selection box across the desktop, move icons on a snap grid, right-click for view options, and open every app from desktop icons or All Apps. Settings now covers your profile, theme, accent colour, wallpaper (including your own photo), icon size and taskbar, and the whole session (windows, icon layout, preferences) is saved in your browser, with export, import and reset. (`/docs/desktop`) `[feature, desktop]`
+- **The prompt director works again, found by its own run receipts**: The first receipts showed the director's brief falling back on every Studio run. The replies were arriving in 5 to 10 seconds but ran past the 1000-character prompt cap or ended on the closing constraint the director is told to end on, and both were discarded as clipped. The director now writes to a word budget the models actually follow, the guard accepts the mandated ending, both forge clients share one guard, and a receipt now names the exact reason a brief fell back (too long with its length, unfinished, no reply) instead of a generic timeout. Receipts also stop saying every stage met when a stage was skipped. (`/runs`) `[fix]`
- **The terminal 3D renderer animates live in every HTTP client**: curl three.ws/tty streams an animated 3D character into your terminal frame by frame. Clients that ask for compressed responses, such as curl --compressed, scripts using fetch, and most HTTP libraries, used to get nothing for about ten seconds and then the whole animation at once. Live streams are no longer compressed, so every client sees the character move from the first frame. Streaming agent and chat responses get the same fix. (`/tty`) `[fix]`
- **three.ws is now a desktop**: The homepage is a web desktop with a taskbar, Start menu, widgets and draggable, snappable windows that open every part of the platform, in the CTRL Windows-style Mica theme. The original homepage is kept as the classic view at /classic, one click from the taskbar. (`/docs/desktop`) `[feature]`
- **Trenches Pulse: live launch and smart-money intelligence**: A new Trenches page shows what is happening on Solana and Robinhood Chain right now: new launches and graduations as they happen, the hottest tokens by trade flow, and scored smart-money wallets. Every number comes from a live on-chain feed, and if the data service is unreachable the page says so instead of showing made-up figures. (`/trenches`) `[feature]`
+- **Walk into three.ws: the homepage boots, unlocks, and lets you enter the desktop as your avatar**: The homepage now starts like a real computer. A boot screen runs live checks (your GPU, the site catalog, your account, the avatar body, the $THREE feed, your gem ledger) and a lock screen greets you with the $THREE price and your balances. Press Walk in and you arrive on a campus as your avatar: walk to your desk and sit down to open the desktop on the monitor, pick up the phone for Pocket, put on the headset for VR, enter the three.ws Exchange (a live ticker board and Trenches inside), the Launchpad, the Forge, the Gallery, Agent Plaza and the Marketplace, or dig for gems in the mine, where every gem is rolled server-side and kept on your account. Settings gets an Arrival section to choose where you start, the taskbar gets a World button, and the desktop wears the classic three.ws violet grid. (`/`) `[feature, desktop]`
## 2026-10-10
diff --git a/STRUCTURE.md b/STRUCTURE.md
index a67f4a454..d50df8a61 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -24,7 +24,7 @@ bottom.
| Event Market pages and share cards | [pages/event-markets.html](pages/event-markets.html) `→ /event-markets`, [pages/event-market.html](pages/event-market.html) `→ /event-markets/<slug>`, [src/event-markets/](src/event-markets/), [api/event-market-og.js](api/event-market-og.js), [api/event-market-share.js](api/event-market-share.js), [api/_lib/event-market-card.js](api/_lib/event-market-card.js) | Live | Browse and detail pages, pick flow, odds chart, per-market SVG share card and crawlable meta page, entry strips on Arena, event, launches and home. Docs: [docs/event-markets.md](docs/event-markets.md#pages-and-share-cards). Tests: [tests/event-market-card.test.js](tests/event-market-card.test.js) |
| Event Market scoring, leaderboard and rewards | [api/_lib/event-markets/scoring.js](api/_lib/event-markets/scoring.js), [rollup.js](api/_lib/event-markets/rollup.js), [fairness.js](api/_lib/event-markets/fairness.js), [leaderboard.js](api/_lib/event-markets/leaderboard.js), [api/cron/event-markets-rollup.js](api/cron/event-markets-rollup.js), [data/event-market-scoring.json](data/event-market-scoring.json), [pages/event-markets-leaderboard.html](pages/event-markets-leaderboard.html) `→ /event-markets/leaderboard`, [scripts/event-markets-season-payouts.mjs](scripts/event-markets-season-payouts.mjs) | Live once migration 20261012400000 is applied; payouts owner-gated | Scores, streaks, season ranks and badges from the rollup cron; wallet-derived names; fair-play ranking checks; season reward table printed for owner approval, never sent automatically. Docs: [docs/event-markets.md](docs/event-markets.md#scoring-and-seasons). Tests: [tests/event-markets-scoring.test.js](tests/event-markets-scoring.test.js) |
| Event Market live feed | [api/event-markets/stream.js](api/event-markets/stream.js), [api/_lib/event-markets/hub.js](api/_lib/event-markets/hub.js), [feed.js](api/_lib/event-markets/feed.js), [moves.js](api/_lib/event-markets/moves.js), [live-stats.js](api/_lib/event-markets/live-stats.js), [api/cron/event-markets-feed.js](api/cron/event-markets-feed.js), [src/event-markets/live-feed.js](src/event-markets/live-feed.js), [ticker.js](src/event-markets/ticker.js), [data/event-markets-feed.json](data/event-markets-feed.json) | Live (migration 20261012200000 applied) | SSE odds, picks, moves and lifecycle with Last-Event-ID resume, odds-move detector, home ticker, in-place odds on the market page with polling fallback, pulse and trending additions. Docs: [docs/event-markets.md](docs/event-markets.md#live-feed). Tests: [tests/event-markets-live-feed.test.js](tests/event-markets-live-feed.test.js), [tests/event-markets-live-stats.test.js](tests/event-markets-live-stats.test.js). Bench: [scripts/event-markets-fanout-bench.mjs](scripts/event-markets-fanout-bench.mjs) |
-| Web desktop (homepage as an OS) | Page [pages/desktop.html](pages/desktop.html) `→ /`, code [src/desktop/](src/desktop) ([README](src/desktop/README.md)), previous homepage [pages/home.html](pages/home.html) `→ /classic` | Built and verified locally | Taskbar, Start, widgets and snappable windows framing real three.ws pages in the CTRL Mica theme. Desktop icons on a snap grid with marquee selection ([icon-layer.js](src/desktop/icon-layer.js)), All Apps, a Settings app (profile, accent, wallpaper, icon size) and a session saved in localStorage plus IndexedDB. Framed pages hide the site nav via `public/nav.js` (`tws-os:` frame name). Docs: [docs/desktop.md](docs/desktop.md). Tests: [tests/desktop-layout.test.js](tests/desktop-layout.test.js), [tests/desktop-page.test.js](tests/desktop-page.test.js), browser drive [scripts/desktop-interact.mjs](scripts/desktop-interact.mjs) |
+| Web desktop (homepage as an OS, with a 3D campus in front of it) | Page [pages/desktop.html](pages/desktop.html) `→ /`, code [src/desktop/](src/desktop) ([README](src/desktop/README.md)): boot and lock screen [boot.js](src/desktop/boot.js) + [boot-logic.js](src/desktop/boot-logic.js), campus [src/desktop/world/](src/desktop/world), gem ledger [api/world/gems.js](api/world/gems.js) over [api/_lib/world-gems.js](api/_lib/world-gems.js) (migration `20261015000000_world_gems.sql`); previous homepage [pages/home.html](pages/home.html) `→ /classic` | Built and verified locally | Boots with a live log of real checks (GPU, site catalog, account, fonts, avatar, $THREE feed, gem ledger), locks with a greeting and live chips, then the visitor walks in as their avatar: a campus with the home office (sit at the desk to open the desktop on the monitor, pick up the phone for Pocket, put on the headset for WebXR), the three.ws Exchange with a live ticker (Trenches), the Launchpad, the Forge, the Gallery, Agent Plaza, the Marketplace and a gem mine with server-rolled, rate-limited digs. Taskbar, Start, widgets and snappable windows framing real three.ws pages in the CTRL Mica theme; icons on a snap grid, All Apps, Settings (profile, Arrival, accent, wallpaper, icon size), session in localStorage plus IndexedDB. Framed pages hide the site nav via `public/nav.js` (`tws-os:` frame name). Docs: [docs/desktop.md](docs/desktop.md). Tests: [tests/desktop-boot.test.js](tests/desktop-boot.test.js), [tests/world-places.test.js](tests/world-places.test.js), [tests/world-ticker.test.js](tests/world-ticker.test.js), [tests/desktop-layout.test.js](tests/desktop-layout.test.js), [tests/desktop-page.test.js](tests/desktop-page.test.js); browser drives [scripts/desktop-world-smoke.mjs](scripts/desktop-world-smoke.mjs), [scripts/desktop-interact.mjs](scripts/desktop-interact.mjs) |
| Trenches Pulse (Solana + Robinhood Chain intelligence) | Service [services/pulse/](services/pulse) (vendored nirholas/pulse: firehose, scorer, API, Telegram newsletter), proxy [api/trenches.js](api/trenches.js) `→ /api/trenches`, page [pages/trenches.html](pages/trenches.html) + [src/trenches.js](src/trenches.js) `→ /trenches` | Built and verified locally; service deploy pending owner approval | Real pump.fun firehose over Solana WebSocket: launches, graduations, hottest tokens, runners, scored wallets. Offline upstream is a designed 503 state, never fabricated data. Docs: [docs/trenches.md](docs/trenches.md). Tests: [tests/trenches-api.test.js](tests/trenches-api.test.js) |
| Browse by goal (every feature grouped into twelve goals, search, pins, what-next strip) | [pages/everything.html](pages/everything.html), [src/everything.js](src/everything.js), [src/everything.css](src/everything.css), taxonomy [scripts/lib/feature-jobs.mjs](scripts/lib/feature-jobs.mjs), [public/next-steps.js](public/next-steps.js) | Live | `/everything` reads `public/features.json`, which `scripts/build-page-index.mjs` builds from `data/pages.json` plus the goal taxonomy, so a new page appears with no extra step. Also drives the goal labels in the ⌘K palette and the nav entry. Docs: [docs/everything.md](docs/everything.md). Tests: [tests/feature-jobs.test.js](tests/feature-jobs.test.js), [tests/next-steps.test.js](tests/next-steps.test.js) |
| Event Market agent forecasters | [api/_lib/event-markets/forecasters.js](api/_lib/event-markets/forecasters.js), [analyze.js](api/_lib/event-markets/analyze.js), [forecast-runner.js](api/_lib/event-markets/forecast-runner.js), [forecaster-routes.js](api/_lib/event-markets/forecaster-routes.js), [api/cron/event-markets-forecasters.js](api/cron/event-markets-forecasters.js), [api/_mcpagent/event-market-forecast-tools.js](api/_mcpagent/event-market-forecast-tools.js), [src/event-markets/forecasting.js](src/event-markets/forecasting.js), [forecasters.js](src/event-markets/forecasters.js), [pages/event-markets-forecasters.html](pages/event-markets-forecasters.html) `→ /event-markets/forecasters`, [data/event-markets-agents.json](data/event-markets-agents.json) | Live (migration 20261012120000 applied) | Agent picks as the agent's own identity with confidence, rationale and evidence; market-page agents panel; track record and calibration on the agent profile; ranked board; follow with notifications; owner-controlled autonomous mode (off by default); MCP analyze, forecasters and agent pick. Docs: [docs/event-markets.md](docs/event-markets.md#agents). Tests: [tests/event-markets-agents.test.js](tests/event-markets-agents.test.js), [tests/event-markets-agents-mcp.test.js](tests/event-markets-agents-mcp.test.js), [tests/event-markets-forecasting-ui.test.js](tests/event-markets-forecasting-ui.test.js) |
diff --git a/api/_lib/migrations/20261015000000_world_gems.sql b/api/_lib/migrations/20261015000000_world_gems.sql
new file mode 100644
index 000000000..06f7947bc
--- /dev/null
+++ b/api/_lib/migrations/20261015000000_world_gems.sql
@@ -0,0 +1,23 @@
+-- World gems: the ledger behind gem mining in the three.ws world (the 3D entry
+-- to the web desktop at /). One row per gem mined. The server rolls the gem
+-- and enforces the mining cadence, so a client can only ever ask "I finished
+-- a dig at this node", never "give me a diamond".
+-- Apply: node scripts/apply-migrations.mjs --apply --file 20261015000000_world_gems.sql
+-- Idempotent and additive. Writer: api/world/gems.js. Docs: docs/desktop.md.
+
+CREATE TABLE IF NOT EXISTS world_gems (
+ id bigserial PRIMARY KEY,
+ -- Exactly one of user_id / anon_id identifies the miner. Anonymous miners
+ -- supply a stable browser id, the same convention walk_metrics uses, and
+ -- their gems move to the account on the first signed-in dig.
+ user_id uuid REFERENCES users(id) ON DELETE CASCADE,
+ anon_id text,
+ node text NOT NULL,
+ gem text NOT NULL,
+ amount integer NOT NULL DEFAULT 1 CHECK (amount > 0),
+ mined_at timestamptz NOT NULL DEFAULT now(),
+ CONSTRAINT world_gems_miner_present CHECK (user_id IS NOT NULL OR anon_id IS NOT NULL)
+);
+
+CREATE INDEX IF NOT EXISTS world_gems_user_idx ON world_gems (user_id, mined_at DESC) WHERE user_id IS NOT NULL;
+CREATE INDEX IF NOT EXISTS world_gems_anon_idx ON world_gems (anon_id, mined_at DESC) WHERE anon_id IS NOT NULL;
diff --git a/api/_lib/world-gems.js b/api/_lib/world-gems.js
new file mode 100644
index 000000000..4bb78b386
--- /dev/null
+++ b/api/_lib/world-gems.js
@@ -0,0 +1,87 @@
+// Pure rules for gem mining in the three.ws world. Kept free of I/O so the
+// api/world/gems.js handler and the src/desktop/world/mine.js HUD agree on
+// the table and the tests can pin it without a database.
+
+/** Seconds a miner has to spend at a node before a dig can complete. */
+export const DIG_SECONDS = 4;
+
+/** Server-side floor between two completed digs for one miner, in ms. */
+export const MIN_DIG_INTERVAL_MS = (DIG_SECONDS - 0.75) * 1000;
+
+/** Most digs one miner can complete per UTC day. Keeps the ledger honest. */
+export const DAILY_DIG_CAP = 300;
+
+/**
+ * Gem table. Weights sum to 1000 and are rolled server-side with crypto
+ * randomness. `hex` is the in-world crystal colour, `points` the gem's value
+ * on the miner's balance.
+ */
+export const GEMS = [
+ { id: 'quartz', label: 'Quartz', weight: 520, points: 1, hex: 0xe6e6f0 },
+ { id: 'amethyst', label: 'Amethyst', weight: 260, points: 3, hex: 0xc4b5fd },
+ { id: 'sapphire', label: 'Sapphire', weight: 130, points: 8, hex: 0x60a5fa },
+ { id: 'emerald', label: 'Emerald', weight: 60, points: 20, hex: 0x34d399 },
+ { id: 'ruby', label: 'Ruby', weight: 24, points: 50, hex: 0xf87171 },
+ { id: 'diamond', label: 'Diamond', weight: 6, points: 200, hex: 0xffffff },
+];
+
+export const GEM_BY_ID = Object.fromEntries(GEMS.map((g) => [g.id, g]));
+
+/** Mining nodes in the world. Ids are the only thing the client may name. */
+export const NODES = ['vein-a', 'vein-b', 'vein-c', 'vein-d', 'vein-e'];
+
+const ANON_RE = /^[A-Za-z0-9_-]{8,64}$/;
+
+export function validAnonId(v) {
+ return typeof v === 'string' && ANON_RE.test(v);
+}
+
+export function validNode(v) {
+ return typeof v === 'string' && NODES.includes(v);
+}
+
+/**
+ * Roll a gem. `r` is a uniform number in [0, 1); callers pass crypto
+ * randomness, tests pass fixed values.
+ */
+export function rollGem(r) {
+ const total = GEMS.reduce((n, g) => n + g.weight, 0);
+ let pick = Math.max(0, Math.min(0.999999, Number(r) || 0)) * total;
+ for (const g of GEMS) {
+ if (pick < g.weight) return g;
+ pick -= g.weight;
+ }
+ return GEMS[0];
+}
+
+/**
+ * Whether a dig may complete now given the miner's last completed dig.
+ * @param {number|null|undefined} lastMinedAtMs epoch ms of the last dig, or null
+ * @param {number} nowMs
+ */
+export function digAllowed(lastMinedAtMs, nowMs = Date.now()) {
+ if (lastMinedAtMs == null || !Number.isFinite(lastMinedAtMs)) return true;
+ return nowMs - lastMinedAtMs >= MIN_DIG_INTERVAL_MS;
+}
+
+/** Total points for a list of { gem, amount } rows. */
+export function totalPoints(rows) {
+ let n = 0;
+ for (const r of rows || []) {
+ const g = GEM_BY_ID[r.gem];
+ if (!g) continue;
+ n += g.points * (Number(r.amount) || 0);
+ }
+ return n;
+}
+
+/**
+ * Collapse ledger rows into the balance the HUD shows.
+ * @param {Array<{gem:string, amount:number|string}>} rows
+ */
+export function summarize(rows) {
+ const counts = {};
+ for (const g of GEMS) counts[g.id] = 0;
+ for (const r of rows || []) if (r.gem in counts) counts[r.gem] += Number(r.amount) || 0;
+ return { gems: counts, points: totalPoints(rows), total: Object.values(counts).reduce((a, b) => a + b, 0) };
+}
diff --git a/api/world/gems.js b/api/world/gems.js
new file mode 100644
index 000000000..156c1393e
--- /dev/null
+++ b/api/world/gems.js
@@ -0,0 +1,100 @@
+// GET /api/world/gems the caller's gem balance and recent digs
+// POST /api/world/gems complete a dig: { node, anonId? }
+// ---------------------------------------------------------------------------
+// The ledger behind gem mining in the three.ws world (the 3D entry to the web
+// desktop). The server owns the roll and the cadence: a dig completes only if
+// the miner's previous dig is at least MIN_DIG_INTERVAL_MS old and the daily
+// cap is not reached, and the gem is drawn with crypto randomness from the
+// shared table in api/_lib/world-gems.js. Miners are the session user or, for
+// visitors, a stable anonymous browser id (the walk_metrics convention). A
+// signed-in dig that carries the browser's anonId adopts that browser's
+// anonymous gems onto the account, so nothing mined before signing in is lost.
+
+import { randomInt } from 'node:crypto';
+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { sql } from '../_lib/db.js';
+import { getSessionUser, extractBearer, authenticateBearer } from '../_lib/auth.js';
+import {
+ DAILY_DIG_CAP,
+ DIG_SECONDS,
+ GEMS,
+ MIN_DIG_INTERVAL_MS,
+ digAllowed,
+ rollGem,
+ summarize,
+ validAnonId,
+ validNode,
+} from '../_lib/world-gems.js';
+
+export const maxDuration = 10;
+
+async function resolveUserId(req) {
+ const bearer = extractBearer(req);
+ if (bearer) {
+ const u = await authenticateBearer(bearer, { ip: clientIp(req) }).catch(() => null);
+ if (u?.id) return u.id;
+ }
+ const u = await getSessionUser(req).catch(() => null);
+ return u?.id || null;
+}
+
+function minerClause(userId, anonId) {
+ return userId ? sql`user_id = ${userId}` : sql`anon_id = ${anonId}`;
+}
+
+async function balance(userId, anonId) {
+ const where = minerClause(userId, anonId);
+ const [rows, recent] = await Promise.all([
+ sql`select gem, sum(amount)::int as amount from world_gems where ${where} group by gem`,
+ sql`select gem, node, amount, mined_at from world_gems where ${where} order by mined_at desc limit 12`,
+ ]);
+ return { ...summarize(rows), recent };
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const ip = clientIp(req);
+ const rl = await limits.publicIp(ip);
+ if (!rl.success) return rateLimited(res, rl);
+
+ const url = new URL(req.url, 'http://local');
+ const userId = await resolveUserId(req);
+
+ if (req.method === 'GET') {
+ const anonId = url.searchParams.get('anonId');
+ if (!userId && !validAnonId(anonId)) {
+ return json(res, 200, { ok: true, miner: null, ...summarize([]), recent: [], table: GEMS, dig_seconds: DIG_SECONDS });
+ }
+ const b = await balance(userId, userId ? null : anonId);
+ return json(res, 200, { ok: true, miner: userId ? 'account' : 'browser', ...b, table: GEMS, dig_seconds: DIG_SECONDS }, { 'cache-control': 'no-store' });
+ }
+
+ const body = (await readJson(req)) || {};
+ if (!validNode(body.node)) return error(res, 400, 'invalid_node', 'node must name a mining vein in the world');
+ const anonId = validAnonId(body.anonId) ? body.anonId : null;
+ if (!userId && !anonId) return error(res, 400, 'no_miner', 'sign in or send a browser id to keep your gems');
+
+ // Adopt the browser's anonymous gems onto the account on a signed-in dig.
+ if (userId && anonId) {
+ await sql`update world_gems set user_id = ${userId}, anon_id = null where anon_id = ${anonId} and user_id is null`;
+ }
+
+ const where = minerClause(userId, userId ? null : anonId);
+ const [last] = await sql`select max(mined_at) as last_at, count(*) filter (where mined_at >= date_trunc('day', now())) ::int as today from world_gems where ${where}`;
+ const lastMs = last?.last_at ? new Date(last.last_at).getTime() : null;
+ if (!digAllowed(lastMs, Date.now())) {
+ const wait = Math.ceil((MIN_DIG_INTERVAL_MS - (Date.now() - lastMs)) / 1000);
+ return error(res, 429, 'dig_too_soon', `the vein needs ${wait}s more`, { retry_in_sec: wait });
+ }
+ if ((last?.today || 0) >= DAILY_DIG_CAP) {
+ return error(res, 429, 'daily_cap', `you have mined ${DAILY_DIG_CAP} gems today; the veins refill at midnight UTC`);
+ }
+
+ const gem = rollGem(randomInt(0, 1_000_000) / 1_000_000);
+ await sql`insert into world_gems (user_id, anon_id, node, gem, amount) values (${userId}, ${userId ? null : anonId}, ${body.node}, ${gem.id}, 1)`;
+ const b = await balance(userId, userId ? null : anonId);
+ return json(res, 200, { ok: true, miner: userId ? 'account' : 'browser', mined: { id: gem.id, label: gem.label, points: gem.points, hex: gem.hex, node: body.node }, ...b }, { 'cache-control': 'no-store' });
+});
diff --git a/data/changelog.json b/data/changelog.json
index 7dd9b8d6d..a0710eea5 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,16 @@
{
"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security, desktop (desktop entries become the desktop app's release notes). `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-10-11",
+ "title": "Walk into three.ws: the homepage boots, unlocks, and lets you enter the desktop as your avatar",
+ "link": "/",
+ "summary": "The homepage now starts like a real computer. A boot screen runs live checks (your GPU, the site catalog, your account, the avatar body, the $THREE feed, your gem ledger) and a lock screen greets you with the $THREE price and your balances. Press Walk in and you arrive on a campus as your avatar: walk to your desk and sit down to open the desktop on the monitor, pick up the phone for Pocket, put on the headset for VR, enter the three.ws Exchange (a live ticker board and Trenches inside), the Launchpad, the Forge, the Gallery, Agent Plaza and the Marketplace, or dig for gems in the mine, where every gem is rolled server-side and kept on your account. Settings gets an Arrival section to choose where you start, the taskbar gets a World button, and the desktop wears the classic three.ws violet grid.",
+ "tags": [
+ "feature",
+ "desktop"
+ ]
+ },
{
"date": "2026-10-11",
"title": "The prompt director works again, found by its own run receipts",
diff --git a/docs/api-reference.md b/docs/api-reference.md
index 2e78d2dbc..8b3dcd681 100644
--- a/docs/api-reference.md
+++ b/docs/api-reference.md
@@ -10081,6 +10081,93 @@ Webhook events: `invoice.created`, `invoice.paid`, `invoice.underpaid`,
`invoice.expired`, `invoice.cancelled`. Full reference and examples:
[Agent Commerce](./agent-commerce.md).
+## Desktop Campus API: gem mining
+
+The homepage (`/`) boots into a 3D campus in front of the web desktop (see
+[Web Desktop](./desktop.md)). Its mine is backed by one endpoint. Everything
+that matters is decided on the server: the gem is rolled there with crypto
+randomness from a fixed table, and a dig is only accepted when the miner's
+previous dig is old enough.
+
+### Read your gem balance
+
+```
+GET /api/world/gems
+GET /api/world/gems?anonId=anon_<uuid> # visitors: the browser's walk id
+```
+
+Signed-in callers (session cookie or bearer key) read the account's ledger.
+Visitors pass the stable anonymous browser id the walk pages keep in
+`localStorage` as `twx_walk_anon` (8 to 64 characters of `A-Za-z0-9_-`). A
+visitor without an id gets an empty ledger with `miner: null`.
+
+**Response**
+
+```json
+{
+ "ok": true,
+ "miner": "browser",
+ "gems": { "quartz": 3, "amethyst": 1, "sapphire": 0, "emerald": 0, "ruby": 0, "diamond": 0 },
+ "points": 6,
+ "total": 4,
+ "recent": [{ "gem": "amethyst", "node": "vein-b", "amount": 1, "mined_at": "2026-10-11T05:20:11.000Z" }],
+ "table": [
+ { "id": "quartz", "label": "Quartz", "weight": 520, "points": 1, "hex": 15132400 },
+ { "id": "amethyst", "label": "Amethyst", "weight": 260, "points": 3, "hex": 12891645 },
+ { "id": "sapphire", "label": "Sapphire", "weight": 130, "points": 8, "hex": 6333946 },
+ { "id": "emerald", "label": "Emerald", "weight": 60, "points": 20, "hex": 3462041 },
+ { "id": "ruby", "label": "Ruby", "weight": 24, "points": 50, "hex": 16286065 },
+ { "id": "diamond", "label": "Diamond", "weight": 6, "points": 200, "hex": 16777215 }
+ ],
+ "dig_seconds": 4
+}
+```
+
+`miner` is `account`, `browser` or `null`. `gems` always lists every gem id.
+`table` is ordered common to rare; `weight` is the drop weight out of 1000,
+`hex` the gem's colour as a number, and `recent` the last 12 digs, newest
+first.
+
+### Complete a dig
+
+```
+POST /api/world/gems
+Content-Type: application/json
+
+{ "node": "vein-a", "anonId": "anon_<uuid>" }
+```
+
+`node` is one of `vein-a` to `vein-e`. A signed-in dig that also carries the
+browser's `anonId` adopts that browser's anonymous gems onto the account
+first, so gems mined before signing in are kept.
+
+**Response**
+
+```json
+{
+ "ok": true,
+ "miner": "browser",
+ "mined": { "id": "amethyst", "label": "Amethyst", "points": 3, "hex": 12891645, "node": "vein-a" },
+ "gems": { "quartz": 3, "amethyst": 2, "sapphire": 0, "emerald": 0, "ruby": 0, "diamond": 0 },
+ "points": 9,
+ "total": 5,
+ "recent": [{ "gem": "amethyst", "node": "vein-a", "amount": 1, "mined_at": "2026-10-11T05:21:03.000Z" }]
+}
+```
+
+| Status | `error` | Meaning |
+| --- | --- | --- |
+| 400 | `invalid_node` | `node` is not a known vein |
+| 400 | `no_miner` | Not signed in and no valid `anonId`, so there is nowhere to keep the gem |
+| 429 | `dig_too_soon` | The previous dig is younger than the dig time; `retry_in_sec` says how long to wait |
+| 429 | `daily_cap` | 300 digs already today (UTC) for this miner |
+
+Rate limited per IP like the other public endpoints. The client holds E at a
+vein for `dig_seconds` of real frame time before posting; the server enforces
+the same cadence, so a client that posts early is refused.
+
+---
+
## Pagination
Paginated list endpoints use `limit`/`offset` query parameters unless noted otherwise (each endpoint's own parameter table is authoritative; some small per-user lists, like `/api/agents` and `/api/widgets`, return everything with no pagination).
diff --git a/docs/desktop.md b/docs/desktop.md
index 8e13ee116..483d3eab9 100644
--- a/docs/desktop.md
+++ b/docs/desktop.md
@@ -1,8 +1,75 @@
# three.ws Desktop
-`/` is a web desktop. Every window frames a real three.ws page, so nothing is
-mocked and every existing surface works unchanged. The previous homepage is
-kept at `/classic`.
+`/` is a web desktop with a 3D campus in front of it. The page boots like a
+computer, locks with a greeting, and then the visitor walks to their desk as
+their avatar and sits down; the desktop opens on the monitor. Every window
+frames a real three.ws page, so nothing is mocked and every existing surface
+works unchanged. The previous homepage is kept at `/classic`.
+
+## Arriving
+
+1. **Boot.** A live log of real checks, each line timed as it settles: Graphics
+ (the GPU name, from WebGL), Site catalog (the page count from
+ `public/nav-data.js`), Account (`/api/auth/me`, skipped when signed out),
+ Fonts, Avatar (the default body and the clip manifest), the $THREE feed
+ (`/api/three-token/stats`), the Gem ledger (`/api/world/gems`) and the
+ Desktop itself. A check that fails is marked and the lock screen says which
+ one is offline; nothing is faked and there is no timed progress bar. The
+ checks run concurrently, so the boot takes as long as the slowest request.
+2. **Lock screen.** A greeting for the hour (with your name once you set one in
+ Settings or sign in), the $THREE price and 24h change, your gem balance and
+ your account, and two ways in: **Walk in** (the campus) or **Desktop**. The
+ first gesture also unlocks the startup chime, a short synthesised chord
+ (Settings, Arrival, Startup chime turns it off).
+3. **The campus.** You spawn at the gate facing your workstation. Walk up to
+ the desk and the prompt says Sit down; hold E and the camera settles into the
+ chair while the desktop fades in on the monitor. The taskbar's World button
+ (also in the Start menu footer and the desktop right-click menu) stands you
+ back up where you were.
+
+Controls: WASD or the arrow keys to walk, Shift to run, drag to orbit, wheel to
+zoom, C cycles the camera (Follow, Cinematic, and the rest of the shared camera
+modes), E interacts, Esc puts the phone down. On a phone the campus shows a
+touch stick and an on-screen interact button. The strip along the bottom lists
+every place; tap one to teleport to its doorstep.
+
+## The campus
+
+| Place | What it is | What E does |
+| --- | --- | --- |
+| Your workstation | The home office: desk, monitor, phone, VR headset | Sit down opens the desktop on the monitor. Step round to the phone to pick up Pocket (the handheld agent console, framed as `/pocket?chrome=off`). Step round to the headset to enter the world in WebXR when the browser offers an immersive session; the button is hidden otherwise. |
+| three.ws Exchange | The trading floor, with a ticker board scrolling $THREE and the top market coins | Opens Trenches (live Solana launches, runners and smart money) |
+| Launchpad | The launch tower | Opens the pump.fun Launchpad |
+| The Mine | A quarry with five glowing veins | Hold E at a vein for four seconds to dig. The server rolls the gem (quartz, amethyst, sapphire, emerald, ruby, diamond, rarest last) and enforces the cadence; the gem panel in the HUD keeps the running balance and points. |
+| The Forge | Text to 3D | Opens Forge |
+| Gallery | Every public avatar | Opens Gallery |
+| Agent Plaza | The agent directory | Opens Discover |
+| Marketplace | Agent skills | Opens Marketplace |
+
+The ticker board reads `/api/three-token/stats` and `/api/coin/markets` and
+refreshes every minute; when a feed is down the board says so instead of
+showing stale numbers. Places, keep-out radii, the veins and the desk-object
+trigger distances live in `src/desktop/world/places.js`, which is pure data
+and unit tested, so a place can never point at an app the desktop does not
+have.
+
+Walking into a place opens its app as a window and sits you at the desk; the
+World button brings you back to that place's doorstep, not the gate. Your
+avatar is the same default body and clip library the rest of the site uses
+(`/avatars/default.glb`, `/animations/manifest.json`).
+
+### Gems
+
+`GET /api/world/gems` returns the caller's balance (`gems` by id, `points`,
+`total`, `recent`, the gem `table` and `dig_seconds`). `POST /api/world/gems`
+with `{ node: "vein-a" }` completes a dig and returns the gem. Visitors mine
+under the stable anonymous browser id the walk pages use (`twx_walk_anon`,
+sent as `anonId`); a signed-in dig that carries that id adopts the browser's
+gems onto the account, so nothing mined before signing in is lost. The server
+refuses a dig that comes sooner than the dig time allows (`429 dig_too_soon`,
+with `retry_in_sec`), stops at 300 digs a day (`429 daily_cap`) and rejects an
+unknown vein (`400 invalid_node`). Table and rules: `api/_lib/world-gems.js`;
+storage: migration `20261015000000_world_gems.sql`.
## What is in it
@@ -26,15 +93,19 @@ kept at `/classic`.
- **Rubber band.** Drag on the empty desktop to draw a selection box; Ctrl or Shift adds to the current selection.
- **Right-click.** The desktop menu sets icon size, sorts by name, auto-arranges, refreshes, and opens All Apps and Personalize. Icon menus open or remove the selection.
- **All Apps.** A native app listing every app and page from the site navigation, with Open and Add to desktop for each.
-- **Settings.** Profile (name, avatar colour), Personalization (dark, light or match system, six accents, five wallpapers or your own photo), Desktop and taskbar (icon size, taskbar alignment, 24-hour clock), and Session and storage.
+- **Settings.** Profile (name, avatar colour), Arrival (start in the campus or on the desktop, startup chime, a Walk the campus button), Personalization (dark, light or match system, seven accents, six wallpapers or your own photo; the default `three.ws` wallpaper is the classic site's violet glow over a hairline grid), Desktop and taskbar (icon size, taskbar alignment, 24-hour clock), and Session and storage.
- **Session.** Open windows and their geometry, icon layout, preferences, recent apps and the custom wallpaper are saved in this browser (`tws:desktop`, `tws:icons`, `tws:prefs`, `tws:recent` in localStorage; the wallpaper image in IndexedDB database `tws-desktop`) and restored on reload. Settings can export the session to a JSON file, import one (only known `tws:` keys are accepted, files over 2 MB are refused), close all windows, or reset everything. Nothing is sent to a server.
## URLs and preferences
| What | How |
| --- | --- |
-| Open an app on load | `/?app=forge` or `/#app=forge` |
-| Force the desktop | `/?view=desktop` (also remembers the choice) |
+| Open an app on load | `/?app=forge` or `/#app=forge` (skips the campus, lands on the desktop) |
+| Walk in as your avatar | `/?world=1` or `/#world` (ignores the Arrival preference) |
+| Straight to the desktop this once | `/?world=0` |
+| Force the desktop | `/?view=desktop` (also remembers the classic-vs-desktop choice) |
+| Skip the boot screen | `/?boot=0` (tests and embeds) |
+| Where to start every time | Settings, Arrival, Start in (`startIn` in `tws:prefs`). Without WebGL the desktop opens directly and the World button is hidden. |
| Classic site | `/classic`, or the taskbar button. Remembered in `tws:view` |
| Session | Window layout is saved in `tws:desktop` and restored on reload |
@@ -53,10 +124,18 @@ until the two agree. A new skeleton or page needs no other wiring.
## Verify
-`npm run dev`, then `node scripts/desktop-smoke.mjs http://localhost:3000` boots
-the desktop in a real browser, opens the Start menu and an app, and reports
-console errors and failed requests. `npx vitest run tests/desktop-layout.test.js
-tests/desktop-page.test.js`.
+`npm run dev`, then `node scripts/desktop-world-smoke.mjs http://localhost:3000`
+drives the whole arrival in a real browser: it reads every boot line, the lock
+greeting and chips, walks in, runs to the desk and sits down, checks the
+desktop, teleports to the Exchange and opens Trenches, picks up the phone,
+opens the gem panel, cycles the camera and checks the phone layout, then
+prints every console error and every failed or 5xx request. The gem endpoint
+needs a database, so run the API locally (`PORT=3018 node --env-file=.env.local
+server/index.mjs`) and start Vite with `DEV_API_PROXY=http://localhost:3018`.
+`node scripts/desktop-smoke.mjs http://localhost:3000` is the shorter
+desktop-only drive. Unit tests: `npx vitest run tests/desktop-boot.test.js
+tests/world-places.test.js tests/world-ticker.test.js
+tests/desktop-layout.test.js tests/desktop-page.test.js`.
## Provenance
diff --git a/pages/desktop.html b/pages/desktop.html
index 3d85dfb97..06897b290 100644
--- a/pages/desktop.html
+++ b/pages/desktop.html
@@ -45,9 +45,11 @@
<li><a href="/pulse">Pulse</a>: Live feed of agent wallet activity</li>
<li><a href="/trenches">Trenches</a>: Live Solana launches, runners and smart money</li>
<li><a href="/dashboard">Console</a>: Your agents, wallets and usage</li>
+ <li><a href="/launcher">Launchpad</a>: Launch a coin on pump.fun from an agent or a prompt</li>
+ <li><a href="/pocket">Pocket</a>: A handheld agent console in a phone-sized window</li>
<li><a href="/tour">Tour</a>: A guided walk through the platform</li>
</ul>
- <p><a href="/classic">Classic website</a></p>
+ <p><a href="/classic">Classic website</a> | <a href="/?world=1">Walk in as your avatar</a> | <a href="/?view=desktop">Straight to the desktop</a></p>
<noscript><p>The desktop needs JavaScript. The links above work without it.</p></noscript>
</div>
<script type="module" src="/src/desktop/main.js"></script>
diff --git a/public/changelog-recent.json b/public/changelog-recent.json
index 61e32a3f8..bd85939ee 100644
--- a/public/changelog-recent.json
+++ b/public/changelog-recent.json
@@ -1,11 +1,11 @@
{
- "generated_at": "2026-10-11T02:11:16.227Z",
+ "generated_at": "2026-10-11T05:36:54.872Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
- "total": 3979,
+ "total": 3981,
"complete": false,
"full_feed": "/changelog.json",
"entries": [
@@ -171,6 +171,16 @@
"desktop"
]
},
+ {
+ "date": "2026-10-11",
+ "type": "update",
+ "title": "The prompt director works again, found by its own run receipts",
+ "summary": "The first receipts showed the director's brief falling back on every Studio run. The replies were arriving in 5 to 10 seconds but ran past the 1000-character prompt cap or ended on the closing constraint the director is told to end on, and both were discarded as clipped. The director now writes to a word budget the models actually follow, the guard accepts the mandated ending, both forge clients share one guard, and a receipt now names the exact reason a brief fell back (too long with its length, unfinished, no reply) instead of a generic timeout. Receipts also stop saying every stage met when a stage was skipped.",
+ "link": "/runs",
+ "tags": [
+ "fix"
+ ]
+ },
{
"date": "2026-10-11",
"type": "update",
@@ -201,6 +211,17 @@
"feature"
]
},
+ {
+ "date": "2026-10-11",
+ "type": "update",
+ "title": "Walk into three.ws: the homepage boots, unlocks, and lets you enter the desktop as your avatar",
+ "summary": "The homepage now starts like a real computer. A boot screen runs live checks (your GPU, the site catalog, your account, the avatar body, the $THREE feed, your gem ledger) and a lock screen greets you with the $THREE price and your balances. Press Walk in and you arrive on a campus as your avatar: walk to your desk and sit down to open the desktop on the monitor, pick up the phone for Pocket, put on the headset for VR, enter the three.ws Exchange (a live ticker board and Trenches inside), the Launchpad, the Forge, the Gallery, Agent Plaza and the Marketplace, or dig for gems in the mine, where every gem is rolled server-side and kept on your account. Settings gets an Arrival section to choose where you start, the taskbar gets a World button, and the desktop wears the classic three.ws violet grid.",
+ "link": "/",
+ "tags": [
+ "feature",
+ "desktop"
+ ]
+ },
{
"date": "2026-10-10",
"type": "launch",
@@ -1522,26 +1543,6 @@
"tags": [
"launch"
]
- },
- {
- "date": "2026-10-08",
- "type": "launch",
- "title": "Launch on Robinhood Chain",
- "summary": "Launch a coin on Robinhood Chain through Pons, signed by your 3D AI agent's own wallet: a live cost quote, an atomic opening buy, and an API your bots can call.",
- "link": "/launch/robinhood",
- "tags": [
- "launch"
- ]
- },
- {
- "date": "2026-10-08",
- "type": "launch",
- "title": "Paired Coins",
- "summary": "Coins on Robinhood Chain that trade against up to five assets at once: tokenized stocks, WETH, stablecoins and chain coins, each in its own bonding curve with liquidity locked forever. Live pools priced in dollars, charts per pool, every trade, a buy and sell ticket, and the AI agents that launched them.",
- "link": "/markets/robinhood/paired",
- "tags": [
- "launch"
- ]
}
]
}
diff --git a/public/changelog.json b/public/changelog.json
index 78bfa5c7d..b05ccdd14 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-10-11T02:11:16.206Z",
+ "generated_at": "2026-10-11T05:36:54.847Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -168,6 +168,16 @@
"desktop"
]
},
+ {
+ "date": "2026-10-11",
+ "type": "update",
+ "title": "The prompt director works again, found by its own run receipts",
+ "summary": "The first receipts showed the director's brief falling back on every Studio run. The replies were arriving in 5 to 10 seconds but ran past the 1000-character prompt cap or ended on the closing constraint the director is told to end on, and both were discarded as clipped. The director now writes to a word budget the models actually follow, the guard accepts the mandated ending, both forge clients share one guard, and a receipt now names the exact reason a brief fell back (too long with its length, unfinished, no reply) instead of a generic timeout. Receipts also stop saying every stage met when a stage was skipped.",
+ "link": "/runs",
+ "tags": [
+ "fix"
+ ]
+ },
{
"date": "2026-10-11",
"type": "update",
@@ -198,6 +208,17 @@
"feature"
]
},
+ {
+ "date": "2026-10-11",
+ "type": "update",
+ "title": "Walk into three.ws: the homepage boots, unlocks, and lets you enter the desktop as your avatar",
+ "summary": "The homepage now starts like a real computer. A boot screen runs live checks (your GPU, the site catalog, your account, the avatar body, the $THREE feed, your gem ledger) and a lock screen greets you with the $THREE price and your balances. Press Walk in and you arrive on a campus as your avatar: walk to your desk and sit down to open the desktop on the monitor, pick up the phone for Pocket, put on the headset for VR, enter the three.ws Exchange (a live ticker board and Trenches inside), the Launchpad, the Forge, the Gallery, Agent Plaza and the Marketplace, or dig for gems in the mine, where every gem is rolled server-side and kept on your account. Settings gets an Arrival section to choose where you start, the taskbar gets a World button, and the desktop wears the classic three.ws violet grid.",
+ "link": "/",
+ "tags": [
+ "feature",
+ "desktop"
+ ]
+ },
{
"date": "2026-10-10",
"type": "launch",
diff --git a/public/changelog.xml b/public/changelog.xml
index c79d826aa..fc3388fd2 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -134,6 +134,14 @@
<category>feature</category>
<description>Drag a selection box across the desktop, move icons on a snap grid, right-click for view options, and open every app from desktop icons or All Apps. Settings now covers your profile, theme, accent colour, wallpaper (including your own photo), icon size and taskbar, and the whole session (windows, icon layout, preferences) is saved in your browser, with export, import and reset.</description>
</item>
+ <item>
+ <title>The prompt director works again, found by its own run receipts</title>
+ <link>https://three.ws/runs</link>
+ <guid isPermaLink="false">2026-10-11:The prompt director works again, found by its own run receipts</guid>
+ <pubDate>Sun, 11 Oct 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>The first receipts showed the director's brief falling back on every Studio run. The replies were arriving in 5 to 10 seconds but ran past the 1000-character prompt cap or ended on the closing constraint the director is told to end on, and both were discarded as clipped. The director now writes to a word budget the models actually follow, the guard accepts the mandated ending, both forge clients share one guard, and a receipt now names the exact reason a brief fell back (too long with its length, unfinished, no reply) instead of a generic timeout. Receipts also stop saying every stage met when a stage was skipped.</description>
+ </item>
<item>
<title>The terminal 3D renderer animates live in every HTTP client</title>
<link>https://three.ws/tty</link>
@@ -158,6 +166,14 @@
<category>feature</category>
<description>A new Trenches page shows what is happening on Solana and Robinhood Chain right now: new launches and graduations as they happen, the hottest tokens by trade flow, and scored smart-money wallets. Every number comes from a live on-chain feed, and if the data service is unreachable the page says so instead of showing made-up figures.</description>
</item>
+ <item>
+ <title>Walk into three.ws: the homepage boots, unlocks, and lets you enter the desktop as your avatar</title>
+ <link>https://three.ws/</link>
+ <guid isPermaLink="false">2026-10-11:Walk into three.ws: the homepage boots, unlocks, and lets you enter the desktop as your avatar</guid>
+ <pubDate>Sun, 11 Oct 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The homepage now starts like a real computer. A boot screen runs live checks (your GPU, the site catalog, your account, the avatar body, the $THREE feed, your gem ledger) and a lock screen greets you with the $THREE price and your balances. Press Walk in and you arrive on a campus as your avatar: walk to your desk and sit down to open the desktop on the monitor, pick up the phone for Pocket, put on the headset for VR, enter the three.ws Exchange (a live ticker board and Trenches inside), the Launchpad, the Forge, the Gallery, Agent Plaza and the Marketplace, or dig for gems in the mine, where every gem is rolled server-side and kept on your account. Settings gets an Arrival section to choose where you start, the taskbar gets a World button, and the desktop wears the classic three.ws violet grid.</description>
+ </item>
<item>
<title>Agent Commerce</title>
<link>https://three.ws/commerce</link>
diff --git a/public/features.json b/public/features.json
index f080b4848..e5795d201 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-10-11T02:11:16.193Z",
+ "generated_at": "2026-10-11T05:36:54.831Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/scripts/desktop-world-smoke.mjs b/scripts/desktop-world-smoke.mjs
new file mode 100644
index 000000000..e232d5571
--- /dev/null
+++ b/scripts/desktop-world-smoke.mjs
@@ -0,0 +1,116 @@
+// Drives the homepage arrival in a real browser: boot log, lock screen, walking
+// in as the avatar, sitting down at the desk, coming back out, teleporting to
+// the exchange, picking up the phone, and the phone-sized layout. Reports
+// console errors and failed requests.
+// Usage: node scripts/desktop-world-smoke.mjs [baseUrl] [screenshotDir]
+import { chromium } from 'playwright';
+
+const base = process.argv[2] || 'http://localhost:3000';
+const shots = process.argv[3] || '';
+const browser = await chromium.launch({ args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'] });
+const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
+const problems = [];
+page.on('console', (m) => m.type() === 'error' && !/Failed to load resource/.test(m.text()) && problems.push(`console: ${m.text()}`));
+page.on('pageerror', (e) => problems.push(`pageerror: ${e.message}`));
+page.on('requestfailed', (r) => !/ERR_ABORTED/.test(r.failure()?.errorText || '') && problems.push(`failed: ${r.url()}`));
+page.on('response', (r) => r.status() >= 500 && problems.push(`http ${r.status()}: ${r.url()}`));
+const shot = (n) => shots && page.screenshot({ path: `${shots}/${n}.png` });
+const text = (sel) => page.locator(sel).first().textContent().then((t) => (t || '').trim());
+
+await page.goto(`${base}/`, { waitUntil: 'domcontentloaded' });
+await page.waitForSelector('.os-boot');
+await page.waitForSelector('.os-lock:not([hidden])', { timeout: 60_000 });
+const lines = await page.$$eval('.os-boot-log li', (els) => els.map((li) => `${li.dataset.state.padEnd(5)} ${li.querySelector('.os-boot-label').textContent} : ${li.querySelector('.os-boot-detail').textContent} ${li.querySelector('.os-boot-ms').textContent}`));
+console.log('boot log\n ' + lines.join('\n '));
+console.log('lock greeting:', await text('.os-lock-greet'), '|', await text('.os-lock-status'));
+console.log('lock chips:', await page.$$eval('.os-lock-chip', (els) => els.map((e) => e.textContent.trim()).join(' / ')));
+console.log('primary button:', await text('.os-lock-enter'));
+await shot('1-lock');
+
+// Walk in.
+await page.click('.os-lock-enter');
+await page.waitForSelector('.wd:not([hidden])', { timeout: 30_000 });
+await page.waitForSelector('html.in-world');
+await page.waitForFunction(() => !document.querySelector('.os-boot'), null, { timeout: 15_000 });
+await page.waitForTimeout(3000);
+console.log('world HUD where:', await text('.wd-where'), '| camera:', await text('.wd-cam-label'));
+console.log('places in strip:', await page.locator('.wd-place').count(), '| VR button hidden:', await page.locator('.wd-vr[hidden]').count());
+await shot('2-world-spawn');
+
+// Run to the desk (22 m at run speed) and watch the prompt arm.
+await page.mouse.click(720, 450);
+await page.keyboard.down('Shift');
+await page.keyboard.down('w');
+await page.waitForFunction(() => /sit down/i.test(document.querySelector('.wd-prompt')?.textContent || ''), null, { timeout: 15_000 }).catch(() => {});
+await page.keyboard.up('w');
+await page.keyboard.up('Shift');
+await page.waitForTimeout(400);
+console.log('prompt at desk:', await text('.wd-prompt'));
+await shot('3-at-desk');
+
+// Sit down: camera dolly into the monitor, then the desktop.
+await page.keyboard.press('e');
+await page.waitForSelector('html:not(.in-world)', { timeout: 20_000 });
+await page.waitForSelector('.os-task');
+await page.waitForTimeout(800);
+console.log('desktop wallpaper:', await page.getAttribute('.os', 'data-wall'), '| welcome window:', await page.locator('.win[data-app=welcome]').count(), '| world button:', await page.locator('.os-tray .os-tb[title="Walk the campus"]:not([hidden])').count());
+await shot('4-desktop');
+
+// Back out to the campus from the taskbar, straight to the exchange.
+await page.click('.os-tray .os-tb[title="Walk the campus"]');
+await page.waitForSelector('html.in-world');
+await page.waitForTimeout(1200);
+await page.click('.wd-place:has-text("Exchange")');
+await page.waitForFunction(() => /exchange/i.test(document.querySelector('.wd-prompt')?.textContent || ''), null, { timeout: 10_000 }).catch(() => {});
+console.log('prompt at exchange:', await text('.wd-prompt'), '| ticker boards drawn:', await page.evaluate(() => !!document.querySelector('.wd-canvas')));
+await shot('5-exchange');
+await page.keyboard.press('e');
+await page.waitForSelector('html:not(.in-world)', { timeout: 20_000 });
+await page.waitForSelector('.win[data-app=trenches]', { timeout: 20_000 });
+console.log('trenches window open:', await page.locator('.win[data-app=trenches]').count());
+await shot('6-trenches');
+
+// Back to the world: the player stands outside the exchange. Teleport home and pick up the phone.
+await page.click('.os-tray .os-tb[title="Walk the campus"]');
+await page.waitForSelector('html.in-world');
+await page.waitForTimeout(800);
+console.log('returned near:', await text('.wd-where'));
+await page.click('.wd-place:has-text("workstation")').catch(() => {});
+await page.waitForTimeout(600);
+await page.keyboard.down('w');
+await page.waitForFunction(() => /sit down/i.test(document.querySelector('.wd-prompt')?.textContent || ''), null, { timeout: 6000 }).catch(() => {});
+console.log('prompt back at desk:', await text('.wd-prompt'));
+// Slide round the desk's keep-out disc to the phone side.
+await page.keyboard.down('d');
+await page.waitForFunction(() => /phone/i.test(document.querySelector('.wd-prompt')?.textContent || ''), null, { timeout: 6000 }).catch(() => {});
+await page.keyboard.up('d');
+await page.keyboard.up('w');
+console.log('prompt near phone:', await text('.wd-prompt'));
+if (/phone/i.test(await text('.wd-prompt'))) {
+ await page.keyboard.press('e');
+ await page.waitForSelector('.wd-phone.is-open, .wd-phone:not([hidden])', { timeout: 8000 });
+ await page.waitForTimeout(2500);
+ console.log('phone iframe:', await page.locator('.wd-phone iframe').getAttribute('src'));
+ await shot('7-phone');
+ await page.keyboard.press('Escape');
+ await page.waitForTimeout(500);
+}
+
+// Gem HUD and camera cycle.
+await page.click('.wd-gems');
+await page.waitForTimeout(400);
+console.log('gem panel:', (await text('.wd-gempanel')).slice(0, 160));
+await shot('8-gems');
+await page.keyboard.press('Escape');
+await page.keyboard.press('c');
+await page.waitForTimeout(300);
+console.log('camera after C:', await text('.wd-cam-label'));
+
+// Phone-sized layout.
+await page.setViewportSize({ width: 390, height: 780 });
+await page.waitForTimeout(600);
+console.log('touch stick visible:', await page.locator('.wd-stick').isVisible(), '| dig button present:', await page.locator('.wd-digbtn').count());
+await shot('9-mobile');
+
+console.log(problems.length ? `PROBLEMS:\n${problems.join('\n')}` : 'no console errors');
+await browser.close();
diff --git a/src/desktop/README.md b/src/desktop/README.md
index 4c7fb99f5..c5c272b24 100644
--- a/src/desktop/README.md
+++ b/src/desktop/README.md
@@ -5,10 +5,20 @@ The web desktop served at `/` (page: `pages/desktop.html`). See
| File | Role |
| --- | --- |
-| `main.js` | Entry: boot, restore session, deep links |
-| `shell.js` | Taskbar, Start, widgets, calendar, menus, native apps |
+| `main.js` | Entry: runs the boot checks, shows the lock screen, then walks the visitor in as an avatar or lands them on the desktop; deep links |
+| `boot-logic.js` | Pure boot rules: concurrent boot steps with timings, entry mode (`?world=1`, `?world=0`, `?view=desktop`, deep links, WebGL, the Arrival preference), greeting, summary, GPU name (unit tested) |
+| `boot.js`, `boot.css` | The boot screen (live log of real checks) and the lock screen (greeting, $THREE, gems and account chips, Walk in / Desktop), plus the synthesised startup chime |
+| `shell.js` | Taskbar, Start, widgets, calendar, menus, native apps, the World button and the Arrival settings |
| `wm.js` | Window manager (drag, resize, snap, focus, persistence hooks) |
-| `layout.js` | Pure geometry, search ranking, state validation (unit tested) |
+| `layout.js` | Pure geometry, search ranking, state and preference validation (unit tested) |
| `apps.js` | App registry and wallpapers |
| `icons.js` | Stroke glyphs |
| `theme.css`, `desktop.css` | CTRL tokens; shell and window styles |
+| `world/index.js` | The campus controller: mounts the 3D world over the desktop, input, proximity prompts, sit-down and walk-in transitions, the phone, the VR headset, mining, the frame loop |
+| `world/campus.js` | The scene: ground, office desk, exchange, launchpad, mine, forge, gallery, plaza, market, lighting |
+| `world/places.js` | Pure campus map: places, keep-outs, veins, desk objects, trigger radii, stand points (unit tested) |
+| `world/screen.js` | The desk monitor that shows the live desktop and the sit-down camera move |
+| `world/ticker.js` | The exchange ticker board fed by `/api/three-token/stats` and `/api/coin/markets` (unit tested) |
+| `world/mine.js` | Gem mining client over `/api/world/gems` (server-rolled gems, anonymous id that adopts onto the account) |
+| `world/xr.js` | WebXR session entry for the headset |
+| `world/world.css` | HUD, prompts, phone overlay, gem panel, touch controls |
diff --git a/src/desktop/apps.js b/src/desktop/apps.js
index 87d80c962..429403270 100644
--- a/src/desktop/apps.js
+++ b/src/desktop/apps.js
@@ -137,6 +137,30 @@ export const APPS = [
desc: 'Your agents, wallets and usage',
keywords: ['dashboard', 'account', 'keys', 'billing'],
},
+ {
+ id: 'launcher',
+ title: 'Launchpad',
+ href: '/launcher',
+ hue: 24,
+ icon: 'rocket',
+ size: { w: 1080, h: 740 },
+ dock: false,
+ desktop: true,
+ desc: 'Launch a coin on pump.fun from an agent or a prompt',
+ keywords: ['launch', 'pump', 'token', 'coin', 'mint', 'solana'],
+ },
+ {
+ id: 'pocket',
+ title: 'Pocket',
+ href: '/pocket',
+ hue: 262,
+ icon: 'phone',
+ size: { w: 420, h: 820 },
+ dock: false,
+ desktop: true,
+ desc: 'A handheld agent console in a phone-sized window',
+ keywords: ['phone', 'handheld', 'cartridge', 'embed', 'mobile'],
+ },
{
id: 'tour',
title: 'Tour',
@@ -197,6 +221,7 @@ export function appById(id) {
}
export const WALLPAPERS = [
+ { id: 'three', label: 'three.ws' },
{ id: 'aurora', label: 'Aurora' },
{ id: 'midnight', label: 'Midnight' },
{ id: 'solana', label: 'Solana' },
diff --git a/src/desktop/boot-logic.js b/src/desktop/boot-logic.js
new file mode 100644
index 000000000..30208571c
--- /dev/null
+++ b/src/desktop/boot-logic.js
@@ -0,0 +1,128 @@
+// Pure rules for the desktop boot sequence and the lock screen. No DOM, no
+// timers: boot.js renders what these functions decide, and the tests pin them.
+
+/** A boot step's lifecycle. */
+export const STEP_STATES = ['pending', 'running', 'ok', 'skip', 'fail'];
+
+/**
+ * Run every boot step concurrently and report each transition. A step is
+ * `{ id, label, task }` where `task()` resolves to a detail string, an object
+ * `{ skip: 'reason' }` to report a step that was deliberately not needed, or
+ * any other value (kept as `value`; a string `detail` field on it is shown on
+ * the line), and rejects on failure. Nothing here is a fake delay: a line
+ * turns green the moment its real promise settles.
+ *
+ * @param {Array<{id:string,label:string,task:() => Promise<any>}>} steps
+ * @param {(snapshot: ReturnType<typeof snapshotOf>) => void} onUpdate
+ * @param {() => number} [now]
+ */
+export async function runBootSteps(steps, onUpdate, now = () => Date.now()) {
+ const results = steps.map((s) => ({ id: s.id, label: s.label, state: 'running', detail: '', ms: 0, value: undefined }));
+ const t0 = now();
+ const emit = () => onUpdate?.(snapshotOf(results));
+ emit();
+ await Promise.all(
+ steps.map(async (s, i) => {
+ const r = results[i];
+ try {
+ const v = await s.task();
+ r.ms = now() - t0;
+ if (v && typeof v === 'object' && 'skip' in v) {
+ r.state = 'skip';
+ r.detail = String(v.skip);
+ } else {
+ r.state = 'ok';
+ r.detail = typeof v === 'string' ? v : v && typeof v.detail === 'string' ? v.detail : '';
+ r.value = v;
+ }
+ } catch (err) {
+ r.ms = now() - t0;
+ r.state = 'fail';
+ r.detail = (err && err.message) || 'failed';
+ }
+ emit();
+ }),
+ );
+ return snapshotOf(results);
+}
+
+/** Progress (0..1) and counts for a set of step results. */
+export function snapshotOf(results) {
+ const done = results.filter((r) => r.state !== 'pending' && r.state !== 'running');
+ const failed = results.filter((r) => r.state === 'fail');
+ return {
+ steps: results,
+ done: done.length,
+ total: results.length,
+ progress: results.length ? done.length / results.length : 1,
+ failed: failed.map((r) => r.id),
+ complete: done.length === results.length,
+ };
+}
+
+/** Right-aligned timing column for a boot line. */
+export function formatMs(ms) {
+ if (!Number.isFinite(ms) || ms < 0) return '';
+ return ms >= 1000 ? `${(ms / 1000).toFixed(2)}s` : `${Math.round(ms)}ms`;
+}
+
+/** The greeting on the lock screen. `hour` is local 0..23. */
+export function greeting(hour, name, returning) {
+ const h = Number.isFinite(hour) ? hour : 12;
+ const part = h < 5 ? 'Still up' : h < 12 ? 'Good morning' : h < 17 ? 'Good afternoon' : h < 22 ? 'Good evening' : 'Working late';
+ const who = (name || '').trim();
+ if (who) return `${part}, ${who}.`;
+ return returning ? `${part}. Welcome back.` : `${part}. Welcome to three.ws.`;
+}
+
+/**
+ * Decide how the visitor enters. `world` means boot, lock, then walk to the
+ * computer as an avatar; `desktop` means boot, lock, then the desktop at once.
+ * Deep links and explicit view choices always win so a shared `/?app=forge`
+ * link never strands someone in a 3D lobby.
+ */
+export function entryMode({ search = '', hash = '', prefs = {}, webgl = true, deepLink = null, mobile = false } = {}) {
+ const q = new URLSearchParams(search || '');
+ if (q.get('world') === '1' || hash === '#world') return webgl ? 'world' : 'desktop';
+ if (q.get('world') === '0' || q.get('view') === 'desktop' || deepLink) return 'desktop';
+ if (!webgl) return 'desktop';
+ if (prefs.startIn === 'desktop') return 'desktop';
+ // Small screens get the world too (touch joystick), unless they opted out.
+ return mobile && prefs.startIn !== 'world' && prefs.startIn !== undefined ? 'desktop' : 'world';
+}
+
+/** Whether the boot screen itself should be shown. `?boot=0` skips it (tests, embeds). */
+export function showBoot(search = '') {
+ return new URLSearchParams(search || '').get('boot') !== '0';
+}
+
+/**
+ * Lock-screen status line: what the boot found, in one sentence.
+ * @param {{failed:string[], steps:Array<{id:string,state:string,detail:string}>}} snap
+ */
+export function bootSummary(snap, labels = {}) {
+ if (!snap) return '';
+ if (!snap.failed.length) return 'Every system is up.';
+ const names = snap.failed.map((id) => labels[id] || id);
+ return names.length === 1 ? `${names[0]} is offline. Everything else is up.` : `${names.slice(0, -1).join(', ')} and ${names.at(-1)} are offline.`;
+}
+
+/**
+ * A short GPU name for the Graphics line from WEBGL_debug_renderer_info, e.g.
+ * "ANGLE (NVIDIA, NVIDIA GeForce RTX 3080 Direct3D11 vs_5_0 ps_5_0, D3D11)"
+ * becomes "NVIDIA GeForce RTX 3080" and "Google, Vulkan 1.3.0 (SwiftShader
+ * Device (Subzero))" becomes "SwiftShader Device".
+ */
+export function gpuName(raw, max = 40) {
+ let s = String(raw || '').trim();
+ if (!s) return 'WebGL';
+ s = s.replace(/^ANGLE\s*\((.*)\)$/s, '$1');
+ const parts = s.split(/,\s*/);
+ let name = parts.length > 1 ? parts[1] : parts[0];
+ if (name.includes(':')) name = name.split(':').pop().trim();
+ const sw = name.match(/\((SwiftShader[^()]*)/i);
+ if (sw) name = sw[1];
+ name = name.replace(/\s+(Direct3D|OpenGL|Vulkan|Metal|D3D)\S*.*$/i, '').replace(/\s*\(.*$/, '').trim();
+ if (!name) name = parts[0];
+ return name.length > max ? `${name.slice(0, max - 1).trimEnd()}…` : name;
+}
diff --git a/src/desktop/boot.css b/src/desktop/boot.css
new file mode 100644
index 000000000..6116348db
--- /dev/null
+++ b/src/desktop/boot.css
@@ -0,0 +1,365 @@
+/* Boot and lock screens for the three.ws desktop. Classic site palette: near
+ * black, hairline strokes, Space Grotesk display, JetBrains Mono for the log. */
+
+.os-boot {
+ position: fixed;
+ inset: 0;
+ z-index: 1000;
+ background: #050505;
+ color: #fff;
+ font: 14px/1.5 'Inter', system-ui, sans-serif;
+ -webkit-font-smoothing: antialiased;
+ overflow: hidden;
+ transition: opacity 0.7s ease, transform 0.9s cubic-bezier(0.2, 0.8, 0.2, 1);
+ user-select: none;
+ -webkit-user-select: none;
+}
+.os-boot.is-leaving {
+ opacity: 0;
+ transform: scale(1.04);
+ pointer-events: none;
+}
+.os-boot.reduced,
+.os-boot.reduced * {
+ animation: none !important;
+ transition: none !important;
+}
+.os-boot *,
+.os-boot *::before,
+.os-boot *::after {
+ box-sizing: border-box;
+}
+.os-boot :where(button) {
+ font: inherit;
+ color: inherit;
+ background: none;
+ border: 0;
+ cursor: pointer;
+}
+.os-boot :focus-visible {
+ outline: 2px solid #c4b5fd;
+ outline-offset: 3px;
+}
+
+.os-boot-glow {
+ position: absolute;
+ inset: -20%;
+ background:
+ radial-gradient(40% 35% at 50% 38%, rgba(196, 181, 253, 0.16), transparent 70%),
+ radial-gradient(30% 30% at 20% 90%, rgba(99, 102, 241, 0.1), transparent 70%);
+ animation: os-boot-breathe 9s ease-in-out infinite alternate;
+}
+@keyframes os-boot-breathe {
+ to {
+ transform: translate3d(2%, -2%, 0) scale(1.06);
+ }
+}
+.os-boot-grid {
+ position: absolute;
+ inset: 0;
+ background-image:
+ linear-gradient(rgba(255, 255, 255, 0.045) 1px, transparent 1px),
+ linear-gradient(90deg, rgba(255, 255, 255, 0.045) 1px, transparent 1px);
+ background-size: 56px 56px;
+ mask-image: radial-gradient(70% 70% at 50% 45%, #000 20%, transparent 100%);
+ -webkit-mask-image: radial-gradient(70% 70% at 50% 45%, #000 20%, transparent 100%);
+}
+
+.os-boot-stage {
+ position: absolute;
+ inset: 0;
+ display: grid;
+ grid-template-rows: 1fr auto auto auto;
+ gap: 20px;
+ padding: clamp(20px, 5vh, 56px) clamp(16px, 6vw, 96px);
+ max-width: 1100px;
+ margin: 0 auto;
+ transition: opacity 0.5s ease, transform 0.6s ease;
+}
+.os-boot-stage[data-phase='lock'] {
+ opacity: 0;
+ transform: translateY(-18px);
+ pointer-events: none;
+}
+.os-boot-brand {
+ align-self: center;
+ animation: os-boot-rise 0.9s cubic-bezier(0.2, 0.8, 0.2, 1) both;
+}
+@keyframes os-boot-rise {
+ from {
+ opacity: 0;
+ transform: translateY(16px);
+ }
+}
+.os-boot-eyebrow,
+.os-lock-chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ padding: 5px 12px;
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ border-radius: 999px;
+ font: 500 12px/1 'JetBrains Mono', ui-monospace, monospace;
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ color: rgba(255, 255, 255, 0.72);
+}
+.os-boot-eyebrow::before {
+ content: '';
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: #c4b5fd;
+ box-shadow: 0 0 12px #c4b5fd;
+ animation: os-boot-pulse 1.4s ease-in-out infinite;
+}
+@keyframes os-boot-pulse {
+ 50% {
+ opacity: 0.35;
+ }
+}
+.os-boot-h,
+.os-lock-greet,
+.os-lock-clock {
+ font-family: 'Space Grotesk', 'Inter', system-ui, sans-serif;
+ letter-spacing: -0.03em;
+ margin: 0;
+}
+.os-boot-h {
+ margin-top: 18px;
+ font-size: clamp(32px, 5.4vw, 64px);
+ line-height: 1.02;
+ font-weight: 600;
+ max-width: 14ch;
+}
+.os-boot-h em {
+ font-style: normal;
+ color: rgba(255, 255, 255, 0.45);
+ font-weight: 500;
+}
+.os-boot-sub {
+ margin: 14px 0 0;
+ color: rgba(255, 255, 255, 0.6);
+ font-size: 15px;
+}
+
+.os-boot-log {
+ list-style: none;
+ margin: 0;
+ padding: 14px 16px;
+ max-height: min(38vh, 300px);
+ overflow: auto;
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 12px;
+ background: rgba(255, 255, 255, 0.02);
+ font: 12.5px/1.9 'JetBrains Mono', ui-monospace, monospace;
+ color: rgba(255, 255, 255, 0.78);
+ scrollbar-width: thin;
+}
+.os-boot-log li {
+ display: grid;
+ grid-template-columns: 5ch minmax(9ch, 15ch) 1fr auto;
+ gap: 14px;
+ align-items: baseline;
+ white-space: nowrap;
+ animation: os-boot-line 0.3s ease both;
+}
+@keyframes os-boot-line {
+ from {
+ opacity: 0;
+ transform: translateX(-6px);
+ }
+}
+.os-boot-log b {
+ font-weight: 600;
+ color: rgba(255, 255, 255, 0.4);
+}
+.os-boot-log li[data-state='ok'] b {
+ color: #34d399;
+}
+.os-boot-log li[data-state='skip'] b {
+ color: #c4b5fd;
+}
+.os-boot-log li[data-state='fail'] b {
+ color: #f87171;
+}
+.os-boot-log li[data-state='running'] b {
+ color: #fff;
+ animation: os-boot-pulse 0.8s ease-in-out infinite;
+}
+.os-boot-label {
+ color: #fff;
+}
+.os-boot-detail {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ color: rgba(255, 255, 255, 0.55);
+}
+.os-boot-ms {
+ color: rgba(255, 255, 255, 0.35);
+ font-variant-numeric: tabular-nums;
+}
+.os-boot-bar {
+ position: relative;
+ height: 2px;
+ background: rgba(255, 255, 255, 0.1);
+ border-radius: 2px;
+ overflow: hidden;
+}
+.os-boot-bar i {
+ position: absolute;
+ inset: 0 auto 0 0;
+ width: 0;
+ background: linear-gradient(90deg, #fff, #c4b5fd);
+ box-shadow: 0 0 16px rgba(196, 181, 253, 0.6);
+ transition: width 0.35s cubic-bezier(0.2, 0.8, 0.2, 1);
+}
+.os-boot-foot {
+ display: flex;
+ justify-content: space-between;
+ margin: 0;
+ font: 12px/1 'JetBrains Mono', ui-monospace, monospace;
+ color: rgba(255, 255, 255, 0.45);
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+}
+
+/* ---------- lock ---------- */
+.os-lock {
+ position: absolute;
+ inset: 0;
+ display: grid;
+ grid-template-rows: 1fr auto 1fr;
+ justify-items: center;
+ padding: clamp(20px, 6vh, 64px) 16px;
+ animation: os-boot-rise 0.8s cubic-bezier(0.2, 0.8, 0.2, 1) both;
+}
+.os-lock-top {
+ text-align: center;
+ align-self: end;
+ padding-bottom: 28px;
+}
+.os-lock-clock {
+ display: block;
+ font-size: clamp(64px, 12vw, 132px);
+ line-height: 0.95;
+ font-weight: 600;
+ font-variant-numeric: tabular-nums;
+ text-shadow: 0 0 60px rgba(196, 181, 253, 0.25);
+}
+.os-lock-date {
+ margin-top: 10px;
+ font-size: 17px;
+ color: rgba(255, 255, 255, 0.62);
+}
+.os-lock-card {
+ width: min(100%, 460px);
+ padding: 28px 28px 22px;
+ border-radius: 20px;
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ background: linear-gradient(180deg, rgba(255, 255, 255, 0.05), rgba(255, 255, 255, 0.02));
+ backdrop-filter: blur(20px) saturate(1.4);
+ text-align: center;
+ box-shadow: 0 30px 90px rgba(0, 0, 0, 0.55);
+}
+.os-lock-avatar {
+ display: grid;
+ place-items: center;
+ width: 64px;
+ height: 64px;
+ margin: 0 auto 14px;
+ border-radius: 50%;
+ background: radial-gradient(circle at 30% 30%, hsl(var(--hue, 262) 70% 72%), hsl(var(--hue, 262) 60% 38%));
+ font: 600 22px/1 'Space Grotesk', sans-serif;
+ font-style: normal;
+ box-shadow: 0 0 0 4px rgba(255, 255, 255, 0.06), 0 10px 30px rgba(0, 0, 0, 0.4);
+}
+.os-lock-greet {
+ font-size: 26px;
+ font-weight: 600;
+}
+.os-lock-status {
+ margin: 8px 0 20px;
+ color: rgba(255, 255, 255, 0.6);
+ font-size: 14px;
+}
+.os-lock-actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 10px;
+ justify-content: center;
+}
+.os-lock-enter,
+.os-lock-skip {
+ padding: 12px 22px;
+ border-radius: 999px;
+ font-weight: 600;
+ font-size: 14px;
+ transition: transform 0.15s ease, background 0.2s ease, box-shadow 0.2s ease;
+}
+.os-lock-enter {
+ background: #fff;
+ color: #050505;
+ box-shadow: 0 8px 30px rgba(255, 255, 255, 0.18);
+}
+.os-lock-enter:hover {
+ transform: translateY(-1px);
+ box-shadow: 0 12px 36px rgba(196, 181, 253, 0.35);
+}
+.os-lock-enter:active {
+ transform: translateY(0) scale(0.98);
+}
+.os-lock-skip {
+ border: 1px solid rgba(255, 255, 255, 0.14);
+ color: rgba(255, 255, 255, 0.85);
+}
+.os-lock-skip:hover {
+ background: rgba(255, 255, 255, 0.07);
+}
+.os-lock-skip:active {
+ transform: scale(0.98);
+}
+.os-lock-hint {
+ margin: 18px 0 0;
+ font-size: 12.5px;
+ line-height: 1.55;
+ color: rgba(255, 255, 255, 0.48);
+}
+.os-lock-chips {
+ align-self: end;
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+ justify-content: center;
+}
+.os-lock-chip {
+ text-transform: none;
+ letter-spacing: 0;
+ gap: 10px;
+ padding: 7px 12px;
+}
+.os-lock-chip small {
+ font-size: 11px;
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ color: rgba(255, 255, 255, 0.45);
+}
+.os-lock-chip b {
+ font-weight: 600;
+ color: #fff;
+ font-variant-numeric: tabular-nums;
+}
+@media (max-width: 640px) {
+ .os-boot-stage {
+ gap: 14px;
+ }
+ .os-boot-log li {
+ grid-template-columns: 5ch 1fr auto;
+ }
+ .os-boot-log .os-boot-detail {
+ display: none;
+ }
+ .os-lock-card {
+ padding: 22px 18px 18px;
+ }
+}
diff --git a/src/desktop/boot.js b/src/desktop/boot.js
new file mode 100644
index 000000000..05ec31efa
--- /dev/null
+++ b/src/desktop/boot.js
@@ -0,0 +1,213 @@
+// The desktop's boot and lock screens. The boot log is driven by real promises
+// (graphics probe, catalog, account, fonts, avatar, market feed, gem ledger,
+// shell); each line settles when its request does. The lock screen then holds
+// until the visitor's first gesture, which is also what lets the chime play.
+
+import { formatMs, greeting, bootSummary } from './boot-logic.js';
+
+const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
+
+const STATE_TAG = { pending: ' ', running: ' .. ', ok: ' OK ', skip: 'SKIP', fail: 'FAIL' };
+
+/**
+ * @param {{ host?: HTMLElement, reducedMotion?: boolean }} [opts]
+ */
+export function createBootScreen({ host = document.body, reducedMotion = false } = {}) {
+ const el = document.createElement('div');
+ el.className = 'os-boot';
+ el.setAttribute('role', 'dialog');
+ el.setAttribute('aria-label', 'three.ws is starting');
+ el.setAttribute('aria-live', 'polite');
+ if (reducedMotion) el.classList.add('reduced');
+ el.innerHTML = `
+ <div class="os-boot-glow" aria-hidden="true"></div>
+ <div class="os-boot-grid" aria-hidden="true"></div>
+ <section class="os-boot-stage" data-phase="boot">
+ <div class="os-boot-brand">
+ <span class="os-boot-eyebrow">three.ws OS</span>
+ <h1 class="os-boot-h">The 3D agent layer <em>of the internet.</em></h1>
+ <p class="os-boot-sub">Starting your workstation.</p>
+ </div>
+ <ol class="os-boot-log" aria-label="Startup checks"></ol>
+ <div class="os-boot-bar" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><i></i></div>
+ <p class="os-boot-foot"><span class="os-boot-count">0 / 0</span><span class="os-boot-status">Probing</span></p>
+ </section>
+ <section class="os-lock" hidden>
+ <div class="os-lock-top">
+ <time class="os-lock-clock"></time>
+ <div class="os-lock-date"></div>
+ </div>
+ <div class="os-lock-card">
+ <i class="os-lock-avatar" aria-hidden="true"></i>
+ <h2 class="os-lock-greet"></h2>
+ <p class="os-lock-status"></p>
+ <div class="os-lock-actions">
+ <button type="button" class="os-lock-enter"></button>
+ <button type="button" class="os-lock-skip"></button>
+ </div>
+ <p class="os-lock-hint"></p>
+ </div>
+ <div class="os-lock-chips"></div>
+ </section>`;
+ host.append(el);
+
+ const log = el.querySelector('.os-boot-log');
+ const bar = el.querySelector('.os-boot-bar');
+ const count = el.querySelector('.os-boot-count');
+ const status = el.querySelector('.os-boot-status');
+ const lines = new Map();
+
+ function update(snap) {
+ for (const s of snap.steps) {
+ let li = lines.get(s.id);
+ if (!li) {
+ li = document.createElement('li');
+ li.dataset.state = s.state;
+ li.innerHTML = `<b></b><span class="os-boot-label">${esc(s.label)}</span><span class="os-boot-detail"></span><span class="os-boot-ms"></span>`;
+ log.append(li);
+ lines.set(s.id, li);
+ }
+ li.dataset.state = s.state;
+ li.querySelector('b').textContent = `[${STATE_TAG[s.state] || ' '}]`;
+ li.querySelector('.os-boot-detail').textContent = s.detail || (s.state === 'running' ? 'waiting' : '');
+ li.querySelector('.os-boot-ms').textContent = s.ms ? formatMs(s.ms) : '';
+ }
+ const pct = Math.round(snap.progress * 100);
+ bar.setAttribute('aria-valuenow', String(pct));
+ bar.firstElementChild.style.width = `${pct}%`;
+ count.textContent = `${snap.done} / ${snap.total}`;
+ status.textContent = snap.complete ? (snap.failed.length ? 'Ready, with warnings' : 'Ready') : 'Starting';
+ log.scrollTop = log.scrollHeight;
+ }
+
+ // ---- lock screen ----
+ const lock = el.querySelector('.os-lock');
+ const stage = el.querySelector('.os-boot-stage');
+ const clock = lock.querySelector('.os-lock-clock');
+ const date = lock.querySelector('.os-lock-date');
+ let clockTimer = 0;
+ let clock24 = false;
+ function tick() {
+ const d = new Date();
+ clock.textContent = d.toLocaleTimeString([], { hour: clock24 ? '2-digit' : 'numeric', minute: '2-digit', hour12: !clock24 });
+ clock.dateTime = d.toISOString();
+ date.textContent = d.toLocaleDateString([], { weekday: 'long', month: 'long', day: 'numeric' });
+ }
+
+ /**
+ * Switch to the lock screen and resolve with 'world' | 'desktop' on the
+ * visitor's gesture.
+ * @param {{ name?: string, returning?: boolean, mode: 'world'|'desktop', snap: object, labels: object, chips?: Array<{label:string,value:string}>, clock24?: boolean, hue?: number, initials?: string }} o
+ */
+ function toLock(o) {
+ clock24 = !!o.clock24;
+ tick();
+ clockTimer = setInterval(tick, 1000);
+ lock.querySelector('.os-lock-greet').textContent = greeting(new Date().getHours(), o.name, o.returning);
+ lock.querySelector('.os-lock-status').textContent = bootSummary(o.snap, o.labels);
+ const av = lock.querySelector('.os-lock-avatar');
+ av.textContent = o.initials || '';
+ av.style.setProperty('--hue', String(o.hue ?? 262));
+ const enter = lock.querySelector('.os-lock-enter');
+ const skip = lock.querySelector('.os-lock-skip');
+ const hint = lock.querySelector('.os-lock-hint');
+ if (o.mode === 'world') {
+ enter.textContent = 'Walk in';
+ skip.textContent = 'Straight to the desktop';
+ hint.textContent = 'You arrive as your avatar. Walk to your desk and sit down to open the desktop, or explore the exchange, the launchpad and the mine first.';
+ } else {
+ enter.textContent = 'Enter';
+ skip.textContent = 'Walk in as your avatar';
+ hint.textContent = 'Press any key or click to continue.';
+ }
+ const chips = lock.querySelector('.os-lock-chips');
+ chips.replaceChildren();
+ for (const c of o.chips || []) {
+ const span = document.createElement('span');
+ span.className = 'os-lock-chip';
+ span.innerHTML = `<small>${esc(c.label)}</small><b>${esc(c.value)}</b>`;
+ chips.append(span);
+ }
+ stage.dataset.phase = 'lock';
+ lock.hidden = false;
+ enter.focus({ preventScroll: true });
+
+ return new Promise((resolve) => {
+ let settled = false;
+ const finish = (choice) => {
+ if (settled) return;
+ settled = true;
+ removeEventListener('keydown', onKey, true);
+ resolve(choice);
+ };
+ const primary = o.mode;
+ const alternate = o.mode === 'world' ? 'desktop' : 'world';
+ enter.addEventListener('click', () => finish(primary));
+ skip.addEventListener('click', () => finish(alternate));
+ function onKey(e) {
+ if (e.key === 'Tab' || e.altKey || e.metaKey || e.ctrlKey) return;
+ if (e.target === skip && (e.key === 'Enter' || e.key === ' ')) return finish(alternate);
+ e.preventDefault();
+ finish(primary);
+ }
+ addEventListener('keydown', onKey, true);
+ lock.addEventListener('click', (e) => {
+ if (e.target.closest('button')) return;
+ finish(primary);
+ });
+ });
+ }
+
+ /** Fade out and remove. Resolves when the transition ends. */
+ function dismiss() {
+ clearInterval(clockTimer);
+ el.classList.add('is-leaving');
+ return new Promise((resolve) => {
+ const done = () => {
+ el.remove();
+ resolve();
+ };
+ if (reducedMotion) return done();
+ el.addEventListener('transitionend', done, { once: true });
+ // A browser that never fires transitionend (hidden tab) still gets out.
+ el.addEventListener('animationend', done, { once: true });
+ });
+ }
+
+ return { el, update, toLock, dismiss };
+}
+
+/**
+ * The startup chime: two short sine partials, synthesised so nothing loads
+ * and it works offline. Must run inside a user gesture; returns false when the
+ * browser refused to start audio.
+ */
+export function playChime() {
+ try {
+ const Ctx = globalThis.AudioContext || globalThis.webkitAudioContext;
+ if (!Ctx) return false;
+ const ctx = new Ctx();
+ const t = ctx.currentTime;
+ const master = ctx.createGain();
+ master.gain.value = 0.0001;
+ master.connect(ctx.destination);
+ master.gain.exponentialRampToValueAtTime(0.22, t + 0.02);
+ master.gain.exponentialRampToValueAtTime(0.0001, t + 1.6);
+ [[440, 0], [659.25, 0.12], [880, 0.26]].forEach(([f, dt]) => {
+ const o = ctx.createOscillator();
+ o.type = 'sine';
+ o.frequency.value = f;
+ const g = ctx.createGain();
+ g.gain.value = 0.0001;
+ g.gain.exponentialRampToValueAtTime(0.6, t + dt + 0.03);
+ g.gain.exponentialRampToValueAtTime(0.0001, t + dt + 1.2);
+ o.connect(g).connect(master);
+ o.start(t + dt);
+ o.stop(t + dt + 1.3);
+ });
+ setTimeout(() => ctx.close().catch(() => {}), 2000);
+ return true;
+ } catch {
+ return false;
+ }
+}
diff --git a/src/desktop/desktop.css b/src/desktop/desktop.css
index 77ad186e9..afe69f4fb 100644
--- a/src/desktop/desktop.css
+++ b/src/desktop/desktop.css
@@ -62,6 +62,21 @@ body {
background-size: cover;
transition: background 0.6s;
}
+.os[data-wall='three'] .os-wall {
+ background:
+ radial-gradient(55% 45% at 50% 108%, rgba(139, 92, 246, 0.42), transparent 70%),
+ radial-gradient(40% 35% at 85% -5%, rgba(196, 181, 253, 0.14), transparent 70%),
+ linear-gradient(rgba(255, 255, 255, 0.045) 1px, transparent 1px) 0 0 / 100% 64px,
+ linear-gradient(90deg, rgba(255, 255, 255, 0.045) 1px, transparent 1px) 0 0 / 64px 100%,
+ #050505;
+}
+[data-theme='light'] .os[data-wall='three'] .os-wall {
+ background:
+ radial-gradient(55% 45% at 50% 108%, rgba(139, 92, 246, 0.28), transparent 70%),
+ linear-gradient(rgba(0, 0, 0, 0.05) 1px, transparent 1px) 0 0 / 100% 64px,
+ linear-gradient(90deg, rgba(0, 0, 0, 0.05) 1px, transparent 1px) 0 0 / 64px 100%,
+ #f4f2fb;
+}
.os[data-wall='aurora'] .os-wall {
background: radial-gradient(60% 55% at 22% 18%, #7a3fa8aa, transparent 70%),
radial-gradient(55% 60% at 82% 78%, #1f6fbfaa, transparent 70%), var(--mica);
@@ -717,6 +732,13 @@ body {
height: 34px;
border-radius: var(--siz-radius2);
}
+.sm-foot-actions {
+ display: flex;
+ gap: 4px;
+}
+.sm-world {
+ color: var(--accent);
+}
.widgets {
left: 8px;
@@ -927,8 +949,10 @@ body {
}
.native h2 {
margin: 0 0 6px;
+ font-family: 'Space Grotesk', 'Inter', system-ui, sans-serif;
font-size: 22px;
font-weight: 600;
+ letter-spacing: -0.01em;
}
.native h3 {
margin: 20px 0 8px;
@@ -1013,6 +1037,22 @@ body {
.step small {
color: var(--text2);
}
+.step-wide {
+ width: 100%;
+ text-align: left;
+ border: 1px solid color-mix(in srgb, var(--accent) 45%, transparent);
+ background: color-mix(in srgb, var(--accent) 12%, var(--card));
+}
+.step-wide:hover {
+ background: color-mix(in srgb, var(--accent) 22%, var(--card));
+}
+.step-wide > svg {
+ flex: none;
+ color: var(--accent);
+}
+.welcome-walk {
+ margin: 0 0 14px;
+}
/* ---------- Small screens ---------- */
@media (max-width: 720px) {
diff --git a/src/desktop/icons.js b/src/desktop/icons.js
index baa6be557..f925b3aea 100644
--- a/src/desktop/icons.js
+++ b/src/desktop/icons.js
@@ -31,6 +31,12 @@ const P = {
widgets: '<rect x="3.5" y="3.5" width="7" height="7" rx="1.5"/><rect x="13.5" y="3.5" width="7" height="7" rx="1.5"/><rect x="3.5" y="13.5" width="7" height="7" rx="1.5"/><path d="M17 13.5v7M13.5 17h7"/>',
power: '<path d="M12 3v8M6.3 6.8a8 8 0 1 0 11.4 0"/>',
chevron: '<path d="m9 6 6 6-6 6"/>',
+ world: '<circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3c2.8 3 4.2 6 4.2 9s-1.4 6-4.2 9c-2.8-3-4.2-6-4.2-9S9.2 6 12 3z"/>',
+ gem: '<path d="M7 3h10l4 6-9 12L3 9z"/><path d="M3 9h18M7 3l5 18L17 3M9.5 9l2.5-6 2.5 6"/>',
+ camera: '<path d="M4 8h3l2-3h6l2 3h3v11H4z"/><circle cx="12" cy="13" r="3.5"/>',
+ vr: '<path d="M3 8a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2h-4l-2-2.5-1 .01L10 17H5a2 2 0 0 1-2-2z"/><circle cx="8.5" cy="11.5" r="1.5"/><circle cx="15.5" cy="11.5" r="1.5"/>',
+ phone: '<rect x="7" y="3" width="10" height="18" rx="2"/><path d="M11 17.5h2"/>',
+ rocket: '<path d="M12 3c3 2.5 4.5 6 4.5 10L12 16l-4.5-3C7.5 9 9 5.5 12 3z"/><path d="M7.5 13 5 17l3.5-.5M16.5 13 19 17l-3.5-.5M12 16v5"/><circle cx="12" cy="9.5" r="1.5"/>',
close: '<path d="m6 6 12 12M18 6 6 18"/>',
};
diff --git a/src/desktop/layout.js b/src/desktop/layout.js
index 480afece7..56378b399 100644
--- a/src/desktop/layout.js
+++ b/src/desktop/layout.js
@@ -187,11 +187,13 @@ export const ICON_SIZES = {
medium: { w: 92, h: 100, tile: 44 },
large: { w: 112, h: 120, tile: 56 },
};
-export const ACCENTS = ['#3b91d8', '#ad6eca', '#e5484d', '#f08a24', '#2fb67c', '#d6409f'];
+export const ACCENTS = ['#8b5cf6', '#3b91d8', '#ad6eca', '#e5484d', '#f08a24', '#2fb67c', '#d6409f'];
+/** How the visitor arrives at `/`: as an avatar walking to the desk, or straight at the desktop. */
+export const START_MODES = ['world', 'desktop'];
export const MODES = ['dark', 'light', 'auto'];
export const PREFS_VERSION = 1;
export const DEFAULT_PREFS = {
- wall: 'aurora',
+ wall: 'three',
accent: ACCENTS[0],
mode: 'dark',
iconSize: 'medium',
@@ -199,6 +201,8 @@ export const DEFAULT_PREFS = {
taskbarAlign: 'center',
name: '',
avatarHue: 262,
+ startIn: 'world',
+ sound: true,
};
/** Normalise a rectangle given two corner points (any drag direction). */
@@ -353,6 +357,8 @@ export function sanitizePrefs(raw, wallpaperIds) {
taskbarAlign: d.taskbarAlign === 'left' ? 'left' : 'center',
name,
avatarHue: hue,
+ startIn: START_MODES.includes(d.startIn) ? d.startIn : DEFAULT_PREFS.startIn,
+ sound: d.sound !== false,
};
}
diff --git a/src/desktop/main.js b/src/desktop/main.js
index 81937bca8..1250e9053 100644
--- a/src/desktop/main.js
+++ b/src/desktop/main.js
@@ -1,23 +1,226 @@
-// Desktop entry: boot the shell, restore the last session, honour deep links.
+// Desktop entry: boot, lock, then either walk in as an avatar or land on the
+// desktop. Every boot line settles on a real request; the lock screen waits
+// for the visitor's gesture (which is also what unlocks the chime); deep links
+// and `?view=desktop` skip the world so a shared `/?app=forge` still opens Forge.
import './theme.css';
import './desktop.css';
+import './boot.css';
import { createShell } from './shell.js';
-import { deepLinkApp } from './layout.js';
+import { APPS } from './apps.js';
+import { deepLinkApp, initialsOf, sanitizePrefs } from './layout.js';
+import { runBootSteps, entryMode, showBoot, gpuName } from './boot-logic.js';
+import { createBootScreen, playChime } from './boot.js';
+import { isWebGLAvailable } from '../webgl-support.js';
+import { anonId } from './world/mine.js';
+
+const PREFS_KEY = 'tws:prefs';
+const AVATAR_GLB = '/avatars/default.glb';
+const CLIP_MANIFEST = '/animations/manifest.json';
+
+const reducedMotion = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
+const coarse = typeof matchMedia === 'function' && matchMedia('(pointer: coarse)').matches;
+
+function readPrefs() {
+ try {
+ return sanitizePrefs(localStorage.getItem(PREFS_KEY), []);
+ } catch {
+ return sanitizePrefs(null, []);
+ }
+}
+
+async function json(url, init) {
+ const r = await fetch(url, { credentials: 'include', ...init });
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
+ return r.json();
+}
+
+function fmtUsd(n) {
+ if (!Number.isFinite(n)) return '';
+ return n >= 1 ? `$${n.toFixed(2)}` : `$${n.toPrecision(3)}`;
+}
+function fmtPct(n) {
+ if (!Number.isFinite(n)) return '';
+ return `${n >= 0 ? '+' : ''}${n.toFixed(1)}%`;
+}
+function fmtBytes(n) {
+ return n >= 1024 * 1024 ? `${(n / 1024 / 1024).toFixed(1)} MB` : `${Math.round(n / 1024)} KB`;
+}
+
+/** The boot checks. Each resolves to the detail string shown on its line. */
+function bootSteps(root, webgl) {
+ return [
+ {
+ id: 'graphics',
+ label: 'Graphics',
+ task: async () => {
+ if (!webgl) throw new Error('WebGL unavailable, 3D campus disabled');
+ const gl = document.createElement('canvas').getContext('webgl2') || document.createElement('canvas').getContext('webgl');
+ const dbg = gl?.getExtension('WEBGL_debug_renderer_info');
+ const name = dbg ? String(gl.getParameter(dbg.UNMASKED_RENDERER_WEBGL)) : 'WebGL';
+ gl?.getExtension('WEBGL_lose_context')?.loseContext();
+ return gpuName(name);
+ },
+ },
+ {
+ id: 'catalog',
+ label: 'Site catalog',
+ task: async () => {
+ const r = await fetch('/nav-data.js');
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
+ const text = await r.text();
+ const n = (text.match(/href:\s*'/g) || []).length;
+ return n ? `${n} pages` : 'loaded';
+ },
+ },
+ {
+ id: 'account',
+ label: 'Account',
+ task: async () => {
+ const data = await json('/api/auth/me');
+ const u = data && data.user;
+ if (!u) return { skip: 'signed out' };
+ const name = u.display_name || u.username || '';
+ return { name, detail: name ? `signed in as ${name}` : 'signed in' };
+ },
+ },
+ {
+ id: 'fonts',
+ label: 'Fonts',
+ task: async () => {
+ if (!document.fonts) return { skip: 'system fonts' };
+ await document.fonts.ready;
+ return `${document.fonts.size} faces`;
+ },
+ },
+ {
+ id: 'avatar',
+ label: 'Avatar',
+ task: async () => {
+ if (!webgl) return { skip: 'no 3D' };
+ const [glb, manifest] = await Promise.all([fetch(AVATAR_GLB), fetch(CLIP_MANIFEST)]);
+ if (!glb.ok) throw new Error(`body HTTP ${glb.status}`);
+ const bytes = (await glb.arrayBuffer()).byteLength;
+ const clips = manifest.ok ? (await manifest.json()).length : 0;
+ return `${fmtBytes(bytes)} body, ${clips} clips`;
+ },
+ },
+ {
+ id: 'market',
+ label: '$THREE feed',
+ task: async () => {
+ const data = await json('/api/three-token/stats', { credentials: 'omit' });
+ const t = data && data.token;
+ if (!t || !Number.isFinite(Number(t.price_usd))) throw new Error('no price');
+ const price = Number(t.price_usd);
+ const change = Number(t.price_change_24h);
+ return { price, change, detail: `${fmtUsd(price)} ${fmtPct(change)}`.trim() };
+ },
+ },
+ {
+ id: 'gems',
+ label: 'Gem ledger',
+ task: async () => {
+ const data = await json(`/api/world/gems?anonId=${encodeURIComponent(anonId())}`);
+ const points = Number(data.points) || 0;
+ const total = Number(data.total) || 0;
+ return { points, total, detail: total ? `${total} gems, ${points} pts` : 'empty ledger' };
+ },
+ },
+ {
+ id: 'shell',
+ label: 'Desktop',
+ task: async () => {
+ const shell = await createShell(root);
+ return { shell, detail: 'session restored' };
+ },
+ },
+ ];
+}
+
+function stepValue(snap, id) {
+ return snap.steps.find((s) => s.id === id)?.value;
+}
async function main() {
const root = document.getElementById('os');
if (!root) return;
- const shell = await createShell(root);
+ const webgl = isWebGLAvailable();
+ const prefs = readPrefs();
+ const wanted = deepLinkApp(location.search, location.hash);
+ const mode = entryMode({ search: location.search, hash: location.hash, prefs, webgl, deepLink: wanted, mobile: coarse && innerWidth < 760 });
+ const boot = showBoot(location.search) ? createBootScreen({ reducedMotion }) : null;
+
+ const steps = bootSteps(root, webgl);
+ const snap = await runBootSteps(steps, (s) => boot?.update(s));
+ const shell = stepValue(snap, 'shell')?.shell;
+ if (!shell) throw new Error(snap.steps.find((s) => s.id === 'shell')?.detail || 'shell failed');
document.documentElement.classList.add('os-ready');
+ const account = stepValue(snap, 'account');
+ const name = account?.name || shell.prefs.name || '';
+ const market = stepValue(snap, 'market');
+ const gems = stepValue(snap, 'gems');
+ const chips = [];
+ if (market) chips.push({ label: '$THREE', value: `${fmtUsd(market.price)} ${fmtPct(market.change)}`.trim() });
+ if (gems) chips.push({ label: 'Gems', value: gems.total ? `${gems.total} mined, ${gems.points} pts` : 'none yet, visit the mine' });
+ chips.push({ label: 'Account', value: account?.name ? account.name : 'Guest' });
+
+ let choice = mode;
+ if (boot) {
+ const labels = Object.fromEntries(steps.map((s) => [s.id, s.label]));
+ choice = await boot.toLock({
+ name,
+ returning: !!shell.store.get(shell.KEY.welcomed),
+ mode,
+ snap,
+ labels,
+ chips,
+ clock24: shell.prefs.clock24,
+ hue: shell.prefs.avatarHue,
+ initials: initialsOf(name),
+ });
+ if (shell.prefs.sound) playChime();
+ if (choice === 'world' && !webgl) {
+ choice = 'desktop';
+ shell.toast('This browser has no WebGL, so the campus is unavailable. Opening the desktop.');
+ }
+ }
+
const restored = shell.restore();
- const wanted = deepLinkApp(location.search, location.hash);
- if (wanted && shell.hasApp(wanted)) shell.launchId(wanted);
- else if (!restored) shell.welcomeIfFirst();
+ const landOnDesktop = () => {
+ if (wanted && shell.hasApp(wanted)) shell.launchId(wanted);
+ else if (!restored) shell.welcomeIfFirst();
+ };
+
+ let world = null;
+ let lastPlace = null;
+ if (webgl) {
+ const { createWorld } = await import('./world/index.js');
+ world = createWorld({
+ shell,
+ apps: APPS.filter((a) => a.dock),
+ reducedMotion,
+ onDesktop({ app, place }) {
+ document.documentElement.classList.remove('in-world');
+ lastPlace = place || null;
+ if (app && shell.hasApp(app)) shell.launchId(app);
+ else landOnDesktop();
+ },
+ });
+ shell.onWorld = () => world.enter({ at: lastPlace && lastPlace !== 'office' ? lastPlace : null });
+ }
+
+ // The world mounts under the boot screen (its fade is already black), so
+ // the boot dissolves straight into the campus with no desktop flash.
+ if (choice === 'world' && world) await Promise.all([world.enter(), boot?.dismiss()]);
+ else {
+ if (boot) await boot.dismiss();
+ landOnDesktop();
+ }
- // `?app=` is a one-shot: drop it so a reload restores the saved layout.
- if (wanted) history.replaceState(null, '', location.pathname);
+ // `?app=` and `?world=` are one-shots: drop them so a reload restores the saved layout.
+ if (wanted || /[?&](world|boot)=/.test(location.search)) history.replaceState(null, '', location.pathname);
addEventListener('storage', (e) => {
if (e.key === shell.KEY.view && e.newValue === 'classic') location.assign('/classic');
@@ -26,6 +229,7 @@ async function main() {
main().catch((err) => {
console.error('[desktop] boot failed', err);
+ document.querySelector('.os-boot')?.remove();
const root = document.getElementById('os');
if (root) root.innerHTML = '<p style="padding:24px;color:#fff;font:15px system-ui">The desktop could not start. <a style="color:#4cc2ff" href="/classic">Open the classic site</a>.</p>';
});
diff --git a/src/desktop/shell.js b/src/desktop/shell.js
index a88bb46da..87b9d8908 100644
--- a/src/desktop/shell.js
+++ b/src/desktop/shell.js
@@ -362,6 +362,11 @@ export async function createShell(root, opts = {}) {
const tray = h('div', 'os-tray');
const btnTheme = h('button', 'os-tb', '');
btnTheme.type = 'button';
+ const btnWorld = h('button', 'os-tb', icon('world', 20));
+ btnWorld.type = 'button';
+ btnWorld.title = 'Walk the campus';
+ btnWorld.setAttribute('aria-label', 'Leave the desk and walk the three.ws campus as your avatar');
+ btnWorld.hidden = true;
const btnClassic = h('button', 'os-tb hide-sm', icon('classic', 20));
btnClassic.type = 'button';
btnClassic.title = 'Classic view';
@@ -378,7 +383,7 @@ export async function createShell(root, opts = {}) {
clock.type = 'button';
clock.setAttribute('aria-haspopup', 'dialog');
clock.setAttribute('aria-expanded', 'false');
- tray.append(btnTheme, btnClassic, chip, clock);
+ tray.append(btnTheme, btnWorld, btnClassic, chip, clock);
right.append(tray);
const isLight = () => document.documentElement.getAttribute('data-theme') === 'light';
@@ -393,6 +398,15 @@ export async function createShell(root, opts = {}) {
syncTheme();
btnClassic.addEventListener('click', goClassic);
+ // The 3D campus is optional (no WebGL, or the visitor opted out): the
+ // entry wires `onWorld` once the world exists, and every "walk" control
+ // stays hidden until then.
+ let onWorld = null;
+ btnWorld.addEventListener('click', () => onWorld?.());
+ function goWorld() {
+ if (onWorld) onWorld();
+ else toast('The 3D campus is not available in this browser.');
+ }
function goClassic() {
save();
store.set(KEY.view, 'classic');
@@ -424,6 +438,7 @@ export async function createShell(root, opts = {}) {
});
let userName = '';
let startUserEl = null;
+ let startWorldEl = null;
const displayName = () => userName || prefs.name || 'Guest';
function paintUser() {
if (!startUserEl) return;
@@ -491,12 +506,24 @@ export async function createShell(root, opts = {}) {
startUserEl = user;
paintUser();
user.addEventListener('click', () => launchId('settings', { section: 'profile' }));
+ const walk = h('button', 'sm-pwr sm-world', icon('world', 20));
+ walk.type = 'button';
+ walk.title = 'Walk the campus';
+ walk.setAttribute('aria-label', 'Leave the desk and walk the three.ws campus as your avatar');
+ walk.hidden = !onWorld;
+ walk.addEventListener('click', () => {
+ closePops();
+ goWorld();
+ });
+ startWorldEl = walk;
const pwr = h('button', 'sm-pwr', icon('classic', 20));
pwr.type = 'button';
pwr.title = 'Classic view';
pwr.setAttribute('aria-label', 'Switch to the classic website');
pwr.addEventListener('click', goClassic);
- foot.append(user, pwr);
+ const actions = h('div', 'sm-foot-actions');
+ actions.append(walk, pwr);
+ foot.append(user, actions);
el.append(search, body, foot);
let selectable = [];
@@ -722,6 +749,7 @@ export async function createShell(root, opts = {}) {
['Personalize', 'gear', () => launchId('settings', { section: 'personalize' })],
['Open Start', 'logo', () => toggleStart()],
'-',
+ ['Walk the campus', 'world', goWorld],
['Switch to classic view', 'classic', goClassic],
['Close all windows', 'close', () => wm.closeAll()],
]);
@@ -779,6 +807,7 @@ export async function createShell(root, opts = {}) {
// ---------- native apps ----------
const WALL_PREVIEW = {
+ three: 'radial-gradient(70% 60% at 50% 110%,#8b5cf6aa,transparent 70%),#050505',
aurora: 'linear-gradient(215deg,#7a3fa8,#1f6fbf)',
midnight: 'linear-gradient(180deg,#1d2b5a,#05060d)',
solana: 'linear-gradient(135deg,#14f195,#9945ff)',
@@ -1032,6 +1061,12 @@ export async function createShell(root, opts = {}) {
setRow('Alignment', 'Centre the Start button or keep it on the left.', seg([['center', 'Centre'], ['left', 'Left']], prefs.taskbarAlign, (v) => setPrefs({ taskbarAlign: v }))),
setRow('24-hour clock', 'Show the time as 14:30 instead of 2:30 PM.', toggle(prefs.clock24, (v) => setPrefs({ clock24: v }), '24-hour clock')),
);
+ pane.append(h('h3', '', 'Arrival'));
+ pane.append(
+ setRow('Start in', 'Walk to your desk as your avatar, or land on the desktop at once. A shared link with ?app= always opens the desktop.', seg([['world', 'The campus'], ['desktop', 'The desktop']], prefs.startIn, (v) => setPrefs({ startIn: v }))),
+ setRow('Startup chime', 'A short synthesised chime when you unlock. Nothing is downloaded.', toggle(prefs.sound, (v) => setPrefs({ sound: v }), 'Startup chime')),
+ setRow('Walk the campus', 'Leave the desk and explore the exchange, the launchpad and the mine as your avatar.', btn('Walk', goWorld)),
+ );
pane.append(h('h3', '', 'View'));
pane.append(setRow('Classic website', 'The original three.ws homepage. Your choice is remembered until you switch back.', btn('Open classic', goClassic)));
}
@@ -1132,12 +1167,13 @@ export async function createShell(root, opts = {}) {
body.append(wrap);
if (app.id === 'settings') return renderSettings(wrap);
if (app.id === 'apps') return renderApps(wrap);
- wrap.innerHTML = '<h2>Welcome to three.ws</h2><p>The 3D agent layer of the internet, now as a desktop. Every window is a real three.ws page: drag, resize, snap to an edge, or minimize to the taskbar.</p>';
+ wrap.innerHTML = '<h2>Welcome to three.ws</h2><p>The 3D agent layer of the internet. Give your AI a body: make a living 3D agent from a selfie, forge models from a prompt, launch a coin, trade the trenches, and embed any of it on any site with one tag. This desktop is your workstation; every window is a real three.ws page.</p>';
const steps = h('div', 'steps');
[
['create', 'Make your agent', 'Start from a selfie, a prompt or a model.'],
['forge', 'Forge a 3D model', 'Type a prompt and get a textured GLB.'],
- ['discover', 'Meet other agents', 'Browse every registered agent.'],
+ ['trenches', 'Trade the trenches', 'Live Solana launches, runners and smart money.'],
+ ['launcher', 'Launch a coin', 'Put a token on pump.fun from an agent or a prompt.'],
].forEach(([id, t, s]) => {
const a = appById(id);
const b = h('button', 'step', `${tile(a, 'sm', 17)}<div><b>${t}</b><small>${s}</small></div>`);
@@ -1146,6 +1182,13 @@ export async function createShell(root, opts = {}) {
steps.append(b);
});
wrap.append(steps);
+ const walkRow = h('p', 'welcome-walk', '');
+ const walkBtn = h('button', 'step step-wide', `${icon('world', 22)}<div><b>Walk the campus</b><small>Stand up from the desk and explore the exchange, the launchpad and the gem mine as your avatar. Sit back down at the monitor to return here.</small></div>`);
+ walkBtn.type = 'button';
+ walkBtn.hidden = !onWorld;
+ walkBtn.addEventListener('click', goWorld);
+ walkRow.append(walkBtn);
+ wrap.append(walkRow);
wrap.append(h('p', '', 'Drag on the desktop to select icons, right-click for options, and open Settings to make it yours. Press Ctrl+K to search everything.'));
}
@@ -1178,5 +1221,24 @@ export async function createShell(root, opts = {}) {
toast,
store,
KEY,
+ get prefs() {
+ return prefs;
+ },
+ setPrefs,
+ onPrefs(fn) {
+ prefsListeners.add(fn);
+ return () => prefsListeners.delete(fn);
+ },
+ displayName,
+ /** Register the 3D campus. Every "walk" control appears once this is set. */
+ set onWorld(fn) {
+ onWorld = typeof fn === 'function' ? fn : null;
+ btnWorld.hidden = !onWorld;
+ if (startWorldEl) startWorldEl.hidden = !onWorld;
+ root.querySelectorAll('.welcome-walk .step').forEach((b) => (b.hidden = !onWorld));
+ },
+ get onWorld() {
+ return onWorld;
+ },
};
}
diff --git a/src/desktop/world/campus.js b/src/desktop/world/campus.js
new file mode 100644
index 000000000..4602686af
--- /dev/null
+++ b/src/desktop/world/campus.js
@@ -0,0 +1,713 @@
+// The campus: the 3D place the visitor walks through before (and around) the
+// desktop. Low-poly, emissive, one hemisphere light and one directional light,
+// so it holds 60fps on integrated GPUs. Every building here maps to a real
+// surface in places.js; the exchange board, the monitor and the mine show live
+// data supplied by the controller (index.js).
+
+import {
+ BoxGeometry,
+ CircleGeometry,
+ Color,
+ ConeGeometry,
+ CylinderGeometry,
+ DirectionalLight,
+ Fog,
+ Group,
+ HemisphereLight,
+ Mesh,
+ MeshBasicMaterial,
+ MeshStandardMaterial,
+ OctahedronGeometry,
+ PerspectiveCamera,
+ PlaneGeometry,
+ PointLight,
+ Raycaster,
+ RingGeometry,
+ Scene,
+ TorusGeometry,
+ Vector2,
+ Vector3,
+ CanvasTexture,
+ SRGBColorSpace,
+ DoubleSide,
+ ACESFilmicToneMapping,
+} from 'three';
+import { createRenderer } from '../../webgl-support.js';
+import { makeLabelSprite, makeSkyDome, makeStars } from '../../docs-world/world.js';
+import { CAMPUS_RADIUS, DESK_OBJECTS, PLACES, VEINS, facingOf as facing, placeById } from './places.js';
+import { GEMS } from '../../../api/_lib/world-gems.js';
+
+const BG = 0x050505;
+const VIOLET = 0xc4b5fd;
+
+const hueColor = (hue, l = 0.62) => new Color().setHSL(hue / 360, 0.6, l);
+const hex = (c) => `#${c.getHexString()}`;
+
+const std = (o) => new MeshStandardMaterial({ roughness: 0.78, metalness: 0.12, ...o });
+const glow = (color, intensity = 1) => new MeshBasicMaterial({ color: new Color(color).multiplyScalar(intensity), toneMapped: false });
+
+function groundTexture() {
+ const size = 2048;
+ const canvas = document.createElement('canvas');
+ canvas.width = size;
+ canvas.height = size;
+ const g = canvas.getContext('2d');
+ const c = size / 2;
+ const px = (m) => (m / CAMPUS_RADIUS) * c; // metres to pixels
+
+ const base = g.createRadialGradient(c, c, 0, c, c, c);
+ base.addColorStop(0, '#0d0d12');
+ base.addColorStop(0.6, '#08080b');
+ base.addColorStop(1, '#050505');
+ g.fillStyle = base;
+ g.fillRect(0, 0, size, size);
+
+ // Hairline grid, the classic site's background motif.
+ g.strokeStyle = 'rgba(255,255,255,0.045)';
+ g.lineWidth = 1.5;
+ for (let m = -CAMPUS_RADIUS; m <= CAMPUS_RADIUS; m += 2) {
+ g.beginPath();
+ g.moveTo(c + px(m), 0);
+ g.lineTo(c + px(m), size);
+ g.stroke();
+ g.beginPath();
+ g.moveTo(0, c + px(m));
+ g.lineTo(size, c + px(m));
+ g.stroke();
+ }
+
+ // Paths from the gate (spawn) to the office and from the office to every place.
+ const office = placeById('office');
+ const path = (ax, az, bx, bz, w, a) => {
+ g.strokeStyle = `rgba(196,181,253,${a})`;
+ g.lineWidth = px(w);
+ g.lineCap = 'round';
+ g.beginPath();
+ g.moveTo(c + px(ax), c + px(az));
+ g.lineTo(c + px(bx), c + px(bz));
+ g.stroke();
+ };
+ path(0, CAMPUS_RADIUS - 4, office.x, office.z + 4, 3.2, 0.16);
+ for (const p of PLACES) {
+ if (p.id === 'office') continue;
+ path(office.x, office.z, p.x, p.z, 2.2, 0.1);
+ }
+ // Plaza ring around the office.
+ g.strokeStyle = 'rgba(196,181,253,0.14)';
+ g.lineWidth = px(0.5);
+ g.beginPath();
+ g.arc(c + px(office.x), c + px(office.z), px(7), 0, Math.PI * 2);
+ g.stroke();
+
+ const tex = new CanvasTexture(canvas);
+ tex.colorSpace = SRGBColorSpace;
+ tex.anisotropy = 8;
+ return tex;
+}
+
+function lamp(x, z, hue = 262) {
+ const g = new Group();
+ const post = new Mesh(new CylinderGeometry(0.05, 0.07, 3.2, 8), std({ color: 0x1a1a1f, metalness: 0.5 }));
+ post.position.y = 1.6;
+ const head = new Mesh(new BoxGeometry(0.5, 0.12, 0.5), glow(hueColor(hue, 0.7), 1.4));
+ head.position.y = 3.2;
+ g.add(post, head);
+ g.position.set(x, 0, z);
+ return g;
+}
+
+/* ---------------------------------------------------------------- office */
+
+function buildOffice(place, screenMaterial) {
+ const g = new Group();
+ const col = hueColor(place.hue);
+
+ // Floor slab and a back wall carrying the wordmark: the "room" is open so
+ // the camera can orbit freely.
+ const slab = new Mesh(new BoxGeometry(9, 0.18, 7), std({ color: 0x0f0f14, roughness: 0.6 }));
+ slab.position.y = 0.09;
+ g.add(slab);
+ const rim = new Mesh(new RingGeometry(5.3, 5.42, 64), glow(col, 0.6));
+ rim.rotation.x = -Math.PI / 2;
+ rim.position.y = 0.02;
+ g.add(rim);
+
+ const wall = new Mesh(new BoxGeometry(9, 4.2, 0.25), std({ color: 0x0a0a0d }));
+ wall.position.set(0, 2.1, -3.4);
+ g.add(wall);
+ const brand = makeLabelSprite('three.ws', 'The 3D agent layer of the internet', hex(col), 1.1);
+ brand.position.set(0, 3.2, -3.1);
+ g.add(brand);
+ // A thin violet strip at the wall foot reads as the site's hairline motif.
+ const strip = new Mesh(new BoxGeometry(9, 0.04, 0.02), glow(col, 1.2));
+ strip.position.set(0, 0.2, -3.26);
+ g.add(strip);
+
+ // Desk.
+ const top = new Mesh(new BoxGeometry(2.6, 0.06, 1.1), std({ color: 0x15151a, roughness: 0.4, metalness: 0.3 }));
+ top.position.set(0, 0.76, -0.5);
+ g.add(top);
+ for (const sx of [-1.15, 1.15]) {
+ const leg = new Mesh(new BoxGeometry(0.08, 0.74, 0.9), std({ color: 0x111115 }));
+ leg.position.set(sx, 0.37, -0.5);
+ g.add(leg);
+ }
+
+ // Monitor: stand, bezel and the live screen plane.
+ const mon = DESK_OBJECTS.find((o) => o.id === 'monitor');
+ const stand = new Mesh(new CylinderGeometry(0.035, 0.05, 0.22, 10), std({ color: 0x1c1c22, metalness: 0.5 }));
+ stand.position.set(mon.dx, 0.9, mon.dz);
+ const foot = new Mesh(new CylinderGeometry(0.22, 0.24, 0.02, 20), std({ color: 0x1c1c22, metalness: 0.5 }));
+ foot.position.set(mon.dx, 0.8, mon.dz);
+ const bezel = new Mesh(new BoxGeometry(1.44, 0.84, 0.04), std({ color: 0x0b0b0e, roughness: 0.3, metalness: 0.4 }));
+ bezel.position.set(mon.dx, 1.42, mon.dz);
+ const screen = new Mesh(new PlaneGeometry(1.36, 0.765), screenMaterial);
+ screen.position.set(mon.dx, 1.42, mon.dz + 0.021);
+ screen.userData.hit = { type: 'object', id: 'monitor' };
+ bezel.userData.hit = screen.userData.hit;
+ g.add(stand, foot, bezel, screen);
+ const screenLight = new PointLight(0x9d8cff, 0.9, 4, 2);
+ screenLight.position.set(mon.dx, 1.5, mon.dz + 0.6);
+ g.add(screenLight);
+
+ // Keyboard.
+ const kb = new Mesh(new BoxGeometry(0.62, 0.025, 0.2), std({ color: 0x18181d, roughness: 0.5 }));
+ kb.position.set(0, 0.8, -0.1);
+ g.add(kb);
+
+ // Phone: a slab with a lit screen.
+ const ph = DESK_OBJECTS.find((o) => o.id === 'phone');
+ const phoneBody = new Mesh(new BoxGeometry(0.075, 0.012, 0.155), std({ color: 0x0c0c0f, roughness: 0.3, metalness: 0.6 }));
+ phoneBody.position.set(ph.dx, 0.8, ph.dz);
+ phoneBody.rotation.y = -0.35;
+ phoneBody.userData.hit = { type: 'object', id: 'phone' };
+ const phoneScreen = new Mesh(new PlaneGeometry(0.066, 0.142), glow(0x8b5cf6, 0.9));
+ phoneScreen.rotation.x = -Math.PI / 2;
+ phoneScreen.rotation.z = -0.35;
+ phoneScreen.position.set(ph.dx, 0.807, ph.dz);
+ phoneScreen.userData.hit = phoneBody.userData.hit;
+ g.add(phoneBody, phoneScreen);
+
+ // Headset: a visor ring with a strap.
+ const hs = DESK_OBJECTS.find((o) => o.id === 'headset');
+ const visor = new Mesh(new BoxGeometry(0.22, 0.1, 0.11), std({ color: 0xe8e8ee, roughness: 0.35 }));
+ visor.position.set(hs.dx, 0.85, hs.dz);
+ visor.rotation.y = 0.4;
+ visor.userData.hit = { type: 'object', id: 'headset' };
+ const strap = new Mesh(new TorusGeometry(0.11, 0.012, 8, 24), std({ color: 0x2a2a30 }));
+ strap.position.set(hs.dx - 0.02, 0.85, hs.dz - 0.07);
+ strap.rotation.set(0, 0.4, 0);
+ strap.userData.hit = visor.userData.hit;
+ const lens = new Mesh(new PlaneGeometry(0.18, 0.06), glow(0x60a5fa, 0.8));
+ lens.position.set(hs.dx + 0.04, 0.85, hs.dz + 0.057);
+ lens.rotation.y = 0.4;
+ lens.userData.hit = visor.userData.hit;
+ g.add(visor, strap, lens);
+
+ // Chair, facing the desk.
+ const seat = new Mesh(new BoxGeometry(0.56, 0.08, 0.56), std({ color: 0x1a1a20, roughness: 0.6 }));
+ seat.position.set(0, 0.48, 0.55);
+ const back = new Mesh(new BoxGeometry(0.56, 0.7, 0.08), std({ color: 0x1a1a20, roughness: 0.6 }));
+ back.position.set(0, 0.87, 0.83);
+ const post = new Mesh(new CylinderGeometry(0.03, 0.03, 0.44, 8), std({ color: 0x2b2b33, metalness: 0.6 }));
+ post.position.set(0, 0.22, 0.55);
+ const base = new Mesh(new CylinderGeometry(0.3, 0.3, 0.03, 12), std({ color: 0x2b2b33, metalness: 0.6 }));
+ base.position.set(0, 0.015, 0.55);
+ g.add(seat, back, post, base);
+
+ g.position.set(place.x, 0, place.z);
+ return {
+ group: g,
+ screen,
+ // Where the camera goes when the visitor sits down, in world space.
+ sitFrom: new Vector3(place.x, 1.55, place.z + 1.9),
+ sitTo: new Vector3(place.x + mon.dx, 1.42, place.z + mon.dz + 0.42),
+ screenCentre: new Vector3(place.x + mon.dx, 1.42, place.z + mon.dz),
+ };
+}
+
+/* -------------------------------------------------------------- exchange */
+
+function buildExchange(place, tickerMaterial) {
+ const g = new Group();
+ const col = hueColor(place.hue);
+ const stone = std({ color: 0x1b1b21, roughness: 0.9 });
+
+ // Steps.
+ for (let i = 0; i < 3; i++) {
+ const s = new Mesh(new BoxGeometry(14 - i * 0.6, 0.22, 2.2 - i * 0.5), stone);
+ s.position.set(0, 0.11 + i * 0.22, 4.6 - i * 0.3);
+ g.add(s);
+ }
+ // Podium and hall.
+ const podium = new Mesh(new BoxGeometry(14, 0.7, 8), stone);
+ podium.position.set(0, 0.35, 0);
+ g.add(podium);
+ const hall = new Mesh(new BoxGeometry(12.4, 6, 6), std({ color: 0x0d0d11 }));
+ hall.position.set(0, 3.7, -0.8);
+ hall.userData.hit = { type: 'place', id: place.id };
+ g.add(hall);
+ // Six columns.
+ for (let i = 0; i < 6; i++) {
+ const x = -5.5 + i * 2.2;
+ const c = new Mesh(new CylinderGeometry(0.42, 0.46, 6.2, 14), std({ color: 0x26262e, roughness: 0.7 }));
+ c.position.set(x, 3.8, 2.6);
+ c.userData.hit = hall.userData.hit;
+ g.add(c);
+ const cap = new Mesh(new BoxGeometry(1.1, 0.3, 1.1), stone);
+ cap.position.set(x, 6.95, 2.6);
+ g.add(cap);
+ }
+ // Entablature and pediment.
+ const beam = new Mesh(new BoxGeometry(14, 0.9, 1.6), stone);
+ beam.position.set(0, 7.5, 2.6);
+ g.add(beam);
+ const ped = new Mesh(new ConeGeometry(7.6, 2.4, 4), stone);
+ ped.rotation.y = Math.PI / 4;
+ ped.scale.z = 0.22;
+ ped.position.set(0, 9.1, 2.6);
+ g.add(ped);
+ // The board: a live ticker across the front of the entablature, and a
+ // taller board above the hall for the second line of sight.
+ const board = new Mesh(new PlaneGeometry(13.4, 1.25), tickerMaterial);
+ board.position.set(0, 7.5, 3.42);
+ g.add(board);
+ const board2 = new Mesh(new PlaneGeometry(11, 1.0), tickerMaterial);
+ board2.position.set(0, 6.0, 2.22);
+ g.add(board2);
+ // Door glow.
+ const door = new Mesh(new PlaneGeometry(2.4, 4.2), glow(col, 0.55));
+ door.position.set(0, 2.8, 2.22);
+ door.userData.hit = hall.userData.hit;
+ g.add(door);
+ const sign = makeLabelSprite(place.title, place.sub, hex(col), 1.25);
+ sign.position.set(0, 11.6, 2.4);
+ g.add(sign);
+
+ g.position.set(place.x, 0, place.z);
+ g.rotation.y = facing(place);
+ return g;
+}
+
+/* ------------------------------------------------------------- launchpad */
+
+function buildLaunchpad(place) {
+ const g = new Group();
+ const col = hueColor(place.hue);
+ const pad = new Mesh(new CylinderGeometry(5.2, 5.4, 0.5, 32), std({ color: 0x15151a }));
+ pad.position.y = 0.25;
+ pad.userData.hit = { type: 'place', id: place.id };
+ g.add(pad);
+ const ring = new Mesh(new RingGeometry(4.3, 4.6, 48), glow(col, 0.8));
+ ring.rotation.x = -Math.PI / 2;
+ ring.position.y = 0.51;
+ g.add(ring);
+ // Rocket.
+ const rocket = new Group();
+ const body = new Mesh(new CylinderGeometry(0.9, 1.0, 6, 20), std({ color: 0xe9e9f0, roughness: 0.35, metalness: 0.25 }));
+ body.position.y = 3.5;
+ const nose = new Mesh(new ConeGeometry(0.9, 2.2, 20), std({ color: hueColor(place.hue, 0.55), roughness: 0.4 }));
+ nose.position.y = 7.6;
+ rocket.add(body, nose);
+ for (let i = 0; i < 3; i++) {
+ const fin = new Mesh(new BoxGeometry(0.12, 1.8, 1.4), std({ color: hueColor(place.hue, 0.55) }));
+ const a = (i / 3) * Math.PI * 2;
+ fin.position.set(Math.cos(a) * 1.25, 1.2, Math.sin(a) * 1.25);
+ fin.rotation.y = -a;
+ rocket.add(fin);
+ }
+ const porthole = new Mesh(new CylinderGeometry(0.3, 0.3, 0.05, 16), glow(0x60a5fa, 1));
+ porthole.rotation.x = Math.PI / 2;
+ porthole.position.set(0, 5.2, 0.98);
+ rocket.add(porthole);
+ const flame = new Mesh(new ConeGeometry(0.75, 1.8, 16, 1, true), glow(hueColor(place.hue, 0.7), 1.6));
+ flame.rotation.x = Math.PI;
+ flame.position.y = -0.4;
+ flame.material.transparent = true;
+ flame.material.opacity = 0.85;
+ flame.material.side = DoubleSide;
+ rocket.add(flame);
+ rocket.traverse((o) => (o.userData.hit = pad.userData.hit));
+ rocket.position.y = 0.5;
+ g.add(rocket);
+ // Gantry.
+ const gantry = new Mesh(new BoxGeometry(0.3, 7.5, 0.3), std({ color: 0x2a2a30, metalness: 0.5 }));
+ gantry.position.set(2.2, 4.25, 0);
+ g.add(gantry);
+ for (const y of [3, 5, 7]) {
+ const arm = new Mesh(new BoxGeometry(1.4, 0.12, 0.12), std({ color: 0x2a2a30, metalness: 0.5 }));
+ arm.position.set(1.5, y, 0);
+ g.add(arm);
+ }
+ const sign = makeLabelSprite(place.title, place.sub, hex(col), 1.1);
+ sign.position.set(0, 10.6, 0);
+ g.add(sign);
+ g.position.set(place.x, 0, place.z);
+ return { group: g, rocket, flame };
+}
+
+/* ------------------------------------------------------------------ mine */
+
+function buildMine(place) {
+ const g = new Group();
+ const col = hueColor(place.hue);
+ const rock = std({ color: 0x14141a, roughness: 1 });
+
+ // Cave: two shoulders, a lintel, a dark back wall and a dim interior floor.
+ const left = new Mesh(new BoxGeometry(3.2, 6.5, 4), rock);
+ left.position.set(-5.2, 3.25, -3);
+ const right = left.clone();
+ right.position.x = 5.2;
+ const lintel = new Mesh(new BoxGeometry(13.6, 2.2, 4), rock);
+ lintel.position.set(0, 6.4, -3);
+ const back = new Mesh(new BoxGeometry(13.6, 7.5, 1), rock);
+ back.position.set(0, 3.75, -7);
+ const floor = new Mesh(new CircleGeometry(7.2, 40), std({ color: 0x0a0a0d, roughness: 1 }));
+ floor.rotation.x = -Math.PI / 2;
+ floor.position.y = 0.01;
+ g.add(left, right, lintel, back, floor);
+ // Rails and a cart.
+ for (const dx of [-0.35, 0.35]) {
+ const rail = new Mesh(new BoxGeometry(0.06, 0.05, 12), std({ color: 0x3a3a44, metalness: 0.7 }));
+ rail.position.set(dx, 0.04, 1);
+ g.add(rail);
+ }
+ const cart = new Mesh(new BoxGeometry(0.9, 0.5, 1.2), std({ color: 0x24242b, metalness: 0.4 }));
+ cart.position.set(0, 0.45, 4.6);
+ g.add(cart);
+
+ // Veins: clusters of octahedra, one per gem colour, lit from inside.
+ const veins = [];
+ const palette = GEMS.map((gm) => gm.hex);
+ VEINS.forEach((v, i) => {
+ const cluster = new Group();
+ const colour = palette[(i + 1) % palette.length];
+ const mat = new MeshStandardMaterial({ color: colour, emissive: colour, emissiveIntensity: 0.55, roughness: 0.2, metalness: 0.1, transparent: true, opacity: 0.92 });
+ for (let k = 0; k < 5; k++) {
+ const s = 0.22 + Math.random() * 0.32;
+ const crystal = new Mesh(new OctahedronGeometry(s, 0), mat);
+ crystal.scale.y = 1.8 + Math.random();
+ const a = (k / 5) * Math.PI * 2 + i;
+ crystal.position.set(Math.cos(a) * 0.35, s * 1.1, Math.sin(a) * 0.35);
+ crystal.rotation.set(Math.random() * 0.5 - 0.25, a, Math.random() * 0.5 - 0.25);
+ crystal.userData.hit = { type: 'vein', id: v.id };
+ cluster.add(crystal);
+ }
+ const light = new PointLight(colour, 0.6, 3.5, 2);
+ light.position.y = 0.6;
+ cluster.add(light);
+ cluster.position.set(v.dx, 0, v.dz);
+ g.add(cluster);
+ veins.push({ id: v.id, group: cluster, material: mat, light, x: place.x + v.dx, z: place.z + v.dz, phase: i * 1.3 });
+ });
+ const sign = makeLabelSprite(place.title, place.sub, hex(col), 1.1);
+ sign.position.set(0, 9, -1);
+ g.add(sign);
+ g.position.set(place.x, 0, place.z);
+ return { group: g, veins };
+}
+
+/* ------------------------------------------------------- small pavilions */
+
+function buildForge(place) {
+ const g = new Group();
+ const col = hueColor(place.hue);
+ const base = new Mesh(new CylinderGeometry(3.6, 3.8, 0.4, 24), std({ color: 0x15151a }));
+ base.position.y = 0.2;
+ base.userData.hit = { type: 'place', id: place.id };
+ const anvil = new Mesh(new BoxGeometry(2.4, 1.3, 1.1), std({ color: 0x23232a, metalness: 0.7, roughness: 0.35 }));
+ anvil.position.y = 1.05;
+ anvil.userData.hit = base.userData.hit;
+ const hot = new Mesh(new BoxGeometry(2.4, 0.08, 1.1), glow(col, 1.6));
+ hot.position.y = 1.74;
+ const chimney = new Mesh(new CylinderGeometry(0.5, 0.7, 5.5, 12), std({ color: 0x1b1b21 }));
+ chimney.position.set(-1.6, 3.1, -1.2);
+ const ember = new Mesh(new CylinderGeometry(0.48, 0.48, 0.1, 12), glow(col, 1.2));
+ ember.position.set(-1.6, 5.9, -1.2);
+ g.add(base, anvil, hot, chimney, ember);
+ const sign = makeLabelSprite(place.title, place.sub, hex(col));
+ sign.position.set(0, 7.4, 0);
+ g.add(sign);
+ g.position.set(place.x, 0, place.z);
+ g.rotation.y = facing(place);
+ return { group: g, pulse: [hot.material, ember.material] };
+}
+
+function buildGallery(place) {
+ const g = new Group();
+ const col = hueColor(place.hue);
+ const base = new Mesh(new CylinderGeometry(3.6, 3.8, 0.4, 24), std({ color: 0x15151a }));
+ base.position.y = 0.2;
+ base.userData.hit = { type: 'place', id: place.id };
+ g.add(base);
+ const frames = [];
+ for (let i = 0; i < 4; i++) {
+ const a = (i / 4) * Math.PI * 2;
+ const ped = new Mesh(new BoxGeometry(0.5, 1.1, 0.5), std({ color: 0x1b1b21 }));
+ ped.position.set(Math.cos(a) * 2.2, 0.95, Math.sin(a) * 2.2);
+ const frame = new Mesh(new BoxGeometry(1.2, 1.6, 0.08), std({ color: 0x0b0b0e, metalness: 0.4 }));
+ frame.position.set(Math.cos(a) * 2.2, 2.5, Math.sin(a) * 2.2);
+ frame.rotation.y = -a + Math.PI / 2;
+ const art = new Mesh(new PlaneGeometry(1.0, 1.4), glow(hueColor(place.hue + i * 40, 0.6), 0.7));
+ art.position.set(0, 0, 0.05);
+ frame.add(art);
+ frame.userData.hit = base.userData.hit;
+ art.userData.hit = base.userData.hit;
+ g.add(ped, frame);
+ frames.push(frame);
+ }
+ const sign = makeLabelSprite(place.title, place.sub, hex(col));
+ sign.position.set(0, 5.6, 0);
+ g.add(sign);
+ g.position.set(place.x, 0, place.z);
+ g.rotation.y = facing(place);
+ return { group: g, frames };
+}
+
+function buildPlaza(place) {
+ const g = new Group();
+ const col = hueColor(place.hue);
+ const base = new Mesh(new CylinderGeometry(3.6, 3.8, 0.4, 24), std({ color: 0x15151a }));
+ base.position.y = 0.2;
+ base.userData.hit = { type: 'place', id: place.id };
+ g.add(base);
+ const figures = [];
+ for (let i = 0; i < 7; i++) {
+ const a = (i / 7) * Math.PI * 2;
+ const fig = new Mesh(new CylinderGeometry(0.22, 0.26, 1.5, 10), std({ color: 0x1f1f26, emissive: hueColor(place.hue + i * 30, 0.5), emissiveIntensity: 0.4 }));
+ fig.position.set(Math.cos(a) * 2.4, 1.15, Math.sin(a) * 2.4);
+ const head = new Mesh(new OctahedronGeometry(0.22, 1), std({ color: 0xeeeef4 }));
+ head.position.set(Math.cos(a) * 2.4, 2.15, Math.sin(a) * 2.4);
+ fig.userData.hit = base.userData.hit;
+ head.userData.hit = base.userData.hit;
+ g.add(fig, head);
+ figures.push(head);
+ }
+ const beacon = new Mesh(new CylinderGeometry(0.1, 0.1, 4.5, 8), glow(col, 1.2));
+ beacon.position.y = 2.6;
+ g.add(beacon);
+ const sign = makeLabelSprite(place.title, place.sub, hex(col));
+ sign.position.set(0, 6.2, 0);
+ g.add(sign);
+ g.position.set(place.x, 0, place.z);
+ g.rotation.y = facing(place);
+ return { group: g, figures };
+}
+
+function buildMarket(place) {
+ const g = new Group();
+ const col = hueColor(place.hue);
+ const base = new Mesh(new CylinderGeometry(3.6, 3.8, 0.4, 24), std({ color: 0x15151a }));
+ base.position.y = 0.2;
+ base.userData.hit = { type: 'place', id: place.id };
+ g.add(base);
+ for (let i = 0; i < 3; i++) {
+ const a = (i / 3) * Math.PI * 2 + 0.5;
+ const stall = new Group();
+ const counter = new Mesh(new BoxGeometry(2, 0.9, 0.8), std({ color: 0x1b1b21 }));
+ counter.position.y = 0.85;
+ const canopy = new Mesh(new BoxGeometry(2.3, 0.08, 1.4), std({ color: hueColor(place.hue + i * 25, 0.5) }));
+ canopy.position.set(0, 2.5, 0.1);
+ const light = new Mesh(new BoxGeometry(1.9, 0.05, 0.05), glow(col, 1.2));
+ light.position.set(0, 2.44, 0.6);
+ for (const sx of [-1.05, 1.05]) {
+ const post = new Mesh(new CylinderGeometry(0.04, 0.04, 2.5, 8), std({ color: 0x2a2a30 }));
+ post.position.set(sx, 1.25, 0.6);
+ stall.add(post);
+ }
+ stall.add(counter, canopy, light);
+ stall.position.set(Math.cos(a) * 2.1, 0.4, Math.sin(a) * 2.1);
+ stall.rotation.y = -a - Math.PI / 2;
+ stall.traverse((o) => (o.userData.hit = base.userData.hit));
+ g.add(stall);
+ }
+ const sign = makeLabelSprite(place.title, place.sub, hex(col));
+ sign.position.set(0, 5.6, 0);
+ g.add(sign);
+ g.position.set(place.x, 0, place.z);
+ g.rotation.y = facing(place);
+ return { group: g };
+}
+
+/**
+ * @param {HTMLCanvasElement} canvas
+ * @param {{ screenMaterial: import('three').Material, tickerMaterial: import('three').Material, reducedMotion?: boolean }} o
+ */
+export function createCampus(canvas, { screenMaterial, tickerMaterial, reducedMotion = false }) {
+ const renderer = createRenderer(
+ { canvas, antialias: true, alpha: false, powerPreference: 'high-performance' },
+ { fallback: canvas.parentElement },
+ );
+ renderer.setPixelRatio(Math.min(2, devicePixelRatio || 1));
+ renderer.setSize(innerWidth, innerHeight, false);
+ renderer.toneMapping = ACESFilmicToneMapping;
+ renderer.toneMappingExposure = 1.05;
+
+ const scene = new Scene();
+ scene.background = new Color(BG);
+ scene.fog = new Fog(BG, 42, 120);
+ const camera = new PerspectiveCamera(58, innerWidth / innerHeight, 0.1, 400);
+
+ scene.add(new HemisphereLight(0xa39bd0, 0x14121c, 1.25));
+ const sun = new DirectionalLight(0xdcd6ff, 1.1);
+ sun.position.set(18, 30, 12);
+ scene.add(sun);
+ scene.add(makeSkyDome(), makeStars(560));
+
+ // Ground.
+ const groundTex = groundTexture();
+ const ground = new Mesh(new CircleGeometry(CAMPUS_RADIUS + 14, 96), new MeshStandardMaterial({ map: groundTex, roughness: 0.95, metalness: 0 }));
+ ground.rotation.x = -Math.PI / 2;
+ ground.receiveShadow = false;
+ scene.add(ground);
+ // Edge glow where the walkable disc ends.
+ const edge = new Mesh(new RingGeometry(CAMPUS_RADIUS - 0.1, CAMPUS_RADIUS + 0.25, 128), glow(VIOLET, 0.5));
+ edge.rotation.x = -Math.PI / 2;
+ edge.position.y = 0.015;
+ scene.add(edge);
+
+ // Lamps along the gate path and around the plaza.
+ for (const z of [26, 20, 14]) scene.add(lamp(-2.2, z), lamp(2.2, z));
+ for (let i = 0; i < 8; i++) {
+ const a = (i / 8) * Math.PI * 2;
+ scene.add(lamp(Math.cos(a) * 9, 8 + Math.sin(a) * 9));
+ }
+
+ // Gate pylons at the spawn.
+ for (const sx of [-3.2, 3.2]) {
+ const pylon = new Mesh(new BoxGeometry(0.5, 5.5, 0.5), std({ color: 0x0f0f14 }));
+ pylon.position.set(sx, 2.75, 33);
+ const tip = new Mesh(new BoxGeometry(0.5, 0.1, 0.5), glow(VIOLET, 1.2));
+ tip.position.set(sx, 5.55, 33);
+ scene.add(pylon, tip);
+ }
+ const gateSign = makeLabelSprite('Welcome to three.ws', 'Walk to your desk, or explore', '#c4b5fd', 1.1);
+ gateSign.position.set(0, 6.4, 33);
+ scene.add(gateSign);
+
+ // Buildings.
+ const office = buildOffice(placeById('office'), screenMaterial);
+ const exchange = buildExchange(placeById('exchange'), tickerMaterial);
+ const launchpad = buildLaunchpad(placeById('launchpad'));
+ const mine = buildMine(placeById('mine'));
+ const forge = buildForge(placeById('forge'));
+ const gallery = buildGallery(placeById('gallery'));
+ const plaza = buildPlaza(placeById('agents'));
+ const market = buildMarket(placeById('market'));
+ scene.add(office.group, exchange, launchpad.group, mine.group, forge.group, gallery.group, plaza.group, market.group);
+
+ // Keep-out volumes for the player (same shape player.update expects).
+ const solids = PLACES.filter((p) => p.keepout > 0).map((p) => ({ group: { position: new Vector3(p.x, 0, p.z) }, keepout: p.keepout }));
+ // The desk itself: a small disc so the avatar never walks through the table.
+ const o = placeById('office');
+ solids.push({ group: { position: new Vector3(o.x, 0, o.z - 0.5) }, keepout: 1.35 });
+ // Mine shoulders.
+ const m = placeById('mine');
+ solids.push({ group: { position: new Vector3(m.x - 5.2, 0, m.z - 3) }, keepout: 2.6 }, { group: { position: new Vector3(m.x + 5.2, 0, m.z - 3) }, keepout: 2.6 });
+ for (const v of mine.veins) solids.push({ group: { position: new Vector3(v.x, 0, v.z) }, keepout: 0.75 });
+
+ // Highlight: the nearest interactable gets a soft ring under it.
+ const halo = new Mesh(new RingGeometry(0.9, 1.1, 40), new MeshBasicMaterial({ color: VIOLET, transparent: true, opacity: 0.7, toneMapped: false }));
+ halo.rotation.x = -Math.PI / 2;
+ halo.position.y = 0.03;
+ halo.visible = false;
+ scene.add(halo);
+ function highlight(target) {
+ if (!target) {
+ halo.visible = false;
+ return;
+ }
+ halo.visible = true;
+ let x = target.x;
+ let z = target.z;
+ let r = 1;
+ if (target.type === 'object') {
+ const ob = DESK_OBJECTS.find((d) => d.id === target.id);
+ x = o.x + ob.dx;
+ z = o.z + ob.dz;
+ r = 0.45;
+ } else if (target.type === 'vein') {
+ const v = mine.veins.find((vv) => vv.id === target.id);
+ x = v.x;
+ z = v.z;
+ r = 0.9;
+ } else if (target.type === 'place') {
+ const p = placeById(target.id);
+ x = p.x;
+ z = p.z;
+ r = p.keepout + 0.6;
+ }
+ halo.position.x = x;
+ halo.position.z = z;
+ halo.scale.setScalar(r);
+ }
+
+ // Tap-to-interact raycast against anything carrying userData.hit.
+ const raycaster = new Raycaster();
+ const ndc = new Vector2();
+ function pick(clientX, clientY) {
+ const rect = canvas.getBoundingClientRect();
+ ndc.set(((clientX - rect.left) / rect.width) * 2 - 1, -((clientY - rect.top) / rect.height) * 2 + 1);
+ raycaster.setFromCamera(ndc, camera);
+ const hits = raycaster.intersectObjects(scene.children, true);
+ for (const h of hits) {
+ let obj = h.object;
+ while (obj && !obj.userData.hit) obj = obj.parent;
+ if (obj?.userData.hit) return { ...obj.userData.hit, point: h.point };
+ }
+ return null;
+ }
+
+ let t = 0;
+ function tick(dt) {
+ if (reducedMotion) return;
+ t += dt;
+ launchpad.rocket.position.y = 0.5 + Math.sin(t * 0.8) * 0.06;
+ launchpad.flame.scale.set(1 + Math.sin(t * 17) * 0.12, 1 + Math.sin(t * 13) * 0.2, 1 + Math.cos(t * 15) * 0.12);
+ for (const v of mine.veins) {
+ const k = 0.45 + Math.sin(t * 1.6 + v.phase) * 0.2;
+ v.material.emissiveIntensity = k;
+ v.light.intensity = 0.4 + k;
+ }
+ for (const f of gallery.frames) f.rotation.y += dt * 0.25;
+ for (const h of plaza.figures) h.rotation.y += dt * 0.6;
+ halo.material.opacity = 0.55 + Math.sin(t * 4) * 0.2;
+ }
+
+ function resize() {
+ const w = innerWidth;
+ const hgt = innerHeight;
+ renderer.setSize(w, hgt, false);
+ camera.aspect = w / hgt;
+ camera.updateProjectionMatrix();
+ }
+
+ function dispose() {
+ renderer.setAnimationLoop(null);
+ scene.traverse((obj) => {
+ obj.geometry?.dispose?.();
+ const mats = Array.isArray(obj.material) ? obj.material : obj.material ? [obj.material] : [];
+ for (const mat of mats) {
+ if (mat === screenMaterial || mat === tickerMaterial) continue;
+ mat.map?.dispose?.();
+ mat.dispose?.();
+ }
+ });
+ groundTex.dispose();
+ renderer.dispose();
+ }
+
+ return {
+ renderer,
+ scene,
+ camera,
+ solids,
+ veinPositions: mine.veins.map((v) => ({ id: v.id, x: v.x, z: v.z })),
+ desk: office,
+ highlight,
+ pick,
+ tick,
+ resize,
+ dispose,
+ };
+}
diff --git a/src/desktop/world/index.js b/src/desktop/world/index.js
new file mode 100644
index 000000000..855e47769
--- /dev/null
+++ b/src/desktop/world/index.js
@@ -0,0 +1,484 @@
+// The world controller: mounts the campus over the desktop, wires input,
+// proximity prompts, the sit-down and walk-in transitions, the phone, the VR
+// headset and gem mining, and runs the frame loop. main.js decides whether the
+// visitor starts here or on the desktop; the taskbar's World button brings
+// them back.
+
+import { MeshBasicMaterial, Vector3 } from 'three';
+import { createPlayer } from '../../docs-world/player.js';
+import { createControls } from '../../docs-world/controls.js';
+import { createCameraModeController, CAMERA_MODE_LABELS } from '../../game/camera-modes.js';
+import { createFrameGovernor, FPS_ACTIVE, FPS_IDLE, getPowerSaver, onPowerSaverChange, trackWindowFocus } from '../../shared/frame-governor.js';
+import { log } from '../../shared/log.js';
+import { icon } from '../icons.js';
+import { createCampus } from './campus.js';
+import { createDesktopScreen } from './screen.js';
+import { createTickerBoard, loadTickerItems } from './ticker.js';
+import { createMiner, GEM_BY_ID } from './mine.js';
+import { enterVR, vrSupported } from './xr.js';
+import { CAMPUS_RADIUS, PLACES, SPAWN, nearestInteractable, placeById, standPointFor } from './places.js';
+import './world.css';
+
+const TICKER_REFRESH_MS = 60_000;
+const SIT_SECONDS = 1.15;
+
+function h(tag, cls, html) {
+ const el = document.createElement(tag);
+ if (cls) el.className = cls;
+ if (html != null) el.innerHTML = html;
+ return el;
+}
+const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
+
+/** Wait for an element's running CSS transitions to settle. Resolves at once when nothing animates. */
+async function settled(el) {
+ const anims = typeof el.getAnimations === 'function' ? el.getAnimations() : [];
+ await Promise.all(anims.map((a) => a.finished.catch(() => {})));
+}
+
+/**
+ * @param {{
+ * shell: { launchId(id:string, o?:object): void, prefs: object, onPrefs(fn:(p:object)=>void): void, displayName(): string, toast(msg:string): void },
+ * apps: Array<{id:string,title:string,hue:number}>,
+ * reducedMotion?: boolean,
+ * onDesktop: (o: { app?: string|null, place?: string|null }) => void,
+ * }} o
+ */
+export function createWorld({ shell, apps, reducedMotion = false, onDesktop }) {
+ const el = h('div', 'wd');
+ el.hidden = true;
+ el.innerHTML = `
+ <canvas class="wd-canvas" aria-label="three.ws campus"></canvas>
+ <div class="wd-hud">
+ <div class="wd-top">
+ <div class="wd-brand"><b>three.ws</b><span class="wd-where">Campus</span></div>
+ <div class="wd-tools">
+ <button type="button" class="wd-tool wd-gems" aria-haspopup="dialog" aria-expanded="false" title="Your gems">${icon('gem', 18)}<span class="wd-gems-pts">0</span></button>
+ <button type="button" class="wd-tool wd-cam" title="Camera (C)">${icon('camera', 18)}<span class="wd-cam-label"></span></button>
+ <button type="button" class="wd-tool wd-vr" hidden title="Enter VR">${icon('vr', 18)}<span>VR</span></button>
+ <button type="button" class="wd-tool wd-desk" title="Go straight to the desktop">${icon('desktop', 18)}<span>Desktop</span></button>
+ </div>
+ </div>
+ <div class="wd-prompt" hidden role="status">
+ <kbd class="wd-key">E</kbd>
+ <div class="wd-prompt-text"><b></b><span></span></div>
+ <div class="wd-dig" hidden><i></i></div>
+ </div>
+ <button type="button" class="wd-digbtn" hidden>Hold to dig</button>
+ <nav class="wd-places" aria-label="Places"></nav>
+ <div class="wd-stick" hidden><i></i></div>
+ <div class="wd-toasts" aria-live="polite"></div>
+ <section class="wd-gempanel" hidden role="dialog" aria-label="Your gems">
+ <header><b>Your gems</b><button type="button" class="wd-x" aria-label="Close">${icon('close', 16)}</button></header>
+ <ul class="wd-gemlist"></ul>
+ <p class="wd-gemfoot"></p>
+ </section>
+ </div>
+ <div class="wd-phone" hidden role="dialog" aria-label="Pocket">
+ <div class="wd-phone-frame">
+ <button type="button" class="wd-phone-x" aria-label="Put the phone down">${icon('close', 18)}</button>
+ <iframe title="Pocket" name="tws-os:pocket" allow="xr-spatial-tracking; clipboard-write; microphone; camera"></iframe>
+ </div>
+ </div>
+ <div class="wd-fade" aria-hidden="true"><p class="wd-fade-cap"></p></div>`;
+ document.body.append(el);
+
+ const $ = (sel) => el.querySelector(sel);
+ const canvas = $('.wd-canvas');
+ const prompt = $('.wd-prompt');
+ const promptKey = $('.wd-key');
+ const promptTitle = $('.wd-prompt-text b');
+ const promptSub = $('.wd-prompt-text span');
+ const dig = $('.wd-dig');
+ const digBar = $('.wd-dig i');
+ const digBtn = $('.wd-digbtn');
+ const where = $('.wd-where');
+ const fade = $('.wd-fade');
+ const fadeCap = $('.wd-fade-cap');
+ const toasts = $('.wd-toasts');
+ const stick = $('.wd-stick');
+ const isTouch = matchMedia('(pointer: coarse)').matches;
+ if (isTouch) promptKey.textContent = 'Tap';
+
+ // ---- scene ----
+ const screen = createDesktopScreen({ apps });
+ const screenMaterial = new MeshBasicMaterial({ map: screen.texture, toneMapped: false });
+ const ticker = createTickerBoard();
+ const tickerMaterial = new MeshBasicMaterial({ map: ticker.texture, toneMapped: false });
+ const campus = createCampus(canvas, { screenMaterial, tickerMaterial, reducedMotion });
+ const { renderer, scene, camera } = campus;
+ const player = createPlayer(scene, renderer, { spawn: SPAWN, yaw: SPAWN.yaw, bound: CAMPUS_RADIUS, keepout: 0 });
+
+ const cameraCtl = createCameraModeController({ storageKey: 'tws:world-camera', onChange: syncCamera });
+ const camBtn = $('.wd-cam');
+ function syncCamera() {
+ $('.wd-cam-label').textContent = CAMERA_MODE_LABELS[cameraCtl.mode];
+ player.setVisible(!cameraCtl.isFirstPerson());
+ }
+ syncCamera();
+ camBtn.addEventListener('click', () => cameraCtl.cycle(camera));
+
+ let busy = false; // a transition is running: ignore interactions
+ let nearest = null;
+ let digHeld = false;
+
+ const controls = createControls(canvas, {
+ onInteract: () => interact(),
+ onCycleCamera: () => cameraCtl.cycle(camera),
+ onTap: (e) => {
+ const hit = campus.pick(e.clientX, e.clientY);
+ if (!hit) return;
+ // A tap only acts on what the player could also reach by walking up:
+ // far-away taps walk the player there instead.
+ if (nearest && nearest.id === hit.id) return interact();
+ const target = hit.type === 'place' ? placeById(hit.id) : hit.type === 'vein' ? campus.veinPositions.find((v) => v.id === hit.id) : placeById('office');
+ if (target) goTo(target.type === 'vein' || hit.type === 'vein' ? { x: target.x, z: target.z, keepout: 0.75 } : target);
+ },
+ });
+ controls.orbit.yaw = SPAWN.yaw;
+ controls.orbit.dist = 7;
+
+ // Hold-to-dig needs key state, which controls.js deliberately hides.
+ addEventListener('keydown', (e) => {
+ if (!controls.enabled) return;
+ if ((e.key === 'e' || e.key === 'E') && !e.repeat) digHeld = true;
+ });
+ addEventListener('keyup', (e) => {
+ if (e.key === 'e' || e.key === 'E') digHeld = false;
+ });
+ addEventListener('blur', () => (digHeld = false));
+ for (const ev of ['pointerdown']) digBtn.addEventListener(ev, (e) => { e.preventDefault(); digHeld = true; });
+ for (const ev of ['pointerup', 'pointercancel', 'pointerleave']) digBtn.addEventListener(ev, () => (digHeld = false));
+
+ // ---- live data: ticker ----
+ let tickerTimer = 0;
+ async function refreshTicker() {
+ const { items, notes } = await loadTickerItems();
+ ticker.setItems(items, notes);
+ }
+ function scheduleTicker() {
+ clearInterval(tickerTimer);
+ tickerTimer = setInterval(() => { if (!el.hidden && !document.hidden) refreshTicker(); }, TICKER_REFRESH_MS);
+ }
+
+ // ---- live data: gems ----
+ const gemsBtn = $('.wd-gems');
+ const gemPanel = $('.wd-gempanel');
+ const gemList = $('.wd-gemlist');
+ const gemFoot = $('.wd-gemfoot');
+ const miner = createMiner({ onBalance: paintGems });
+ function paintGems(b) {
+ $('.wd-gems-pts').textContent = b.offline ? 'offline' : String(b.points || 0);
+ gemList.replaceChildren();
+ const table = b.table || Object.values(GEM_BY_ID);
+ for (const g of table) {
+ const n = b.gems?.[g.id] || 0;
+ const li = h('li', n ? '' : 'is-empty');
+ li.innerHTML = `<i style="--c:${esc(g.hex)}"></i><span>${esc(g.label)}</span><small>${g.points} pt${g.points === 1 ? '' : 's'}</small><b>${n}</b>`;
+ gemList.append(li);
+ }
+ if (b.offline) gemFoot.textContent = 'The gem ledger is unreachable right now. Digging will retry when it is back.';
+ else if (b.miner === 'account') gemFoot.textContent = `${b.total || 0} gems, ${b.points || 0} points, saved to your account.`;
+ else if (b.total) gemFoot.textContent = `${b.total} gems in this browser. Sign in and they move to your account.`;
+ else gemFoot.textContent = 'Nothing yet. Walk into the mine and hold E at a glowing vein.';
+ }
+ paintGems(miner.balance);
+ gemsBtn.addEventListener('click', () => {
+ const open = gemPanel.hidden;
+ gemPanel.hidden = !open;
+ gemsBtn.setAttribute('aria-expanded', String(open));
+ if (open) miner.refresh();
+ });
+ $('.wd-gempanel .wd-x').addEventListener('click', () => { gemPanel.hidden = true; gemsBtn.setAttribute('aria-expanded', 'false'); });
+
+ // ---- places strip (teleport) ----
+ const nav = $('.wd-places');
+ for (const p of PLACES) {
+ const b = h('button', 'wd-place', `<i style="--h:${p.hue}"></i>${esc(p.title)}`);
+ b.type = 'button';
+ b.title = p.sub;
+ b.addEventListener('click', () => goTo(p));
+ nav.append(b);
+ }
+ /** Put the player just outside a place, facing it. */
+ function goTo(p) {
+ const s = standPointFor(p);
+ player.root.position.set(s.x, 0, s.z);
+ player.root.rotation.y = s.yaw;
+ controls.orbit.yaw = s.yaw;
+ camera.position.set(s.x - Math.sin(s.yaw) * 6, 3.2, s.z - Math.cos(s.yaw) * 6);
+ }
+
+ // ---- toasts ----
+ function toast(text, color) {
+ const t = h('div', 'wd-toast', esc(text));
+ if (color) t.style.setProperty('--c', color);
+ toasts.append(t);
+ t.addEventListener('animationend', () => t.remove(), { once: true });
+ }
+
+ // ---- fade ----
+ async function fadeTo(opaque, caption = '') {
+ fadeCap.textContent = caption;
+ fade.classList.toggle('is-on', opaque);
+ if (reducedMotion) return;
+ await new Promise((r) => requestAnimationFrame(r));
+ await settled(fade);
+ }
+
+ // ---- interactions ----
+ let vrOk = false;
+ vrSupported().then((ok) => {
+ vrOk = ok;
+ $('.wd-vr').hidden = !ok;
+ });
+ $('.wd-vr').addEventListener('click', () => wearHeadset());
+ $('.wd-desk').addEventListener('click', () => sitDown());
+
+ async function interact() {
+ if (busy || !nearest) return;
+ if (nearest.type === 'object') {
+ if (nearest.id === 'monitor') return sitDown();
+ if (nearest.id === 'phone') return pickUpPhone();
+ if (nearest.id === 'headset') return wearHeadset();
+ }
+ if (nearest.type === 'place') return enterPlace(placeById(nearest.id));
+ // Veins are hold-to-dig; a press alone just nudges.
+ if (nearest.type === 'vein' && !digHeld) toast('Hold E to dig', '#c4b5fd');
+ }
+
+ let sitting = null; // { t, from, to, look }
+ async function sitDown() {
+ if (busy) return;
+ busy = true;
+ controls.enabled = false;
+ gemPanel.hidden = true;
+ // Dolly from where the camera is into the screen; the frame loop drives it.
+ sitting = { t: 0, from: camera.position.clone(), to: campus.desk.sitTo.clone(), look: campus.desk.screenCentre.clone(), fromLook: new Vector3() };
+ camera.getWorldDirection(sitting.fromLook).multiplyScalar(5).add(camera.position);
+ await new Promise((resolve) => (sitting.done = resolve));
+ await fadeTo(true, '');
+ leaveTo({ app: null, place: 'office' });
+ }
+
+ async function enterPlace(place) {
+ if (!place || busy) return;
+ busy = true;
+ controls.enabled = false;
+ await fadeTo(true, `Entering ${place.title}`);
+ const s = standPointFor(place);
+ player.root.position.set(s.x, 0, s.z);
+ player.root.rotation.y = s.yaw;
+ leaveTo({ app: place.app, place: place.id });
+ }
+
+ /** Hand control to the desktop. The world stays mounted (paused) so coming back is instant. */
+ function leaveTo(o) {
+ stopLoop();
+ el.hidden = true;
+ sitting = null;
+ onDesktop(o);
+ busy = false;
+ }
+
+ // ---- phone ----
+ const phone = $('.wd-phone');
+ const phoneFrame = phone.querySelector('iframe');
+ function pickUpPhone() {
+ if (!phoneFrame.src) phoneFrame.src = '/pocket?chrome=off';
+ phone.hidden = false;
+ controls.enabled = false;
+ phone.querySelector('.wd-phone-x').focus();
+ }
+ function putDownPhone() {
+ phone.hidden = true;
+ controls.enabled = true;
+ }
+ phone.querySelector('.wd-phone-x').addEventListener('click', putDownPhone);
+ phone.addEventListener('click', (e) => { if (e.target === phone) putDownPhone(); });
+ addEventListener('keydown', (e) => {
+ if (e.key === 'Escape' && !phone.hidden) putDownPhone();
+ });
+
+ // ---- VR ----
+ let xrSession = null;
+ async function wearHeadset() {
+ if (busy) return;
+ if (!vrOk) {
+ // No runtime: the honest alternative is first-person view.
+ cameraCtl.setMode('firstperson', camera);
+ toast('No VR headset found in this browser. Switched to first person; press C to change the camera.', '#60a5fa');
+ return;
+ }
+ try {
+ xrSession = await enterVR(renderer, {
+ onEnd: () => {
+ xrSession = null;
+ el.classList.remove('is-xr');
+ campus.resize();
+ player.setVisible(!cameraCtl.isFirstPerson());
+ },
+ });
+ el.classList.add('is-xr');
+ player.setVisible(false);
+ } catch (err) {
+ log.warn('[world] VR session failed', err?.message);
+ toast(`Could not start VR: ${err?.message || 'the headset refused the session'}.`, '#f87171');
+ }
+ }
+ /** Thumbstick locomotion from the first XR gamepad; the XR rig follows the player. */
+ function xrMove() {
+ const session = renderer.xr.getSession?.();
+ if (!session) return null;
+ for (const src of session.inputSources) {
+ const ax = src.gamepad?.axes;
+ if (ax && ax.length >= 4 && (Math.abs(ax[2]) > 0.1 || Math.abs(ax[3]) > 0.1)) return { x: ax[2], z: -ax[3] };
+ }
+ return { x: 0, z: 0 };
+ }
+
+ // ---- proximity ----
+ function updateNearest() {
+ const p = player.position;
+ const n = nearestInteractable(p.x, p.z, { veinPositions: campus.veinPositions });
+ const changed = (n && n.id) !== (nearest && nearest.id);
+ nearest = n;
+ if (changed) {
+ campus.highlight(n);
+ prompt.hidden = !n;
+ if (n) {
+ promptTitle.textContent = n.title;
+ promptSub.textContent = n.sub;
+ promptKey.textContent = n.type === 'vein' ? (isTouch ? 'Hold' : 'Hold E') : isTouch ? 'Tap' : 'E';
+ }
+ dig.hidden = !n || n.type !== 'vein';
+ digBtn.hidden = !(isTouch && n && n.type === 'vein');
+ }
+ // Which district are we in? Nearest place by distance, for the top-left line.
+ let best = null;
+ for (const pl of PLACES) {
+ const d = Math.hypot(p.x - pl.x, p.z - pl.z);
+ if (!best || d < best.d) best = { d, pl };
+ }
+ where.textContent = best && best.d < 12 ? best.pl.title : 'Campus';
+ }
+
+ // ---- mining ----
+ async function updateMining(dt) {
+ const vein = nearest && nearest.type === 'vein' ? nearest.id : null;
+ const progress = miner.tick(dt, digHeld && controls.enabled, vein);
+ digBar.style.width = `${Math.round(progress * 100)}%`;
+ if (vein && miner.ready()) {
+ const r = await miner.dig(vein);
+ if (r.ok) toast(`${r.mined.label} +${r.mined.points}`, r.mined.hex);
+ else if (r.error === 'dig_too_soon') toast(`Give the vein a moment (${r.retryIn || 1}s).`, '#c4b5fd');
+ else if (r.error === 'daily_cap') toast('You have hit the daily dig limit. Come back tomorrow.', '#c4b5fd');
+ else toast(r.message, '#f87171');
+ }
+ }
+
+ // ---- touch stick ----
+ function paintStick() {
+ const j = controls.joystick;
+ if (!isTouch) return;
+ stick.hidden = !j.active;
+ if (!j.active) return;
+ stick.style.transform = `translate(${j.baseX - 52}px, ${j.baseY - 52}px)`;
+ stick.firstElementChild.style.transform = `translate(${j.x * 36}px, ${j.y * 36}px)`;
+ }
+
+ // ---- frame loop ----
+ const governor = createFrameGovernor();
+ const focus = trackWindowFocus();
+ let saver = getPowerSaver();
+ onPowerSaverChange((on) => (saver = on));
+ let last = 0;
+ let running = false;
+ const lookScratch = new Vector3();
+
+ function frame(now) {
+ const xr = renderer.xr.isPresenting;
+ const cap = xr ? Infinity : saver || !focus.focused || !phone.hidden ? FPS_IDLE : FPS_ACTIVE;
+ if (!xr && !governor.shouldRun(now, cap)) return;
+ const dt = Math.min(0.05, last ? (now - last) / 1000 : 0.016);
+ last = now;
+
+ const move = xr ? xrMove() || { x: 0, z: 0 } : controls.readMove();
+ const yaw = xr ? Math.atan2(-camera.matrixWorld.elements[8], -camera.matrixWorld.elements[10]) + Math.PI : controls.orbit.yaw;
+ player.update(dt, move, yaw, controls.run, campus.solids);
+ campus.tick(dt);
+ ticker.tick(dt);
+ if (Math.hypot(player.position.x, player.position.z - 8) < 14) {
+ screen.draw({ wall: shell.prefs.wall, name: shell.displayName(), prompt: nearest?.id === 'monitor' ? 'Press E to sit down' : '', clock24: shell.prefs.clock24, accent: shell.prefs.accent });
+ }
+ updateNearest();
+ updateMining(dt);
+ paintStick();
+
+ if (sitting) {
+ sitting.t = Math.min(1, sitting.t + dt / (reducedMotion ? 0.01 : SIT_SECONDS));
+ const e = sitting.t * sitting.t * (3 - 2 * sitting.t);
+ camera.position.lerpVectors(sitting.from, sitting.to, e);
+ lookScratch.lerpVectors(sitting.fromLook, sitting.look, e);
+ camera.lookAt(lookScratch);
+ if (sitting.t >= 1) sitting.done?.();
+ } else if (xr) {
+ // The XR camera is driven by the headset; keep the rig at the player's feet.
+ camera.position.set(player.position.x, 0, player.position.z);
+ } else {
+ cameraCtl.tick(dt);
+ cameraCtl.apply(camera, player.position, player.height, controls.orbit, 0.35);
+ }
+ renderer.render(scene, camera);
+ }
+ function startLoop() {
+ if (running) return;
+ running = true;
+ last = 0;
+ governor.reset();
+ renderer.setAnimationLoop(frame);
+ }
+ function stopLoop() {
+ running = false;
+ renderer.setAnimationLoop(null);
+ }
+ addEventListener('resize', () => { if (!el.hidden) campus.resize(); });
+
+ // ---- lifecycle ----
+ let entered = false;
+ /**
+ * Show the world. On the first entry the player stands at the gate; on a
+ * return they stand where they left (outside the place they walked into).
+ * @param {{ fromBoot?: boolean, at?: string }} [o]
+ */
+ async function enter({ at } = {}) {
+ el.hidden = false;
+ campus.resize();
+ controls.enabled = true;
+ busy = false;
+ if (at && placeById(at)) goTo(placeById(at));
+ document.documentElement.classList.add('in-world');
+ if (!entered) {
+ entered = true;
+ refreshTicker();
+ miner.refresh();
+ scheduleTicker();
+ }
+ startLoop();
+ fade.classList.add('is-on');
+ await new Promise((r) => requestAnimationFrame(r));
+ await fadeTo(false);
+ }
+
+ function dispose() {
+ stopLoop();
+ clearInterval(tickerTimer);
+ xrSession?.end().catch(() => {});
+ campus.dispose();
+ screen.dispose();
+ ticker.dispose();
+ el.remove();
+ }
+
+ return { el, enter, dispose, get entered() { return entered; } };
+}
diff --git a/src/desktop/world/mine.js b/src/desktop/world/mine.js
new file mode 100644
index 000000000..3c5858f93
--- /dev/null
+++ b/src/desktop/world/mine.js
@@ -0,0 +1,113 @@
+// Gem mining client. Progress is the real time the player spends holding the
+// dig key at a vein (advanced by the frame loop's dt), and the gem itself is
+// rolled by the server, which also enforces the cadence. Visitors mine under
+// the same stable browser id the walk pages use, so their gems move onto the
+// account when they sign in.
+
+import { DIG_SECONDS, GEM_BY_ID, GEMS } from '../../../api/_lib/world-gems.js';
+
+const ANON_KEY = 'twx_walk_anon';
+
+export { DIG_SECONDS, GEMS, GEM_BY_ID };
+
+export function anonId() {
+ try {
+ let id = localStorage.getItem(ANON_KEY);
+ if (!id) {
+ id = `anon_${crypto.randomUUID()}`;
+ localStorage.setItem(ANON_KEY, id);
+ }
+ return id;
+ } catch {
+ if (!anonId._mem) anonId._mem = `anon_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 10)}`;
+ return anonId._mem;
+ }
+}
+
+/**
+ * @param {{ onBalance?: (b: object) => void, fetchFn?: typeof fetch }} [o]
+ */
+export function createMiner({ onBalance, fetchFn = fetch } = {}) {
+ let balance = { gems: {}, points: 0, total: 0, miner: null };
+ let progress = 0;
+ let activeVein = null;
+ let inflight = null;
+
+ async function refresh() {
+ try {
+ const r = await fetchFn(`/api/world/gems?anonId=${encodeURIComponent(anonId())}`, { credentials: 'include', headers: { accept: 'application/json' } });
+ if (!r.ok) throw new Error(`gems ${r.status}`);
+ const b = await r.json();
+ balance = b;
+ onBalance?.(b);
+ return b;
+ } catch (err) {
+ balance = { ...balance, offline: true, error: err.message };
+ onBalance?.(balance);
+ return balance;
+ }
+ }
+
+ /**
+ * Advance the dig. Call every frame with whether the dig key is held and
+ * which vein (if any) is in reach. Resolves the server call when the hold
+ * completes. Returns the 0..1 progress for the HUD.
+ */
+ function tick(dt, holding, veinId) {
+ if (!holding || !veinId || inflight) {
+ if (!inflight) progress = Math.max(0, progress - dt * 1.5);
+ if (!veinId) activeVein = null;
+ return progress;
+ }
+ if (activeVein !== veinId) {
+ activeVein = veinId;
+ progress = 0;
+ }
+ progress = Math.min(1, progress + dt / DIG_SECONDS);
+ return progress;
+ }
+
+ /** True when the hold has completed and a dig should be submitted. */
+ const ready = () => progress >= 1 && !inflight;
+
+ async function dig(veinId) {
+ if (inflight) return inflight;
+ progress = 0;
+ inflight = (async () => {
+ try {
+ const r = await fetchFn('/api/world/gems', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
+ body: JSON.stringify({ node: veinId, anonId: anonId() }),
+ });
+ const body = await r.json().catch(() => ({}));
+ if (!r.ok) return { ok: false, error: body.error || `http_${r.status}`, message: body.error_description || 'The vein did not yield.', retryIn: body.retry_in_sec };
+ balance = body;
+ onBalance?.(body);
+ return { ok: true, mined: body.mined, balance: body };
+ } catch (err) {
+ return { ok: false, error: 'offline', message: `The gem ledger is unreachable (${err.message}).` };
+ } finally {
+ inflight = null;
+ }
+ })();
+ return inflight;
+ }
+
+ return {
+ refresh,
+ tick,
+ ready,
+ dig,
+ get progress() {
+ return progress;
+ },
+ get balance() {
+ return balance;
+ },
+ get busy() {
+ return !!inflight;
+ },
+ };
+}
diff --git a/src/desktop/world/places.js b/src/desktop/world/places.js
new file mode 100644
index 000000000..e4853106e
--- /dev/null
+++ b/src/desktop/world/places.js
@@ -0,0 +1,185 @@
+// The campus map: where every place stands, what it opens, and how the player
+// is spawned. Pure data so tests can check that every destination is a real
+// desktop app or page and that nothing overlaps.
+
+/** Walkable radius of the campus, in metres. */
+export const CAMPUS_RADIUS = 46;
+
+/** The visitor arrives at the gate, facing the office. */
+export const SPAWN = { x: 0, z: 30, yaw: Math.PI };
+
+/** Distance at which a place arms its prompt. */
+export const PLACE_TRIGGER = 4.6;
+/**
+ * Distance at which a desk object arms its prompt. The monitor uses this full
+ * reach because the desk's keep-out disc stops the player about 1.5 m short of
+ * it; the phone and headset use SIDE_OBJECT_TRIGGER, so they only take the
+ * prompt once the player has stepped round to their side of the desk and the
+ * monitor never loses "Sit down" to a phone that happens to be a hair closer.
+ */
+export const OBJECT_TRIGGER = 2.2;
+export const SIDE_OBJECT_TRIGGER = 1.2;
+
+/**
+ * Places. `kind` decides what interacting does:
+ * app open that desktop app (and sit at the desk)
+ * mine in-world gem mining, no desktop needed
+ * office the home office (the desk objects live here)
+ */
+export const PLACES = [
+ {
+ id: 'office',
+ kind: 'office',
+ title: 'Your workstation',
+ sub: 'Sit down to open the desktop',
+ x: 0,
+ z: 8,
+ hue: 262,
+ keepout: 0,
+ },
+ {
+ id: 'exchange',
+ kind: 'app',
+ app: 'trenches',
+ title: 'three.ws Exchange',
+ sub: 'Live Solana launches, runners and smart money',
+ x: -24,
+ z: -6,
+ hue: 128,
+ keepout: 7.5,
+ },
+ {
+ id: 'launchpad',
+ kind: 'app',
+ app: 'launcher',
+ title: 'Launchpad',
+ sub: 'Launch a coin on pump.fun',
+ x: 24,
+ z: -6,
+ hue: 24,
+ keepout: 5.5,
+ },
+ {
+ id: 'mine',
+ kind: 'mine',
+ title: 'The Mine',
+ sub: 'Hold E at a vein to dig for gems',
+ x: 0,
+ z: -30,
+ hue: 262,
+ keepout: 0,
+ },
+ {
+ id: 'forge',
+ kind: 'app',
+ app: 'forge',
+ title: 'The Forge',
+ sub: 'Type a prompt, get a textured 3D model',
+ x: -14,
+ z: -24,
+ hue: 24,
+ keepout: 4.2,
+ },
+ {
+ id: 'gallery',
+ kind: 'app',
+ app: 'gallery',
+ title: 'Gallery',
+ sub: 'Every public 3D avatar',
+ x: 14,
+ z: -24,
+ hue: 180,
+ keepout: 4.2,
+ },
+ {
+ id: 'agents',
+ kind: 'app',
+ app: 'discover',
+ title: 'Agent Plaza',
+ sub: 'Browse every registered agent',
+ x: -22,
+ z: 16,
+ hue: 200,
+ keepout: 4.2,
+ },
+ {
+ id: 'market',
+ kind: 'app',
+ app: 'marketplace',
+ title: 'Marketplace',
+ sub: 'Buy and sell agent skills',
+ x: 22,
+ z: 16,
+ hue: 44,
+ keepout: 4.2,
+ },
+];
+
+/** Mining veins inside the mine. Ids must match api/_lib/world-gems.js NODES. */
+export const VEINS = [
+ { id: 'vein-a', dx: -3.6, dz: -1.2 },
+ { id: 'vein-b', dx: -1.4, dz: -3.4 },
+ { id: 'vein-c', dx: 1.4, dz: -3.4 },
+ { id: 'vein-d', dx: 3.6, dz: -1.2 },
+ { id: 'vein-e', dx: 0, dz: -5.2 },
+];
+
+/** Objects on the desk, relative to the office origin. */
+export const DESK_OBJECTS = [
+ { id: 'monitor', title: 'Sit down', sub: 'Open the desktop', dx: 0, dz: -0.65, trigger: OBJECT_TRIGGER },
+ { id: 'phone', title: 'Pick up the phone', sub: 'Pocket, your handheld agent console', dx: 0.78, dz: -0.42, trigger: SIDE_OBJECT_TRIGGER },
+ { id: 'headset', title: 'Put on the headset', sub: 'Enter the world in VR', dx: -0.8, dz: -0.42, trigger: SIDE_OBJECT_TRIGGER },
+];
+
+export function placeById(id) {
+ return PLACES.find((p) => p.id === id) || null;
+}
+
+/** Squared planar distance helper shared by the proximity checks. */
+export function dist2(ax, az, bx, bz) {
+ const dx = ax - bx;
+ const dz = az - bz;
+ return dx * dx + dz * dz;
+}
+
+/**
+ * The nearest interactable to the player: a desk object when inside the
+ * office, otherwise the nearest place within its trigger distance.
+ * @returns {{ type: 'object'|'place'|'vein', id: string, title: string, sub: string, d: number } | null}
+ */
+export function nearestInteractable(px, pz, { veinPositions = [] } = {}) {
+ let best = null;
+ const office = placeById('office');
+ for (const o of DESK_OBJECTS) {
+ const d = Math.sqrt(dist2(px, pz, office.x + o.dx, office.z + o.dz));
+ if (d < o.trigger && (!best || d < best.d)) best = { type: 'object', id: o.id, title: o.title, sub: o.sub, d };
+ }
+ if (best) return best;
+ for (const v of veinPositions) {
+ const d = Math.sqrt(dist2(px, pz, v.x, v.z));
+ if (d < OBJECT_TRIGGER + 0.4 && (!best || d < best.d)) best = { type: 'vein', id: v.id, title: 'Dig here', sub: 'Hold E to mine', d };
+ }
+ if (best) return best;
+ for (const p of PLACES) {
+ if (p.kind === 'office' || p.kind === 'mine') continue;
+ const d = Math.sqrt(dist2(px, pz, p.x, p.z));
+ if (d < PLACE_TRIGGER + p.keepout && (!best || d < best.d)) best = { type: 'place', id: p.id, title: `Enter ${p.title}`, sub: p.sub, d };
+ }
+ return best;
+}
+
+/** Yaw that turns a building's front toward the campus centre (the office). */
+export function facingOf(place) {
+ return Math.atan2(-place.x, -place.z);
+}
+
+/**
+ * Where a player stands when arriving at (or stepping back out of) a place:
+ * just outside its keep-out on the side that faces the campus centre, so the
+ * building is in front of them and the office behind.
+ */
+export function standPointFor(place) {
+ const a = facingOf(place);
+ const r = (place.keepout || 0) + 2.4;
+ return { x: place.x + Math.sin(a) * r, z: place.z + Math.cos(a) * r, yaw: a + Math.PI };
+}
diff --git a/src/desktop/world/screen.js b/src/desktop/world/screen.js
new file mode 100644
index 000000000..72c14513b
--- /dev/null
+++ b/src/desktop/world/screen.js
@@ -0,0 +1,170 @@
+// The monitor on the desk shows the real desktop: wallpaper, the pinned app
+// tiles, the clock and the visitor's name, drawn to a canvas texture that
+// refreshes once a second. The same prefs object the shell uses drives it, so
+// changing the wallpaper in Settings changes what the monitor shows.
+
+import { CanvasTexture, SRGBColorSpace } from 'three';
+
+const W = 1024;
+const H = 640;
+
+/** CSS wallpaper gradients, mirrored for the 2D canvas. Keep in step with desktop.css. */
+const WALLS = {
+ three: (g, w, h) => {
+ g.fillStyle = '#050505';
+ g.fillRect(0, 0, w, h);
+ const r = g.createRadialGradient(w * 0.5, h * 0.42, 0, w * 0.5, h * 0.42, w * 0.42);
+ r.addColorStop(0, 'rgba(196,181,253,0.22)');
+ r.addColorStop(1, 'rgba(196,181,253,0)');
+ g.fillStyle = r;
+ g.fillRect(0, 0, w, h);
+ g.strokeStyle = 'rgba(255,255,255,0.05)';
+ g.lineWidth = 1;
+ for (let x = 0; x < w; x += 56) {
+ g.beginPath();
+ g.moveTo(x, 0);
+ g.lineTo(x, h);
+ g.stroke();
+ }
+ for (let y = 0; y < h; y += 56) {
+ g.beginPath();
+ g.moveTo(0, y);
+ g.lineTo(w, y);
+ g.stroke();
+ }
+ },
+ aurora: (g, w, h) => {
+ const l = g.createLinearGradient(0, 0, w, h);
+ l.addColorStop(0, '#3a2434');
+ l.addColorStop(1, '#1a2a4f');
+ g.fillStyle = l;
+ g.fillRect(0, 0, w, h);
+ glow(g, w * 0.22, h * 0.18, w * 0.5, 'rgba(122,63,168,0.65)');
+ glow(g, w * 0.82, h * 0.78, w * 0.5, 'rgba(31,111,191,0.65)');
+ },
+ midnight: (g, w, h) => {
+ g.fillStyle = '#05060d';
+ g.fillRect(0, 0, w, h);
+ glow(g, w * 0.5, 0, w * 0.6, 'rgba(29,43,90,1)');
+ },
+ solana: (g, w, h) => {
+ g.fillStyle = '#0b0616';
+ g.fillRect(0, 0, w, h);
+ glow(g, w * 0.15, h * 0.85, w * 0.5, 'rgba(20,241,149,0.45)');
+ glow(g, w * 0.85, h * 0.15, w * 0.5, 'rgba(153,69,255,0.55)');
+ },
+ ember: (g, w, h) => {
+ g.fillStyle = '#160a0d';
+ g.fillRect(0, 0, w, h);
+ glow(g, w * 0.8, h, w * 0.55, 'rgba(255,106,44,0.55)');
+ glow(g, w * 0.1, h * 0.1, w * 0.45, 'rgba(122,31,74,0.55)');
+ },
+ graphite: (g, w, h) => {
+ const l = g.createLinearGradient(0, 0, w * 0.4, h);
+ l.addColorStop(0, '#2a2d33');
+ l.addColorStop(1, '#0d0e11');
+ g.fillStyle = l;
+ g.fillRect(0, 0, w, h);
+ },
+};
+
+function glow(g, x, y, r, color) {
+ const grad = g.createRadialGradient(x, y, 0, x, y, r);
+ grad.addColorStop(0, color);
+ grad.addColorStop(1, 'rgba(0,0,0,0)');
+ g.fillStyle = grad;
+ g.fillRect(0, 0, W, H);
+}
+
+function roundRect(g, x, y, w, h, r) {
+ g.beginPath();
+ g.moveTo(x + r, y);
+ g.arcTo(x + w, y, x + w, y + h, r);
+ g.arcTo(x + w, y + h, x, y + h, r);
+ g.arcTo(x, y + h, x, y, r);
+ g.arcTo(x, y, x + w, y, r);
+ g.closePath();
+}
+
+/**
+ * @param {{ apps: Array<{title:string, hue:number}> }} o
+ */
+export function createDesktopScreen({ apps }) {
+ const canvas = document.createElement('canvas');
+ canvas.width = W;
+ canvas.height = H;
+ const g = canvas.getContext('2d');
+ const texture = new CanvasTexture(canvas);
+ texture.colorSpace = SRGBColorSpace;
+ texture.anisotropy = 8;
+
+ let lastKey = '';
+ /**
+ * Redraw if anything changed. Cheap enough to call every frame; it only
+ * paints when the minute, wallpaper, name or prompt differs.
+ */
+ function draw({ wall = 'three', name = 'Guest', prompt = '', clock24 = false, accent = '#c4b5fd' } = {}) {
+ const d = new Date();
+ const time = d.toLocaleTimeString([], { hour: clock24 ? '2-digit' : 'numeric', minute: '2-digit', hour12: !clock24 });
+ const key = `${wall}|${name}|${prompt}|${time}|${accent}`;
+ if (key === lastKey) return false;
+ lastKey = key;
+
+ (WALLS[wall] || WALLS.three)(g, W, H);
+
+ // Desktop icons, left column, like the real shell.
+ g.textAlign = 'center';
+ apps.slice(0, 6).forEach((a, i) => {
+ const x = 46;
+ const y = 44 + i * 92;
+ g.fillStyle = `hsl(${a.hue} 60% 46%)`;
+ roundRect(g, x - 24, y - 24, 48, 48, 12);
+ g.fill();
+ g.fillStyle = 'rgba(255,255,255,0.9)';
+ g.font = '600 20px "Space Grotesk", Inter, sans-serif';
+ g.fillText(a.title[0], x, y + 7);
+ g.fillStyle = '#fff';
+ g.font = '500 13px Inter, system-ui, sans-serif';
+ g.fillText(a.title, x, y + 44, 84);
+ });
+
+ // Centre greeting.
+ g.fillStyle = 'rgba(255,255,255,0.55)';
+ g.font = '500 16px "JetBrains Mono", monospace';
+ g.fillText('THREE.WS OS', W / 2, H * 0.36);
+ g.fillStyle = '#fff';
+ g.font = '600 64px "Space Grotesk", Inter, sans-serif';
+ g.fillText(time, W / 2, H * 0.47);
+ g.font = '500 24px Inter, system-ui, sans-serif';
+ g.fillStyle = 'rgba(255,255,255,0.78)';
+ g.fillText(`Welcome back, ${name}.`, W / 2, H * 0.55);
+ if (prompt) {
+ g.font = '600 20px Inter, system-ui, sans-serif';
+ g.fillStyle = accent;
+ g.fillText(prompt, W / 2, H * 0.63);
+ }
+
+ // Taskbar.
+ g.fillStyle = 'rgba(10,10,14,0.78)';
+ g.fillRect(0, H - 56, W, 56);
+ g.fillStyle = 'rgba(255,255,255,0.08)';
+ g.fillRect(0, H - 56, W, 1);
+ const n = Math.min(apps.length, 8);
+ const start = W / 2 - (n * 48) / 2;
+ for (let i = 0; i < n; i++) {
+ g.fillStyle = `hsl(${apps[i].hue} 60% 46%)`;
+ roundRect(g, start + i * 48 + 8, H - 44, 32, 32, 9);
+ g.fill();
+ }
+ g.textAlign = 'right';
+ g.fillStyle = '#fff';
+ g.font = '500 15px Inter, system-ui, sans-serif';
+ g.fillText(time, W - 20, H - 24);
+ g.textAlign = 'center';
+
+ texture.needsUpdate = true;
+ return true;
+ }
+
+ return { texture, draw, dispose: () => texture.dispose() };
+}
diff --git a/src/desktop/world/ticker.js b/src/desktop/world/ticker.js
new file mode 100644
index 000000000..278b7c468
--- /dev/null
+++ b/src/desktop/world/ticker.js
@@ -0,0 +1,110 @@
+// The exchange's ticker board. Rows come from real market feeds: $THREE from
+// /api/three-token/stats and the top coins from /api/coin/markets. When a
+// feed is down the board says so instead of inventing numbers.
+
+import { CanvasTexture, SRGBColorSpace } from 'three';
+
+const W = 2048;
+const H = 192;
+
+function fmtPrice(p) {
+ if (p == null || !Number.isFinite(p)) return '--';
+ if (p >= 1000) return p.toLocaleString(undefined, { maximumFractionDigits: 0 });
+ if (p >= 1) return p.toFixed(2);
+ if (p >= 0.01) return p.toFixed(4);
+ return p.toPrecision(3);
+}
+function fmtPct(c) {
+ if (c == null || !Number.isFinite(c)) return '';
+ return `${c >= 0 ? '+' : ''}${c.toFixed(1)}%`;
+}
+
+/** Fetch the two feeds; always resolves. */
+export async function loadTickerItems(fetchFn = fetch) {
+ const items = [];
+ const notes = [];
+ const [three, markets] = await Promise.all([
+ fetchFn('/api/three-token/stats', { headers: { accept: 'application/json' } })
+ .then((r) => (r.ok ? r.json() : null))
+ .catch(() => null),
+ fetchFn('/api/coin/markets?per_page=12&sparkline=0', { headers: { accept: 'application/json' } })
+ .then((r) => (r.ok ? r.json() : null))
+ .catch(() => null),
+ ]);
+ const t = three?.token;
+ if (t && t.price_usd != null) items.push({ symbol: '$THREE', price: t.price_usd, change: t.price_change_24h, lead: true });
+ else notes.push('$THREE feed offline');
+ // /api/coin/markets answers { coins: [...] }; a bare array and { rows } are
+ // accepted too so a cached or older shape never blanks the board.
+ const rows = Array.isArray(markets) ? markets : markets?.coins || markets?.rows;
+ if (Array.isArray(rows) && rows.length) {
+ for (const r of rows) if (r?.symbol && r.price != null) items.push({ symbol: r.symbol, price: r.price, change: r.change_24h });
+ } else notes.push('market feed offline');
+ return { items, notes, three: t || null };
+}
+
+export function createTickerBoard() {
+ const canvas = document.createElement('canvas');
+ canvas.width = W;
+ canvas.height = H;
+ const g = canvas.getContext('2d');
+ const texture = new CanvasTexture(canvas);
+ texture.colorSpace = SRGBColorSpace;
+ texture.anisotropy = 8;
+
+ let items = [];
+ let notes = ['connecting to the market feed'];
+ let offset = 0;
+ let textW = 1;
+
+ function segments() {
+ if (!items.length) return notes.map((n) => ({ text: n.toUpperCase(), color: 'rgba(255,255,255,0.55)' }));
+ const out = items.map((it) => ({
+ text: `${it.symbol} ${fmtPrice(it.price)} ${fmtPct(it.change)}`,
+ color: it.lead ? '#c4b5fd' : it.change == null ? '#fff' : it.change >= 0 ? '#34d399' : '#f87171',
+ }));
+ for (const n of notes) out.push({ text: n.toUpperCase(), color: 'rgba(255,255,255,0.5)' });
+ return out;
+ }
+
+ function paint() {
+ g.fillStyle = '#07070a';
+ g.fillRect(0, 0, W, H);
+ g.fillStyle = 'rgba(255,255,255,0.08)';
+ g.fillRect(0, 0, W, 2);
+ g.fillRect(0, H - 2, W, 2);
+ g.font = '600 92px "JetBrains Mono", ui-monospace, monospace';
+ g.textBaseline = 'middle';
+ const segs = segments();
+ const gap = 120;
+ textW = segs.reduce((n, s) => n + g.measureText(s.text).width + gap, 0) || 1;
+ // Draw two copies so the scroll wraps seamlessly.
+ for (let copy = 0; copy < 2; copy++) {
+ let x = -offset + copy * textW;
+ for (const s of segs) {
+ g.fillStyle = s.color;
+ g.fillText(s.text, x, H / 2 + 4);
+ x += g.measureText(s.text).width;
+ g.fillStyle = 'rgba(255,255,255,0.25)';
+ g.fillRect(x + gap / 2 - 2, H * 0.3, 4, H * 0.4);
+ x += gap;
+ }
+ }
+ texture.needsUpdate = true;
+ }
+
+ return {
+ texture,
+ setItems(next, nextNotes = []) {
+ items = next || [];
+ notes = nextNotes;
+ paint();
+ },
+ /** Scroll by dt seconds. 260 canvas px/s reads at a comfortable pace from the street. */
+ tick(dt) {
+ offset = (offset + dt * 260) % textW;
+ paint();
+ },
+ dispose: () => texture.dispose(),
+ };
+}
diff --git a/src/desktop/world/world.css b/src/desktop/world/world.css
new file mode 100644
index 000000000..073d4efc7
--- /dev/null
+++ b/src/desktop/world/world.css
@@ -0,0 +1,548 @@
+/* The campus HUD. Same language as the classic site: near-black, hairlines,
+ * Space Grotesk for display, JetBrains Mono for keys and numbers, violet accent. */
+
+.wd {
+ position: fixed;
+ inset: 0;
+ z-index: 900;
+ background: #050505;
+ color: #fff;
+ font: 14px/1.4 'Inter', system-ui, sans-serif;
+ --wd-violet: #c4b5fd;
+ --wd-line: rgba(255, 255, 255, 0.08);
+ --wd-glass: rgba(10, 10, 12, 0.72);
+}
+.wd[hidden] {
+ display: none;
+}
+.in-world #os {
+ visibility: hidden;
+}
+.wd-canvas {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ display: block;
+ touch-action: none;
+ outline: none;
+}
+.wd-hud {
+ position: absolute;
+ inset: 0;
+ pointer-events: none;
+}
+.wd-hud > * {
+ pointer-events: auto;
+}
+.wd.is-xr .wd-hud {
+ display: none;
+}
+
+/* ---- top bar ---- */
+.wd-top {
+ position: absolute;
+ top: 0;
+ left: 0;
+ right: 0;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ padding: 14px 16px;
+ padding-top: max(14px, env(safe-area-inset-top));
+ pointer-events: none;
+}
+.wd-top > * {
+ pointer-events: auto;
+}
+.wd-brand {
+ display: flex;
+ align-items: baseline;
+ gap: 10px;
+ padding: 8px 14px;
+ border: 1px solid var(--wd-line);
+ border-radius: 999px;
+ background: var(--wd-glass);
+ backdrop-filter: blur(14px);
+ -webkit-backdrop-filter: blur(14px);
+ font-family: 'Space Grotesk', 'Inter', sans-serif;
+}
+.wd-brand b {
+ font-weight: 600;
+ letter-spacing: -0.01em;
+}
+.wd-where {
+ color: rgba(255, 255, 255, 0.6);
+ font-size: 13px;
+}
+.wd-tools {
+ display: flex;
+ gap: 6px;
+}
+.wd-tool {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ height: 36px;
+ padding: 0 12px;
+ border: 1px solid var(--wd-line);
+ border-radius: 999px;
+ background: var(--wd-glass);
+ color: #fff;
+ font: 500 13px/1 'Inter', system-ui, sans-serif;
+ cursor: pointer;
+ backdrop-filter: blur(14px);
+ -webkit-backdrop-filter: blur(14px);
+ transition: background 0.15s, border-color 0.15s, transform 0.15s;
+}
+.wd-tool:hover {
+ background: rgba(255, 255, 255, 0.08);
+ border-color: rgba(255, 255, 255, 0.18);
+}
+.wd-tool:active {
+ transform: scale(0.97);
+}
+.wd-tool:focus-visible,
+.wd-place:focus-visible,
+.wd-x:focus-visible,
+.wd-phone-x:focus-visible,
+.wd-digbtn:focus-visible {
+ outline: 2px solid var(--wd-violet);
+ outline-offset: 2px;
+}
+.wd-tool svg {
+ width: 18px;
+ height: 18px;
+ fill: none;
+ stroke: currentColor;
+ stroke-width: 1.8;
+ stroke-linecap: round;
+ stroke-linejoin: round;
+}
+.wd-gems-pts {
+ font-family: 'JetBrains Mono', ui-monospace, monospace;
+ color: var(--wd-violet);
+}
+
+/* ---- prompt ---- */
+.wd-prompt {
+ position: absolute;
+ left: 50%;
+ bottom: 108px;
+ transform: translateX(-50%);
+ display: grid;
+ grid-template-columns: auto 1fr;
+ gap: 4px 12px;
+ align-items: center;
+ min-width: 260px;
+ max-width: min(92vw, 420px);
+ padding: 10px 14px;
+ border: 1px solid var(--wd-line);
+ border-radius: 14px;
+ background: var(--wd-glass);
+ backdrop-filter: blur(14px);
+ -webkit-backdrop-filter: blur(14px);
+ animation: wd-rise 0.22s ease-out;
+}
+.wd-prompt[hidden] {
+ display: none;
+}
+@keyframes wd-rise {
+ from {
+ opacity: 0;
+ transform: translate(-50%, 8px);
+ }
+}
+.wd-key {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ min-width: 30px;
+ height: 30px;
+ padding: 0 8px;
+ border: 1px solid rgba(255, 255, 255, 0.22);
+ border-bottom-width: 3px;
+ border-radius: 8px;
+ background: #111;
+ font: 600 12px 'JetBrains Mono', ui-monospace, monospace;
+ color: var(--wd-violet);
+ white-space: nowrap;
+}
+.wd-prompt-text {
+ display: flex;
+ flex-direction: column;
+ min-width: 0;
+}
+.wd-prompt-text b {
+ font-family: 'Space Grotesk', 'Inter', sans-serif;
+ font-weight: 600;
+ font-size: 15px;
+}
+.wd-prompt-text span {
+ color: rgba(255, 255, 255, 0.6);
+ font-size: 12.5px;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+.wd-dig {
+ grid-column: 1 / -1;
+ height: 4px;
+ border-radius: 2px;
+ background: rgba(255, 255, 255, 0.1);
+ overflow: hidden;
+}
+.wd-dig[hidden] {
+ display: none;
+}
+.wd-dig i {
+ display: block;
+ height: 100%;
+ width: 0;
+ background: linear-gradient(90deg, #8b5cf6, var(--wd-violet));
+}
+.wd-digbtn {
+ position: absolute;
+ right: 24px;
+ bottom: 120px;
+ width: 84px;
+ height: 84px;
+ border: 1px solid rgba(196, 181, 253, 0.5);
+ border-radius: 50%;
+ background: rgba(139, 92, 246, 0.25);
+ color: #fff;
+ font: 600 13px 'Inter', system-ui, sans-serif;
+ touch-action: none;
+ user-select: none;
+ -webkit-user-select: none;
+}
+.wd-digbtn[hidden] {
+ display: none;
+}
+.wd-digbtn:active {
+ background: rgba(139, 92, 246, 0.5);
+}
+
+/* ---- places strip ---- */
+.wd-places {
+ position: absolute;
+ left: 50%;
+ bottom: 0;
+ transform: translateX(-50%);
+ display: flex;
+ gap: 6px;
+ max-width: 100vw;
+ padding: 10px 16px;
+ padding-bottom: max(14px, env(safe-area-inset-bottom));
+ overflow-x: auto;
+ scrollbar-width: none;
+}
+.wd-places::-webkit-scrollbar {
+ display: none;
+}
+.wd-place {
+ flex: 0 0 auto;
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ height: 34px;
+ padding: 0 12px 0 10px;
+ border: 1px solid var(--wd-line);
+ border-radius: 999px;
+ background: var(--wd-glass);
+ color: rgba(255, 255, 255, 0.82);
+ font: 500 12.5px/1 'Inter', system-ui, sans-serif;
+ white-space: nowrap;
+ cursor: pointer;
+ backdrop-filter: blur(14px);
+ -webkit-backdrop-filter: blur(14px);
+ transition: background 0.15s, color 0.15s, border-color 0.15s;
+}
+.wd-place:hover {
+ color: #fff;
+ background: rgba(255, 255, 255, 0.08);
+ border-color: rgba(255, 255, 255, 0.18);
+}
+.wd-place:active {
+ background: rgba(255, 255, 255, 0.12);
+}
+.wd-place i {
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ background: hsl(var(--h) 60% 62%);
+ box-shadow: 0 0 10px hsl(var(--h) 60% 62% / 0.8);
+}
+
+/* ---- touch stick ---- */
+.wd-stick {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 104px;
+ height: 104px;
+ border: 1px solid rgba(255, 255, 255, 0.18);
+ border-radius: 50%;
+ background: rgba(255, 255, 255, 0.05);
+ pointer-events: none;
+}
+.wd-stick[hidden] {
+ display: none;
+}
+.wd-stick i {
+ position: absolute;
+ left: 50%;
+ top: 50%;
+ width: 44px;
+ height: 44px;
+ margin: -22px 0 0 -22px;
+ border-radius: 50%;
+ background: rgba(196, 181, 253, 0.7);
+}
+
+/* ---- toasts ---- */
+.wd-toasts {
+ position: absolute;
+ left: 50%;
+ top: 76px;
+ transform: translateX(-50%);
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 6px;
+ pointer-events: none;
+}
+.wd-toast {
+ --c: #c4b5fd;
+ padding: 8px 14px;
+ border: 1px solid color-mix(in srgb, var(--c) 50%, transparent);
+ border-radius: 999px;
+ background: var(--wd-glass);
+ color: #fff;
+ font: 600 13px 'Space Grotesk', 'Inter', sans-serif;
+ box-shadow: 0 0 24px color-mix(in srgb, var(--c) 35%, transparent);
+ animation: wd-toast 3.2s ease-out forwards;
+}
+@keyframes wd-toast {
+ 0% {
+ opacity: 0;
+ transform: translateY(-6px);
+ }
+ 10%,
+ 80% {
+ opacity: 1;
+ transform: none;
+ }
+ 100% {
+ opacity: 0;
+ transform: translateY(-6px);
+ }
+}
+
+/* ---- gem panel ---- */
+.wd-gempanel {
+ position: absolute;
+ top: 64px;
+ right: 16px;
+ width: min(320px, calc(100vw - 32px));
+ border: 1px solid var(--wd-line);
+ border-radius: 16px;
+ background: rgba(10, 10, 12, 0.9);
+ backdrop-filter: blur(18px);
+ -webkit-backdrop-filter: blur(18px);
+ box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
+ animation: wd-rise 0.2s ease-out;
+}
+.wd-gempanel[hidden] {
+ display: none;
+}
+.wd-gempanel header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 12px 10px 10px 16px;
+ border-bottom: 1px solid var(--wd-line);
+ font-family: 'Space Grotesk', 'Inter', sans-serif;
+}
+.wd-x {
+ display: inline-grid;
+ place-items: center;
+ width: 30px;
+ height: 30px;
+ border: 0;
+ border-radius: 8px;
+ background: transparent;
+ color: rgba(255, 255, 255, 0.7);
+ cursor: pointer;
+}
+.wd-x:hover {
+ background: rgba(255, 255, 255, 0.08);
+ color: #fff;
+}
+.wd-x svg {
+ width: 16px;
+ height: 16px;
+ fill: none;
+ stroke: currentColor;
+ stroke-width: 1.8;
+}
+.wd-gemlist {
+ list-style: none;
+ margin: 0;
+ padding: 8px 0;
+}
+.wd-gemlist li {
+ display: grid;
+ grid-template-columns: 14px 1fr auto auto;
+ align-items: center;
+ gap: 10px;
+ padding: 6px 16px;
+}
+.wd-gemlist li.is-empty {
+ opacity: 0.45;
+}
+.wd-gemlist i {
+ width: 10px;
+ height: 10px;
+ transform: rotate(45deg);
+ background: var(--c);
+ box-shadow: 0 0 10px var(--c);
+}
+.wd-gemlist small {
+ color: rgba(255, 255, 255, 0.5);
+ font-family: 'JetBrains Mono', ui-monospace, monospace;
+ font-size: 11px;
+}
+.wd-gemlist b {
+ min-width: 2ch;
+ text-align: right;
+ font-family: 'JetBrains Mono', ui-monospace, monospace;
+}
+.wd-gemfoot {
+ margin: 0;
+ padding: 10px 16px 14px;
+ border-top: 1px solid var(--wd-line);
+ color: rgba(255, 255, 255, 0.6);
+ font-size: 12.5px;
+}
+
+/* ---- phone ---- */
+.wd-phone {
+ position: absolute;
+ inset: 0;
+ z-index: 2;
+ display: grid;
+ place-items: center;
+ background: rgba(0, 0, 0, 0.55);
+ backdrop-filter: blur(6px);
+ -webkit-backdrop-filter: blur(6px);
+ animation: wd-fadein 0.25s ease-out;
+}
+.wd-phone[hidden] {
+ display: none;
+}
+@keyframes wd-fadein {
+ from {
+ opacity: 0;
+ }
+}
+.wd-phone-frame {
+ position: relative;
+ width: min(400px, 94vw);
+ height: min(820px, 92vh);
+ padding: 14px;
+ border: 1px solid rgba(255, 255, 255, 0.14);
+ border-radius: 44px;
+ background: #0b0b0e;
+ box-shadow: 0 40px 120px rgba(0, 0, 0, 0.7), inset 0 0 0 2px #1a1a20;
+ animation: wd-lift 0.35s cubic-bezier(0.2, 0.8, 0.2, 1);
+}
+@keyframes wd-lift {
+ from {
+ transform: translateY(40px) scale(0.96);
+ opacity: 0;
+ }
+}
+.wd-phone-frame iframe {
+ width: 100%;
+ height: 100%;
+ border: 0;
+ border-radius: 32px;
+ background: #000;
+}
+.wd-phone-x {
+ position: absolute;
+ top: -14px;
+ right: -14px;
+ display: grid;
+ place-items: center;
+ width: 40px;
+ height: 40px;
+ border: 1px solid var(--wd-line);
+ border-radius: 50%;
+ background: #15151a;
+ color: #fff;
+ cursor: pointer;
+}
+.wd-phone-x svg {
+ width: 18px;
+ height: 18px;
+ fill: none;
+ stroke: currentColor;
+ stroke-width: 1.8;
+}
+.wd-phone-x:hover {
+ background: #222228;
+}
+
+/* ---- fade ---- */
+.wd-fade {
+ position: absolute;
+ inset: 0;
+ z-index: 3;
+ display: grid;
+ place-items: center;
+ background: #050505;
+ opacity: 0;
+ pointer-events: none;
+ transition: opacity 0.55s ease;
+}
+.wd-fade.is-on {
+ opacity: 1;
+ pointer-events: auto;
+}
+.wd-fade-cap {
+ margin: 0;
+ font: 500 15px 'Space Grotesk', 'Inter', sans-serif;
+ color: rgba(255, 255, 255, 0.7);
+ letter-spacing: 0.02em;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .wd-fade {
+ transition: none;
+ }
+ .wd-prompt,
+ .wd-gempanel,
+ .wd-phone,
+ .wd-phone-frame {
+ animation: none;
+ }
+}
+@media (max-width: 640px) {
+ .wd-tool span {
+ display: none;
+ }
+ .wd-tool .wd-gems-pts {
+ display: inline;
+ }
+ .wd-prompt {
+ bottom: 72px;
+ min-width: 0;
+ width: calc(100vw - 32px);
+ }
+ .wd-digbtn {
+ bottom: 150px;
+ }
+}
diff --git a/src/desktop/world/xr.js b/src/desktop/world/xr.js
new file mode 100644
index 000000000..fcbca90f1
--- /dev/null
+++ b/src/desktop/world/xr.js
@@ -0,0 +1,41 @@
+// WebXR for the world. VR is the only headset mode here; AR lives in src/ar.
+// When no immersive-vr runtime exists the caller is told plainly, so the
+// headset on the desk can offer first-person view instead of a silent no-op.
+
+export async function vrSupported() {
+ try {
+ return !!(navigator.xr && (await navigator.xr.isSessionSupported('immersive-vr')));
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Start an immersive-vr session on `renderer`. The XR camera rig is placed
+ * at the player's feet so the visitor stands where their avatar stood.
+ * @param {import('three').WebGLRenderer} renderer
+ * @param {{ onEnd?: () => void }} [o]
+ * @returns {Promise<XRSession>}
+ */
+export async function enterVR(renderer, { onEnd } = {}) {
+ if (!(await vrSupported())) throw new Error('No VR headset is available in this browser.');
+ renderer.xr.enabled = true;
+ renderer.xr.setReferenceSpaceType('local-floor');
+ let session;
+ try {
+ session = await navigator.xr.requestSession('immersive-vr', { optionalFeatures: ['local-floor', 'bounded-floor', 'hand-tracking'] });
+ } catch (err) {
+ renderer.xr.enabled = false;
+ throw err;
+ }
+ session.addEventListener(
+ 'end',
+ () => {
+ renderer.xr.enabled = false;
+ onEnd?.();
+ },
+ { once: true },
+ );
+ await renderer.xr.setSession(session);
+ return session;
+}
diff --git a/src/docs-world/controls.js b/src/docs-world/controls.js
index d5578ea1a..598bc1a50 100644
--- a/src/docs-world/controls.js
+++ b/src/docs-world/controls.js
@@ -29,8 +29,11 @@ export function createControls(canvas, { onTap, onInteract, onCycleCamera } = {}
const t = e.target;
return t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable);
}
+ // A host that hands the keyboard to something else (the desktop once the
+ // player sits down) flips `enabled` off; held keys are released at once.
+ let enabled = true;
addEventListener('keydown', (e) => {
- if (isTypingTarget(e)) return;
+ if (!enabled || isTypingTarget(e)) return;
const k = e.key.toLowerCase();
keys.add(k);
if (k === 'e' || k === 'enter') onInteract?.();
@@ -49,6 +52,7 @@ export function createControls(canvas, { onTap, onInteract, onCycleCamera } = {}
let orbitPointer = null;
canvas.addEventListener('pointerdown', (e) => {
+ if (!enabled) return;
// Touch in the joystick zone belongs to the joystick.
if (e.pointerType === 'touch' && inJoystickZone(e)) {
joystick.active = true;
@@ -124,6 +128,18 @@ export function createControls(canvas, { onTap, onInteract, onCycleCamera } = {}
return {
orbit,
joystick,
+ get enabled() {
+ return enabled;
+ },
+ set enabled(v) {
+ enabled = !!v;
+ if (!enabled) {
+ keys.clear();
+ joystick.active = false;
+ joystick.x = 0;
+ joystick.y = 0;
+ }
+ },
/** Screen-space movement vector, |v| <= 1. x: right, z: forward. */
readMove() {
let x = 0;
diff --git a/src/docs-world/player.js b/src/docs-world/player.js
index 15535726a..8907aa29b 100644
--- a/src/docs-world/player.js
+++ b/src/docs-world/player.js
@@ -73,9 +73,15 @@ function fallbackBody() {
/**
* @param {import('three').Scene} scene
* @param {import('three').WebGLRenderer} renderer
- * @param {{ avatarUrl?: string }} [opts]
+ * @param {{ avatarUrl?: string, spawn?: {x:number, z:number}, yaw?: number, bound?: number, keepout?: number }} [opts]
+ * `spawn`, `yaw`, `bound` and `keepout` default to the docs plaza; other worlds
+ * (the desktop campus) pass their own layout and reuse the same body.
*/
-export function createPlayer(scene, renderer, { avatarUrl = DEFAULT_BODY_GLB } = {}) {
+export function createPlayer(
+ scene,
+ renderer,
+ { avatarUrl = DEFAULT_BODY_GLB, spawn = { x: 1.2, z: 3.4 }, yaw = Math.PI, bound = WORLD_RADIUS, keepout = PAVILION_KEEPOUT } = {},
+) {
const root = new Group();
// Spawn a few metres off plaza centre: the beacon monolith stands at the
// exact origin and would otherwise occlude the freshly-loaded avatar.
@@ -89,8 +95,8 @@ export function createPlayer(scene, renderer, { avatarUrl = DEFAULT_BODY_GLB } =
// shrinks with the aspect ratio, so on a portrait phone the sign spans ~0.47
// of NDC width on its own and an offset past ~1.5m clips it off the left.
// 1.2m clears the avatar and still leaves the sign fully framed at 390px.
- root.position.set(1.2, 0, 3.4);
- root.rotation.y = Math.PI;
+ root.position.set(spawn.x, 0, spawn.z);
+ root.rotation.y = yaw;
scene.add(root);
const anim = new AnimationManager();
@@ -162,7 +168,7 @@ export function createPlayer(scene, renderer, { avatarUrl = DEFAULT_BODY_GLB } =
* @param {{x:number, z:number}} move input vector in camera space, |v| <= 1
* @param {number} camYaw camera yaw so input is screen-relative
* @param {boolean} run
- * @param {Array<{group: import('three').Group}>} pavilions keep-out volumes
+ * @param {Array<{group: import('three').Group, keepout?: number}>} pavilions keep-out volumes
*/
function update(dt, move, camYaw, run, pavilions) {
running = run;
@@ -189,19 +195,21 @@ export function createPlayer(scene, renderer, { avatarUrl = DEFAULT_BODY_GLB } =
// World bound: soft clamp to the walkable disc.
const dist = Math.hypot(root.position.x, root.position.z);
- if (dist > WORLD_RADIUS) {
- root.position.x *= WORLD_RADIUS / dist;
- root.position.z *= WORLD_RADIUS / dist;
+ if (dist > bound) {
+ root.position.x *= bound / dist;
+ root.position.z *= bound / dist;
}
- // Pavilion keep-out: push out radially so portals stay walk-aroundable.
+ // Keep-out: push out radially so portals and props stay walk-aroundable.
+ // A volume may carry its own `keepout` radius; the world default applies otherwise.
if (pavilions) {
for (const p of pavilions) {
const dx = root.position.x - p.group.position.x;
const dz = root.position.z - p.group.position.z;
const d = Math.hypot(dx, dz);
- if (d > 0.001 && d < PAVILION_KEEPOUT) {
- const push = PAVILION_KEEPOUT / d;
+ const r = p.keepout ?? keepout;
+ if (d > 0.001 && d < r) {
+ const push = r / d;
root.position.x = p.group.position.x + dx * push;
root.position.z = p.group.position.z + dz * push;
}
diff --git a/src/docs-world/world.js b/src/docs-world/world.js
index d969fc763..e82ff9fc3 100644
--- a/src/docs-world/world.js
+++ b/src/docs-world/world.js
@@ -118,7 +118,7 @@ const BEACON_LABEL_SCALE = 0.8;
const BEACON_LABEL_W = 6.4 * BEACON_LABEL_SCALE;
const BEACON_LABEL_H = 2 * BEACON_LABEL_SCALE;
-function makeLabelSprite(title, sub, colorHex, scale = 1) {
+export function makeLabelSprite(title, sub, colorHex, scale = 1) {
const material = new SpriteMaterial({
map: makeLabelTexture(title, sub, colorHex),
transparent: true,
@@ -171,7 +171,7 @@ function makeGroundTexture(sectionCount) {
return tex;
}
-function makeSkyDome() {
+export function makeSkyDome() {
// Vertex-coloured dome: near-black zenith into a purple horizon glow.
const geo = new SphereGeometry(220, 24, 12);
const pos = geo.attributes.position;
@@ -194,7 +194,7 @@ function makeSkyDome() {
);
}
-function makeStars(count = 420) {
+export function makeStars(count = 420) {
const positions = new Float32Array(count * 3);
for (let i = 0; i < count; i++) {
// Random point on an upper-hemisphere shell so stars never sit below the
diff --git a/tests/desktop-boot.test.js b/tests/desktop-boot.test.js
new file mode 100644
index 000000000..de0b3dafb
--- /dev/null
+++ b/tests/desktop-boot.test.js
@@ -0,0 +1,117 @@
+import { describe, it, expect } from 'vitest';
+import { runBootSteps, snapshotOf, formatMs, greeting, entryMode, showBoot, bootSummary, gpuName } from '../src/desktop/boot-logic.js';
+
+describe('desktop boot sequence', () => {
+ it('runs every step concurrently and reports ok, skip and fail with timings', async () => {
+ let t = 100;
+ const now = () => (t += 10);
+ const seen = [];
+ const snap = await runBootSteps(
+ [
+ { id: 'a', label: 'A', task: async () => 'fine' },
+ { id: 'b', label: 'B', task: async () => ({ skip: 'not needed' }) },
+ { id: 'c', label: 'C', task: async () => { throw new Error('boom'); } },
+ { id: 'd', label: 'D', task: async () => ({ value: 42 }) },
+ ],
+ (s) => seen.push(s.done),
+ now,
+ );
+ expect(snap.complete).toBe(true);
+ expect(snap.total).toBe(4);
+ expect(snap.failed).toEqual(['c']);
+ const by = Object.fromEntries(snap.steps.map((s) => [s.id, s]));
+ expect(by.a).toMatchObject({ state: 'ok', detail: 'fine' });
+ expect(by.b).toMatchObject({ state: 'skip', detail: 'not needed' });
+ expect(by.c).toMatchObject({ state: 'fail', detail: 'boom' });
+ expect(by.d.state).toBe('ok');
+ expect(by.d.value).toEqual({ value: 42 });
+ expect(by.d.detail).toBe('');
+ snap.steps.forEach((s) => expect(s.ms).toBeGreaterThan(0));
+ // First emit is the all-running snapshot, then one per settled step.
+ expect(seen[0]).toBe(0);
+ expect(seen.at(-1)).toBe(4);
+ expect(seen.length).toBe(5);
+ });
+
+ it('snapshots progress as a fraction of settled steps', () => {
+ const s = snapshotOf([
+ { id: 'a', state: 'ok' },
+ { id: 'b', state: 'running' },
+ { id: 'c', state: 'fail' },
+ { id: 'd', state: 'pending' },
+ ]);
+ expect(s.done).toBe(2);
+ expect(s.progress).toBe(0.5);
+ expect(s.complete).toBe(false);
+ expect(s.failed).toEqual(['c']);
+ expect(snapshotOf([]).progress).toBe(1);
+ });
+
+ it('formats timings for the log column', () => {
+ expect(formatMs(12.4)).toBe('12ms');
+ expect(formatMs(1234)).toBe('1.23s');
+ expect(formatMs(-1)).toBe('');
+ expect(formatMs(NaN)).toBe('');
+ });
+
+ it('greets by time of day, name and return visit', () => {
+ expect(greeting(3, '', false)).toBe('Still up. Welcome to three.ws.');
+ expect(greeting(9, 'Ada', false)).toBe('Good morning, Ada.');
+ expect(greeting(14, '', true)).toBe('Good afternoon. Welcome back.');
+ expect(greeting(19, ' ', true)).toBe('Good evening. Welcome back.');
+ expect(greeting(23, '', false)).toBe('Working late. Welcome to three.ws.');
+ expect(greeting(NaN, '', false)).toBe('Good afternoon. Welcome to three.ws.');
+ });
+
+ it('summarises what the boot found', () => {
+ expect(bootSummary(null)).toBe('');
+ expect(bootSummary({ failed: [], steps: [] })).toBe('Every system is up.');
+ expect(bootSummary({ failed: ['market'], steps: [] }, { market: '$THREE feed' })).toBe('$THREE feed is offline. Everything else is up.');
+ expect(bootSummary({ failed: ['a', 'b', 'c'], steps: [] }, { a: 'A', b: 'B' })).toBe('A, B and c are offline.');
+ });
+});
+
+describe('entry mode', () => {
+ it('defaults to the world and honours the start-in preference', () => {
+ expect(entryMode({})).toBe('world');
+ expect(entryMode({ prefs: { startIn: 'desktop' } })).toBe('desktop');
+ expect(entryMode({ prefs: { startIn: 'world' } })).toBe('world');
+ });
+ it('lets deep links and explicit view choices win', () => {
+ expect(entryMode({ deepLink: 'forge' })).toBe('desktop');
+ expect(entryMode({ search: '?view=desktop' })).toBe('desktop');
+ expect(entryMode({ search: '?world=0' })).toBe('desktop');
+ expect(entryMode({ search: '?world=1', prefs: { startIn: 'desktop' } })).toBe('world');
+ expect(entryMode({ hash: '#world', prefs: { startIn: 'desktop' } })).toBe('world');
+ });
+ it('never sends a browser without WebGL into the 3D lobby', () => {
+ expect(entryMode({ webgl: false })).toBe('desktop');
+ expect(entryMode({ search: '?world=1', webgl: false })).toBe('desktop');
+ });
+ it('keeps phones in the world unless they opted out', () => {
+ expect(entryMode({ mobile: true })).toBe('world');
+ expect(entryMode({ mobile: true, prefs: { startIn: 'world' } })).toBe('world');
+ expect(entryMode({ mobile: true, prefs: { startIn: 'desktop' } })).toBe('desktop');
+ });
+ it('skips the boot screen only on ?boot=0', () => {
+ expect(showBoot('')).toBe(true);
+ expect(showBoot('?boot=1')).toBe(true);
+ expect(showBoot('?boot=0')).toBe(false);
+ });
+});
+
+describe('boot line details', () => {
+ it('shows a detail string carried on an object result', async () => {
+ const snap = await runBootSteps([{ id: 'm', label: 'M', task: async () => ({ price: 1, detail: '$1.00 +2.0%' }) }], null);
+ expect(snap.steps[0].detail).toBe('$1.00 +2.0%');
+ expect(snap.steps[0].value.price).toBe(1);
+ });
+ it('shortens the renderer string to a GPU name', () => {
+ expect(gpuName('ANGLE (NVIDIA, NVIDIA GeForce RTX 3080 Direct3D11 vs_5_0 ps_5_0, D3D11)')).toBe('NVIDIA GeForce RTX 3080');
+ expect(gpuName('Google, Vulkan 1.3.0 (SwiftShader Device (Subzero) (0x0000C0DE)), SwiftShader driver')).toBe('SwiftShader Device');
+ expect(gpuName('ANGLE (Apple, ANGLE Metal Renderer: Apple M2, Unspecified Version)')).toBe('Apple M2');
+ expect(gpuName('Mali-G78')).toBe('Mali-G78');
+ expect(gpuName('')).toBe('WebGL');
+ expect(gpuName('x'.repeat(60)).length).toBeLessThanOrEqual(40);
+ });
+});
diff --git a/tests/desktop-page.test.js b/tests/desktop-page.test.js
index 10711efe3..495ef8b43 100644
--- a/tests/desktop-page.test.js
+++ b/tests/desktop-page.test.js
@@ -15,6 +15,7 @@ describe('desktop page', () => {
it('lists every windowed app as a crawlable link', () => {
for (const app of APPS) expect(html, app.title).toContain(`href="${app.href}"`);
expect(html).toContain('href="/classic"');
+ expect(html).toContain('href="/?world=1"');
});
it('only registers apps with same-origin paths and unique ids', () => {
diff --git a/tests/world-places.test.js b/tests/world-places.test.js
new file mode 100644
index 000000000..167f8d5cf
--- /dev/null
+++ b/tests/world-places.test.js
@@ -0,0 +1,151 @@
+import { describe, it, expect } from 'vitest';
+import { readFileSync, existsSync } from 'node:fs';
+import { resolve, dirname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { ALL_APPS } from '../src/desktop/apps.js';
+import {
+ CAMPUS_RADIUS,
+ SPAWN,
+ PLACES,
+ VEINS,
+ DESK_OBJECTS,
+ PLACE_TRIGGER,
+ OBJECT_TRIGGER,
+ placeById,
+ nearestInteractable,
+ facingOf,
+ standPointFor,
+ dist2,
+} from '../src/desktop/world/places.js';
+import { GEMS, GEM_BY_ID, NODES, DAILY_DIG_CAP, MIN_DIG_INTERVAL_MS, validAnonId, validNode, rollGem, digAllowed, totalPoints, summarize } from '../api/_lib/world-gems.js';
+
+const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+
+describe('campus places', () => {
+ it('opens only real desktop apps', () => {
+ const ids = new Set(ALL_APPS.map((a) => a.id));
+ for (const p of PLACES.filter((p) => p.kind === 'app')) expect(ids.has(p.app), `${p.id} -> ${p.app}`).toBe(true);
+ expect(PLACES.filter((p) => p.kind === 'office')).toHaveLength(1);
+ expect(PLACES.filter((p) => p.kind === 'mine')).toHaveLength(1);
+ });
+ it('has unique ids and keeps every place and the spawn inside the walkable disc', () => {
+ expect(new Set(PLACES.map((p) => p.id)).size).toBe(PLACES.length);
+ for (const p of PLACES) expect(Math.hypot(p.x, p.z) + p.keepout, p.id).toBeLessThan(CAMPUS_RADIUS);
+ expect(Math.hypot(SPAWN.x, SPAWN.z)).toBeLessThan(CAMPUS_RADIUS);
+ });
+ it('spaces buildings so no two keep-outs overlap and the trigger zones are reachable', () => {
+ for (let i = 0; i < PLACES.length; i++) {
+ for (let j = i + 1; j < PLACES.length; j++) {
+ const a = PLACES[i];
+ const b = PLACES[j];
+ const d = Math.sqrt(dist2(a.x, a.z, b.x, b.z));
+ expect(d, `${a.id} vs ${b.id}`).toBeGreaterThan(a.keepout + b.keepout + PLACE_TRIGGER);
+ }
+ }
+ });
+ it('faces every building toward the campus centre and stands the player in front of it', () => {
+ for (const p of PLACES) {
+ const s = standPointFor(p);
+ // The stand point is nearer the origin than the building is.
+ expect(Math.hypot(s.x, s.z)).toBeLessThan(Math.hypot(p.x, p.z) + 0.001);
+ // It sits just outside the keep-out, inside the trigger zone.
+ const d = Math.sqrt(dist2(s.x, s.z, p.x, p.z));
+ expect(d).toBeGreaterThan(p.keepout);
+ expect(d).toBeLessThan(p.keepout + PLACE_TRIGGER);
+ // And the player faces the building: walking along their yaw moves them closer.
+ const step = { x: s.x + Math.sin(s.yaw) * 0.5, z: s.z + Math.cos(s.yaw) * 0.5 };
+ expect(dist2(step.x, step.z, p.x, p.z)).toBeLessThan(d * d);
+ }
+ expect(facingOf({ x: 0, z: -10 })).toBeCloseTo(0);
+ expect(facingOf({ x: 10, z: 0 })).toBeCloseTo(-Math.PI / 2);
+ });
+ it('names the mine veins exactly as the gem API does', () => {
+ expect(VEINS.map((v) => v.id).sort()).toEqual([...NODES].sort());
+ expect(new Set(DESK_OBJECTS.map((o) => o.id)).size).toBe(DESK_OBJECTS.length);
+ expect(placeById('nope')).toBeNull();
+ });
+ it('picks the nearest desk object, then vein, then place', () => {
+ const office = placeById('office');
+ const monitor = DESK_OBJECTS.find((o) => o.id === 'monitor');
+ expect(nearestInteractable(office.x + monitor.dx, office.z + monitor.dz + 0.5)).toMatchObject({ type: 'object', id: 'monitor' });
+ const veins = [{ id: 'vein-a', x: 0, z: -33 }];
+ expect(nearestInteractable(0.3, -33, { veinPositions: veins })).toMatchObject({ type: 'vein', id: 'vein-a' });
+ expect(nearestInteractable(0, -33 - OBJECT_TRIGGER - 1, { veinPositions: veins })).toBeNull();
+ const ex = placeById('exchange');
+ const s = standPointFor(ex);
+ expect(nearestInteractable(s.x, s.z)).toMatchObject({ type: 'place', id: 'exchange' });
+ expect(nearestInteractable(0, 0)).toBeNull();
+ });
+});
+
+describe('gem mining rules', () => {
+ it('ships the API handler and its migration', () => {
+ expect(existsSync(resolve(root, 'api/world/gems.js'))).toBe(true);
+ expect(existsSync(resolve(root, 'api/_lib/migrations/20261015000000_world_gems.sql'))).toBe(true);
+ expect(readFileSync(resolve(root, 'api/_lib/migrations/20261015000000_world_gems.sql'), 'utf8')).toContain('world_gems');
+ });
+ it('weights sum to a thousand so the roll is exact', () => {
+ expect(GEMS.reduce((n, g) => n + g.weight, 0)).toBe(1000);
+ for (const g of GEMS) expect(GEM_BY_ID[g.id]).toBe(g);
+ });
+ it('rolls the common gem at the bottom of the range and the rarest at the top', () => {
+ expect(rollGem(0).id).toBe(GEMS[0].id);
+ expect(rollGem(0.9999).id).toBe(GEMS.at(-1).id);
+ const seen = new Set();
+ for (let i = 0; i < 1000; i++) seen.add(rollGem(i / 1000).id);
+ expect(seen.size).toBe(GEMS.length);
+ });
+ it('validates nodes and anonymous ids', () => {
+ expect(validNode('vein-a')).toBe(true);
+ expect(validNode('vein-z')).toBe(false);
+ expect(validAnonId('anon_0f5e2c1a-3b4d-4e5f-8a6b-7c8d9e0f1a2b')).toBe(true);
+ expect(validAnonId('anon_x')).toBe(false);
+ expect(validAnonId('')).toBe(false);
+ });
+ it('rate limits a dig on the server floor', () => {
+ const now = 1_000_000;
+ expect(digAllowed(null, now)).toBe(true);
+ expect(digAllowed(undefined, now)).toBe(true);
+ expect(digAllowed(NaN, now)).toBe(true);
+ expect(digAllowed(now - MIN_DIG_INTERVAL_MS / 2, now)).toBe(false);
+ expect(digAllowed(now - MIN_DIG_INTERVAL_MS, now)).toBe(true);
+ expect(DAILY_DIG_CAP).toBeGreaterThan(0);
+ const handler = readFileSync(resolve(root, 'api/world/gems.js'), 'utf8');
+ expect(handler).toContain('DAILY_DIG_CAP');
+ expect(handler).toContain('daily_cap');
+ expect(handler).toContain('dig_too_soon');
+ });
+ it('totals points and summarises a ledger', () => {
+ const rows = [
+ { gem: GEMS[0].id, amount: 2 },
+ { gem: GEMS[1].id, amount: 1 },
+ ];
+ expect(totalPoints(rows)).toBe(GEMS[0].points * 2 + GEMS[1].points);
+ const s = summarize(rows);
+ expect(s.total).toBe(3);
+ expect(s.points).toBe(totalPoints(rows));
+ expect(s.gems[GEMS[0].id]).toBe(2);
+ expect(s.gems[GEMS.at(-1).id]).toBe(0);
+ expect(summarize([]).total).toBe(0);
+ });
+});
+
+describe('desk objects', () => {
+ it('arms the monitor, not the phone, when the player walks straight up to the desk', () => {
+ // Walking down the x=0 axis the desk's keep-out disc stops the player
+ // about 1.35 m in front of the monitor; the phone sits to one side and
+ // must not steal the prompt from there.
+ const office = placeById('office');
+ expect(nearestInteractable(0, office.z + 0.85)).toMatchObject({ type: 'object', id: 'monitor' });
+ expect(nearestInteractable(0.05, office.z + 0.9)).toMatchObject({ type: 'object', id: 'monitor' });
+ });
+ it('hands the prompt to the phone and the headset only at the side of the desk', () => {
+ const office = placeById('office');
+ const phone = DESK_OBJECTS.find((o) => o.id === 'phone');
+ const headset = DESK_OBJECTS.find((o) => o.id === 'headset');
+ expect(nearestInteractable(office.x + 1.35, office.z - 0.5)).toMatchObject({ type: 'object', id: 'phone' });
+ expect(nearestInteractable(office.x - 1.35, office.z - 0.5)).toMatchObject({ type: 'object', id: 'headset' });
+ expect(nearestInteractable(office.x + phone.dx, office.z + phone.dz + 1.6)).not.toMatchObject({ id: 'phone' });
+ expect(nearestInteractable(office.x + headset.dx, office.z + headset.dz + 1.6)).not.toMatchObject({ id: 'headset' });
+ });
+});
diff --git a/tests/world-ticker.test.js b/tests/world-ticker.test.js
new file mode 100644
index 000000000..de336c245
--- /dev/null
+++ b/tests/world-ticker.test.js
@@ -0,0 +1,34 @@
+import { describe, it, expect } from 'vitest';
+import { loadTickerItems } from '../src/desktop/world/ticker.js';
+
+const ok = (body) => Promise.resolve({ ok: true, json: () => Promise.resolve(body) });
+const down = () => Promise.resolve({ ok: false, json: () => Promise.reject(new Error('no body')) });
+
+describe('exchange ticker feed', () => {
+ it('reads the real market feed shape ({ coins }) and leads with $THREE', async () => {
+ const fetchFn = (url) => {
+ if (url.startsWith('/api/three-token/stats')) return ok({ token: { price_usd: 0.000504, price_change_24h: -0.1 } });
+ if (url.startsWith('/api/coin/markets')) return ok({ coins: [{ symbol: 'AAA', price: 83009, change_24h: 0.47 }, { symbol: 'BBB', price: 1800, change_24h: -1.2 }] });
+ return down();
+ };
+ const { items, notes } = await loadTickerItems(fetchFn);
+ expect(notes).toEqual([]);
+ expect(items[0]).toMatchObject({ symbol: '$THREE', price: 0.000504, lead: true });
+ expect(items.slice(1).map((i) => i.symbol)).toEqual(['AAA', 'BBB']);
+ expect(items[1].change).toBe(0.47);
+ });
+ it('still accepts a bare array or a rows field', async () => {
+ const bare = await loadTickerItems((url) => (url.startsWith('/api/coin/markets') ? ok([{ symbol: 'CCC', price: 150, change_24h: 2 }]) : down()));
+ expect(bare.items.map((i) => i.symbol)).toEqual(['CCC']);
+ const rows = await loadTickerItems((url) => (url.startsWith('/api/coin/markets') ? ok({ rows: [{ symbol: 'CCC', price: 150, change_24h: 2 }] }) : down()));
+ expect(rows.items.map((i) => i.symbol)).toEqual(['CCC']);
+ });
+ it('reports each feed that is down instead of inventing prices', async () => {
+ const { items, notes, three } = await loadTickerItems(() => down());
+ expect(items).toEqual([]);
+ expect(three).toBeNull();
+ expect(notes).toEqual(['$THREE feed offline', 'market feed offline']);
+ const thrown = await loadTickerItems(() => Promise.reject(new Error('network')));
+ expect(thrown.notes).toHaveLength(2);
+ });
+});