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(city): refine city map/world rendering; add mixamo avatar fetch script

nirholas4d0c1819c263
diff --git a/.gitignore b/.gitignore
index 3243a115f..aef66b2e4 100644
--- a/.gitignore
+++ b/.gitignore
@@ -126,4 +126,7 @@ scripts/load-test-fleet.sh
infra/cdk.out
# SoundCloud backup — local only, never commit
-sc/
\ No newline at end of file
+sc/
+
+# Debug screenshots from scripts — scratch output, never commit
+scripts/debug-*.png
diff --git a/multiplayer/package.json b/multiplayer/package.json
index edd514da7..38f984ec9 100644
--- a/multiplayer/package.json
+++ b/multiplayer/package.json
@@ -18,7 +18,7 @@
"@colyseus/monitor": "^0.16.7",
"@colyseus/redis-driver": "^0.16.0",
"@colyseus/redis-presence": "^0.16.0",
- "@colyseus/schema": "^3.0.0",
+ "@colyseus/schema": "3.0.76",
"@colyseus/ws-transport": "^0.16.5",
"@ethereum-attestation-service/eas-sdk": "0.29.1",
"@metaplex-foundation/js": "^0.20.1",
diff --git a/package.json b/package.json
index 2e35fa837..b9bef88c4 100644
--- a/package.json
+++ b/package.json
@@ -175,7 +175,7 @@
"bn.js": "^5.2.3",
"bs58": "^6.0.0",
"colyseus": "^0.17.10",
- "colyseus.js": "^0.16.22",
+ "colyseus.js": "0.16.22",
"dat.gui": "^0.7.9",
"ethers": "^6.16.0",
"express": "^4.22.1",
diff --git a/scripts/fetch-mixamo-avatars.mjs b/scripts/fetch-mixamo-avatars.mjs
new file mode 100644
index 000000000..d70234dd7
--- /dev/null
+++ b/scripts/fetch-mixamo-avatars.mjs
@@ -0,0 +1,349 @@
+#!/usr/bin/env node
+// Bulk-download Mixamo character avatars as FBX (With Skin).
+// Resumable: re-run to pick up where it left off.
+//
+// Usage:
+// MIXAMO_TOKEN=eyJ... node scripts/fetch-mixamo-avatars.mjs
+// # or put MIXAMO_TOKEN=... in .env.local
+//
+// Optional flags:
+// --concurrency=N parallel export jobs (default 2)
+// --limit=N stop after N successful downloads (default: all)
+// --format=fbx7|fbx6 output format (default fbx7)
+//
+// Prerequisites:
+// node scripts/get-mixamo-token.mjs (first-time login)
+
+import { mkdirSync, writeFileSync, existsSync, readFileSync, renameSync } from 'node:fs';
+import { join } from 'node:path';
+import { S3Client, PutObjectCommand, HeadObjectCommand } from '@aws-sdk/client-s3';
+
+// ── Config ────────────────────────────────────────────────────────────────
+const API = 'https://www.mixamo.com/api/v1';
+const PAGE_LIMIT = 96;
+const POLL_INTERVAL_MS = 3000;
+const POLL_MAX_ATTEMPTS = 60;
+
+const args = Object.fromEntries(
+ process.argv.slice(2).map((a) => {
+ const m = a.match(/^--([^=]+)(?:=(.*))?$/);
+ return m ? [m[1], m[2] ?? true] : [a, true];
+ }),
+);
+
+const CONCURRENCY = Number(args.concurrency) || 2;
+const MAX_DOWNLOADS = args.limit ? Number(args.limit) : Infinity;
+const FORMAT = args.format || 'fbx7';
+
+let globalCooldownUntil = 0;
+const RATE_LIMIT_BASE_MS = 30_000;
+const RATE_LIMIT_MAX_MS = 300_000;
+
+// ── Token loading ──────────────────────────────────────────────────────────
+function loadEnvVar(key) {
+ if (process.env[key]) return process.env[key].trim();
+ const envPath = join(process.cwd(), '.env.local');
+ if (existsSync(envPath)) {
+ const line = readFileSync(envPath, 'utf8').split('\n').find((l) => l.startsWith(`${key}=`));
+ if (line) return line.slice(key.length + 1).trim().replace(/^["']|["']$/g, '');
+ }
+ return null;
+}
+
+const TOKEN = loadEnvVar('MIXAMO_TOKEN');
+if (!TOKEN) {
+ console.error('MIXAMO_TOKEN not set. Run: node scripts/get-mixamo-token.mjs');
+ process.exit(1);
+}
+
+// ── R2 config ─────────────────────────────────────────────────────────────
+const R2_ACCOUNT_ID = loadEnvVar('R2_ACCOUNT_ID');
+const R2_ACCESS_KEY_ID = loadEnvVar('R2_ACCESS_KEY_ID');
+const R2_SECRET_ACCESS_KEY = loadEnvVar('R2_SECRET_ACCESS_KEY');
+const R2_BUCKET = loadEnvVar('R2_BUCKET') || 'test';
+const USE_R2 = !!(R2_ACCOUNT_ID && R2_ACCESS_KEY_ID && R2_SECRET_ACCESS_KEY);
+
+const r2 = USE_R2
+ ? new S3Client({
+ region: 'auto',
+ endpoint: `https://${R2_ACCOUNT_ID}.r2.cloudflarestorage.com`,
+ credentials: { accessKeyId: R2_ACCESS_KEY_ID, secretAccessKey: R2_SECRET_ACCESS_KEY },
+ })
+ : null;
+
+async function existsInR2(key) {
+ try {
+ await r2.send(new HeadObjectCommand({ Bucket: R2_BUCKET, Key: key }));
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+async function uploadToR2(key, buf) {
+ await r2.send(
+ new PutObjectCommand({
+ Bucket: R2_BUCKET,
+ Key: key,
+ Body: buf,
+ ContentType: 'application/octet-stream',
+ }),
+ );
+}
+
+const headers = {
+ Accept: 'application/json',
+ 'Content-Type': 'application/json',
+ Authorization: `Bearer ${TOKEN}`,
+ 'X-Api-Key': 'mixamo2',
+};
+
+// ── Output paths ──────────────────────────────────────────────────────────
+const OUT_DIR = join(process.cwd(), 'public', 'avatars', 'mixamo');
+const CATALOG_PATH = join(OUT_DIR, 'catalog.json');
+mkdirSync(OUT_DIR, { recursive: true });
+
+const catalog = existsSync(CATALOG_PATH)
+ ? JSON.parse(readFileSync(CATALOG_PATH, 'utf8'))
+ : { generated_at: null, avatars: {} };
+
+function saveCatalog() {
+ catalog.generated_at = new Date().toISOString();
+ const tmp = `${CATALOG_PATH}.tmp`;
+ writeFileSync(tmp, JSON.stringify(catalog, null, 2));
+ renameSync(tmp, CATALOG_PATH);
+}
+
+// ── Helpers ───────────────────────────────────────────────────────────────
+const slugify = (s) =>
+ s
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, 80);
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+async function waitForCooldown() {
+ while (Date.now() < globalCooldownUntil) {
+ await sleep(Math.min(2000, globalCooldownUntil - Date.now()));
+ }
+}
+
+function triggerCooldown(retryAfterSec, attempt) {
+ const explicit = retryAfterSec ? Number(retryAfterSec) * 1000 : 0;
+ const backoff = Math.min(RATE_LIMIT_BASE_MS * 2 ** attempt, RATE_LIMIT_MAX_MS);
+ const wait = Math.max(explicit, backoff);
+ const until = Date.now() + wait;
+ if (until > globalCooldownUntil) {
+ globalCooldownUntil = until;
+ console.log(`Rate limited — pausing ${(wait / 1000).toFixed(0)}s`);
+ }
+}
+
+async function rlFetch(url, init = {}, attempt = 0) {
+ await waitForCooldown();
+ const res = await fetch(url, init);
+ if (res.status === 429) {
+ triggerCooldown(res.headers.get('retry-after'), attempt);
+ if (attempt >= 6) throw new Error('429 (max retries)');
+ return rlFetch(url, init, attempt + 1);
+ }
+ return res;
+}
+
+async function api(path, init = {}) {
+ const res = await rlFetch(`${API}${path}`, { ...init, headers: { ...headers, ...init.headers } });
+ if (!res.ok) {
+ const body = await res.text().catch(() => '');
+ throw new Error(`HTTP ${res.status} ${path} ${body.slice(0, 200)}`);
+ }
+ return res.json();
+}
+
+// ── Step 1: list all Character products ──────────────────────────────────
+async function listAllCharacters() {
+ const all = [];
+ let page = 1;
+ while (true) {
+ process.stdout.write(`\rListing characters: page ${page} (${all.length} so far)... `);
+ const data = await api(
+ `/products?page=${page}&limit=${PAGE_LIMIT}&type=Character&order=relevance`,
+ );
+ const results = data.results || [];
+ all.push(...results);
+ const totalPages =
+ data.pagination?.num_pages ?? Math.ceil((data.pagination?.num_results ?? 0) / PAGE_LIMIT);
+ if (!totalPages || page >= totalPages || results.length === 0) break;
+ page += 1;
+ await sleep(200);
+ }
+ process.stdout.write('\n');
+ return all;
+}
+
+// ── Step 2: export + poll + download a single character ─────────────────
+async function downloadOne(product) {
+ const slug = slugify(product.description || product.name || product.id);
+ const r2Key = `avatars/mixamo/${slug}.fbx`;
+ const localPath = join(OUT_DIR, `${slug}.fbx`);
+ const existing = catalog.avatars[product.id];
+
+ if (existing?.status === 'completed') {
+ const alreadyExists = USE_R2 ? await existsInR2(r2Key) : existsSync(localPath);
+ if (alreadyExists) return { skipped: true, slug, reason: 'already-downloaded' };
+ }
+ if (existing?.status === 'permanent_fail') {
+ return { skipped: true, slug, reason: 'permanent-fail' };
+ }
+
+ // Fetch product details to get gms_hash
+ const productDetails = await api(`/products/${product.id}`);
+ const gmsHash = productDetails?.details?.gms_hash;
+ if (!gmsHash) {
+ catalog.avatars[product.id] = {
+ id: product.id,
+ name: product.description || product.name,
+ status: 'permanent_fail',
+ reason: 'no_gms_hash',
+ failed_at: new Date().toISOString(),
+ };
+ saveCatalog();
+ throw new Error('no gms_hash');
+ }
+
+ const exportRes = await rlFetch(`${API}/characters/export`, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({
+ product_id: product.id,
+ product_name: product.description || product.name,
+ type: 'Character',
+ gms_hash: [gmsHash],
+ preferences: { format: FORMAT, skin: 'true', fps: '30', reducekf: '0' },
+ }),
+ });
+
+ if (!exportRes.ok) {
+ const status = exportRes.status;
+ if (status === 400 || status === 404) {
+ catalog.avatars[product.id] = {
+ id: product.id,
+ name: product.description || product.name,
+ status: 'permanent_fail',
+ http: status,
+ failed_at: new Date().toISOString(),
+ };
+ saveCatalog();
+ }
+ throw new Error(`export ${status}`);
+ }
+
+ let downloadUrl = null;
+ for (let i = 0; i < POLL_MAX_ATTEMPTS; i++) {
+ await sleep(POLL_INTERVAL_MS);
+ const status = await api(`/characters/export/${product.id}`);
+ if (status.status === 'completed' && status.result?.url) {
+ downloadUrl = status.result.url;
+ break;
+ }
+ if (status.status === 'failed') throw new Error('export failed');
+ }
+ if (!downloadUrl) throw new Error('poll timeout');
+
+ const fileRes = await rlFetch(downloadUrl);
+ if (!fileRes.ok) throw new Error(`download ${fileRes.status}`);
+ const buf = Buffer.from(await fileRes.arrayBuffer());
+
+ if (USE_R2) {
+ await uploadToR2(r2Key, buf);
+ } else {
+ writeFileSync(localPath, buf);
+ }
+
+ catalog.avatars[product.id] = {
+ id: product.id,
+ name: product.description || product.name,
+ file: USE_R2 ? r2Key : `${slug}.fbx`,
+ bytes: buf.length,
+ downloaded_at: new Date().toISOString(),
+ status: 'completed',
+ storage: USE_R2 ? 'r2' : 'local',
+ };
+ saveCatalog();
+
+ return { slug, bytes: buf.length };
+}
+
+// ── Step 3: concurrency-limited worker pool ─────────────────────────────
+async function runPool(products) {
+ let cursor = 0;
+ let ok = 0;
+ let fail = 0;
+ let skipped = 0;
+
+ async function worker() {
+ while (cursor < products.length && ok + fail < MAX_DOWNLOADS) {
+ const i = cursor++;
+ const product = products[i];
+ const label = `[${i + 1}/${products.length}]`;
+ try {
+ const result = await downloadOne(product);
+ if (result.skipped) {
+ skipped++;
+ console.log(`${label} skip ${result.slug} (${result.reason})`);
+ } else {
+ ok++;
+ console.log(`${label} done ${result.slug} (${(result.bytes / 1024).toFixed(0)} KB)`);
+ await sleep(500);
+ }
+ } catch (err) {
+ fail++;
+ console.warn(`${label} fail ${product.description}: ${err.message}`);
+ if (err.message.includes('HTTP 401') || err.message.includes('HTTP 403')) {
+ console.error('Auth failure — token expired. Refresh MIXAMO_TOKEN and re-run.');
+ process.exit(2);
+ }
+ }
+ }
+ }
+
+ const workers = Array.from({ length: CONCURRENCY }, () => worker());
+ await Promise.all(workers);
+ return { ok, fail, skipped };
+}
+
+// ── Main ──────────────────────────────────────────────────────────────────
+(async () => {
+ console.log(`Mixamo avatar fetcher`);
+ console.log(` Format: ${FORMAT} (with skin)`);
+ console.log(` Storage: ${USE_R2 ? `R2 -> ${R2_BUCKET}/avatars/mixamo/` : OUT_DIR}`);
+ console.log(` Concurrency: ${CONCURRENCY}\n`);
+
+ const products = await listAllCharacters();
+ console.log(`Catalog: ${products.length} characters\n`);
+
+ if (products.length === 0) {
+ console.log('No characters found. Token may be expired.');
+ console.log('Re-run: node scripts/get-mixamo-token.mjs');
+ process.exit(1);
+ }
+
+ const t0 = Date.now();
+ const { ok, fail, skipped } = await runPool(products);
+ const mins = ((Date.now() - t0) / 60000).toFixed(1);
+
+ console.log(`\n${'='.repeat(43)}`);
+ console.log(`Downloaded: ${ok}`);
+ console.log(`Skipped: ${skipped}`);
+ console.log(`Failed: ${fail}`);
+ console.log(`Time: ${mins} min`);
+ console.log(`Output: ${USE_R2 ? `R2:${R2_BUCKET}/avatars/mixamo/` : OUT_DIR}`);
+ console.log(`\nConvert FBX -> GLB with fbx2gltf:`);
+ console.log(` for f in ${OUT_DIR}/*.fbx; do`);
+ console.log(` fbx2gltf -i "$f" -o "\${f%.fbx}.glb"`);
+ console.log(` done`);
+})().catch((err) => {
+ console.error(err);
+ process.exit(1);
+});
diff --git a/src/city/city-map.js b/src/city/city-map.js
index b85c2fb9c..7f3330fdf 100644
--- a/src/city/city-map.js
+++ b/src/city/city-map.js
@@ -1,298 +1,314 @@
import * as THREE from 'three';
-
-// City grid constants (metres)
-export const BLOCK = 56; // building footprint area per block
-export const ROAD = 14; // road width (kerb to kerb + sidewalk)
-export const CELL = BLOCK + ROAD; // 70 — one grid cell
-export const GRID = 8; // 8×8 blocks
-export const CITY_HALF = (GRID * CELL + ROAD) / 2; // 287 — half-extent from origin
-
-// NYC-inspired architectural palette: brick, concrete, glass, stone
-const PALETTE = [
- 0xc0794a, // terracotta brick
- 0xb8a888, // limestone
- 0x4a6e9a, // glass blue
- 0x9a9898, // concrete gray
- 0xd4c890, // sandstone cream
- 0x607878, // weathered dark concrete
- 0xa06048, // dark brick red
- 0x7898b8, // steel glass
- 0xd8ccb8, // light stone
- 0x506070, // dark glass tower
- 0xb89870, // warm sandstone
- 0x88a070, // industrial green-gray
-];
-
-// Deterministic seeded RNG (mulberry32-style)
-function makeRng(seed) {
- let s = seed ^ 0xdeadbeef;
- return () => {
- s = Math.imul(s ^ (s >>> 16), 0x45d9f3b);
- s = Math.imul(s ^ (s >>> 16), 0x45d9f3b);
- s ^= s >>> 16;
- return (s >>> 0) / 0xffffffff;
+import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';
+
+// Manhattan — Times Square area centre
+const CENTER_LAT = 40.7580;
+const CENTER_LON = -73.9855;
+const RADIUS_METERS = 700; // ~10 city blocks
+
+// OSM localStorage cache (24h TTL)
+const CACHE_KEY = 'city-osm-manhattan-v2';
+const CACHE_TTL_MS = 86_400_000;
+
+export const CITY_HALF = RADIUS_METERS;
+
+// Web Mercator projection — returns metres from city centre in XZ world space
+function project(lat, lon) {
+ const R = 6_371_000;
+ const cosC = Math.cos(CENTER_LAT * Math.PI / 180);
+ return {
+ x: (lon - CENTER_LON) * (Math.PI / 180) * R * cosC,
+ z: -(lat - CENTER_LAT) * (Math.PI / 180) * R,
};
}
-// Build the entire city geometry into `scene`.
-// Returns { buildingBoxes } — flat AABB list used for collision.
-export function buildCity(scene) {
- const r = makeRng(42);
+// Fetch building footprints from OpenStreetMap Overpass API (free, no key)
+export async function fetchOSMData(onProgress) {
+ try {
+ const raw = localStorage.getItem(CACHE_KEY);
+ if (raw) {
+ const { ts, data } = JSON.parse(raw);
+ if (Date.now() - ts < CACHE_TTL_MS) {
+ onProgress?.(0.5, 'Using cached city data…');
+ return data;
+ }
+ }
+ } catch { /* ignore bad cache */ }
+
+ const lat1 = CENTER_LAT - RADIUS_METERS / 111_000;
+ const lat2 = CENTER_LAT + RADIUS_METERS / 111_000;
+ const cosC = Math.cos(CENTER_LAT * Math.PI / 180);
+ const lon1 = CENTER_LON - RADIUS_METERS / (111_000 * cosC);
+ const lon2 = CENTER_LON + RADIUS_METERS / (111_000 * cosC);
+
+ // Query buildings + roads in bounding box
+ const query =
+ `[out:json][timeout:30];` +
+ `(way["building"](${lat1},${lon1},${lat2},${lon2});` +
+ `way["highway"]["highway"~"^(primary|secondary|tertiary|residential|unclassified)$"](${lat1},${lon1},${lat2},${lon2});` +
+ `);out body;>;out skel qt;`;
+
+ onProgress?.(0.1, 'Fetching Manhattan map data…');
+ const res = await fetch(
+ `https://overpass-api.de/api/interpreter?data=${encodeURIComponent(query)}`,
+ );
+ if (!res.ok) throw new Error(`Overpass API ${res.status}`);
+
+ onProgress?.(0.4, 'Parsing city geometry…');
+ const data = await res.json();
+
+ try {
+ localStorage.setItem(CACHE_KEY, JSON.stringify({ ts: Date.now(), data }));
+ } catch { /* quota exceeded */ }
+
+ return data;
+}
+
+// Build the city scene from parsed OSM data.
+// Returns { buildingBoxes } for collision in city-player.js.
+export function buildCity(scene, osmData) {
const buildingBoxes = [];
- // ── Ground (grass/dirt base beneath everything) ───────────────────────────
- const groundSize = CITY_HALF * 2 + 600;
+ // ── Parse OSM elements ────────────────────────────────────────────────────
+ const nodeMap = new Map();
+ const buildingWays = [];
+ const roadWays = [];
+
+ for (const el of osmData.elements) {
+ if (el.type === 'node') nodeMap.set(el.id, project(el.lat, el.lon));
+ }
+ for (const el of osmData.elements) {
+ if (el.type !== 'way') continue;
+ if (el.tags?.building) buildingWays.push(el);
+ else if (el.tags?.highway) roadWays.push(el);
+ }
+
+ // ── Ground ────────────────────────────────────────────────────────────────
+ const groundSize = RADIUS_METERS * 2 + 600;
const groundMesh = new THREE.Mesh(
new THREE.PlaneGeometry(groundSize, groundSize),
- new THREE.MeshStandardMaterial({ color: 0x2a3a28, roughness: 1.0 }),
+ new THREE.MeshStandardMaterial({ color: 0x18181c, roughness: 0.95, metalness: 0 }),
);
groundMesh.rotation.x = -Math.PI / 2;
groundMesh.receiveShadow = true;
scene.add(groundMesh);
- // ── Road surface (one large dark plane) ──────────────────────────────────
- const roadMesh = new THREE.Mesh(
- new THREE.PlaneGeometry(CITY_HALF * 2, CITY_HALF * 2),
- new THREE.MeshStandardMaterial({ color: 0x282830, roughness: 0.92, metalness: 0.05 }),
- );
- roadMesh.rotation.x = -Math.PI / 2;
- roadMesh.position.y = 0.01;
- roadMesh.receiveShadow = true;
- scene.add(roadMesh);
-
- // ── Sidewalk pads (one per block, slightly raised) ────────────────────────
- const sidewalkMat = new THREE.MeshStandardMaterial({ color: 0x38383e, roughness: 0.9 });
- const sidewalkGeo = new THREE.PlaneGeometry(BLOCK + 2, BLOCK + 2);
- for (let bx = 0; bx < GRID; bx++) {
- for (let bz = 0; bz < GRID; bz++) {
- const cx = blockCenter(bx);
- const cz = blockCenter(bz);
- const pad = new THREE.Mesh(sidewalkGeo, sidewalkMat);
- pad.rotation.x = -Math.PI / 2;
- pad.position.set(cx, 0.02, cz);
- pad.receiveShadow = true;
- scene.add(pad);
- }
- }
+ // ── Road planes from OSM highway ways ────────────────────────────────────
+ buildRoads(scene, roadWays, nodeMap);
+
+ // ── Buildings ─────────────────────────────────────────────────────────────
+ const WIN_TEX = buildWindowTex();
+ WIN_TEX.wrapS = WIN_TEX.wrapT = THREE.RepeatWrapping;
+
+ // Bucket geometries by facade material tier
+ const buckets = { glass: [], concrete: [], brick: [], stone: [] };
- // ── Road centre-line dashes ───────────────────────────────────────────────
- buildRoadMarkings(scene);
+ for (const way of buildingWays) {
+ const nodes = way.nodes.map(id => nodeMap.get(id)).filter(Boolean);
+ if (nodes.length < 3) continue;
- // ── Collect building instance data grouped by colour ─────────────────────
- const byColor = new Map(); // paletteIdx → [{cx, cz, w, h, d}]
- for (let bx = 0; bx < GRID; bx++) {
- for (let bz = 0; bz < GRID; bz++) {
- placeBlockBuildings(blockCenter(bx), blockCenter(bz), r, byColor, buildingBoxes);
+ // Discard if entirely outside city radius
+ const inside = nodes.some(n => Math.abs(n.x) < RADIUS_METERS && Math.abs(n.z) < RADIUS_METERS);
+ if (!inside) continue;
+
+ const height = inferHeight(way.tags, way.id);
+ const tier = height > 60 ? 'glass' : height > 25 ? 'concrete' : height > 10 ? 'brick' : 'stone';
+
+ const geo = buildingPolygon(nodes, height);
+ if (!geo) continue;
+
+ buckets[tier].push(geo);
+
+ // AABB for collision
+ let minX = Infinity, maxX = -Infinity, minZ = Infinity, maxZ = -Infinity;
+ for (const n of nodes) {
+ minX = Math.min(minX, n.x); maxX = Math.max(maxX, n.x);
+ minZ = Math.min(minZ, n.z); maxZ = Math.max(maxZ, n.z);
}
+ buildingBoxes.push({ minX, maxX, minZ, maxZ, h: height });
}
- // ── Window texture (shared emissive canvas — lit offices) ────────────────
- const WIN_TEX = buildWindowTex();
- WIN_TEX.wrapS = WIN_TEX.wrapT = THREE.RepeatWrapping;
- // Repeat of 0.3 ≈ one window every ~3 building units at typical building sizes
- WIN_TEX.repeat.set(0.3, 0.3);
+ // Per-tier materials with window emissive
+ const tierDefs = {
+ glass: { color: 0x4a6e9a, roughness: 0.08, metalness: 0.82 },
+ concrete: { color: 0x7c7c80, roughness: 0.90, metalness: 0.04 },
+ brick: { color: 0xa06048, roughness: 0.94, metalness: 0.00 },
+ stone: { color: 0xb8a888, roughness: 0.92, metalness: 0.00 },
+ };
+
+ for (const [tier, geos] of Object.entries(buckets)) {
+ if (geos.length === 0) continue;
+ const merged = mergeGeometries(geos, false);
+ const { color, roughness, metalness } = tierDefs[tier];
- // ── Emit one InstancedMesh per colour ─────────────────────────────────────
- const unitBox = new THREE.BoxGeometry(1, 1, 1);
- const tm = new THREE.Matrix4();
- const q = new THREE.Quaternion();
+ const winTexClone = WIN_TEX.clone();
+ winTexClone.wrapS = winTexClone.wrapT = THREE.RepeatWrapping;
+ const rpt = tier === 'glass' ? 0.12 : tier === 'concrete' ? 0.10 : 0.08;
+ winTexClone.repeat.set(rpt, rpt);
+ winTexClone.needsUpdate = true;
- for (const [palIdx, list] of byColor) {
const mat = new THREE.MeshStandardMaterial({
- color: PALETTE[palIdx],
- roughness: 0.85,
- metalness: 0.0,
- emissiveMap: WIN_TEX,
- emissive: new THREE.Color(0xfff0c0),
- emissiveIntensity: 0.55,
+ color,
+ roughness,
+ metalness,
+ emissiveMap: winTexClone,
+ emissive: new THREE.Color(0xfff2d0),
+ emissiveIntensity: tier === 'glass' ? 0.50 : 0.35,
});
- const mesh = new THREE.InstancedMesh(unitBox, mat, list.length);
+
+ const mesh = new THREE.Mesh(merged, mat);
mesh.castShadow = true;
mesh.receiveShadow = true;
- list.forEach(({ cx, cz, w, h, d }, i) => {
- tm.compose(new THREE.Vector3(cx, h / 2, cz), q, new THREE.Vector3(w, h, d));
- mesh.setMatrixAt(i, tm);
- });
- mesh.instanceMatrix.needsUpdate = true;
scene.add(mesh);
}
- // ── Rooftop caps (single grey, all buildings) ─────────────────────────────
- const allBuildings = [...byColor.values()].flat();
- if (allBuildings.length > 0) {
- const roofMat = new THREE.MeshStandardMaterial({ color: 0x505058, roughness: 0.6, metalness: 0.15 });
- const roofMesh = new THREE.InstancedMesh(unitBox, roofMat, allBuildings.length);
- allBuildings.forEach(({ cx, cz, w, h, d }, i) => {
- tm.compose(new THREE.Vector3(cx, h + 0.25, cz), q, new THREE.Vector3(w + 0.4, 0.5, d + 0.4));
- roofMesh.setMatrixAt(i, tm);
- });
- roofMesh.instanceMatrix.needsUpdate = true;
- scene.add(roofMesh);
- }
-
// ── Street lights ─────────────────────────────────────────────────────────
- buildStreetlights(scene);
+ buildStreetlights(scene, buildingBoxes);
return { buildingBoxes };
}
-// Centre coordinate of grid column/row index
-function blockCenter(idx) {
- return -CITY_HALF + ROAD + BLOCK / 2 + idx * CELL;
+// Infer building height from OSM tags
+function inferHeight(tags, wayId) {
+ if (tags.height) {
+ const h = parseFloat(tags.height);
+ if (h > 0) return Math.min(h, 420);
+ }
+ if (tags['building:levels']) {
+ const lvl = parseFloat(tags['building:levels']);
+ if (lvl > 0) return Math.min(lvl * 3.5, 420);
+ }
+ // Deterministic pseudo-random from way ID — consistent across reloads
+ const seed = Math.imul(wayId ^ (wayId >>> 16), 0x45d9f3b);
+ const t = ((seed >>> 0) % 1000) / 1000;
+ return 3 + Math.pow(t, 2.2) * 55;
}
-// Fill a block with buildings, push instances to byColor, boxes to buildingBoxes
-function placeBlockBuildings(bCX, bCZ, r, byColor, buildingBoxes) {
- const margin = 4;
- const inner = BLOCK - margin * 2; // 48m inner area
- const cols = 2 + Math.floor(r() * 2); // 2 or 3
- const rows = 2 + Math.floor(r() * 2);
- const cellW = inner / cols;
- const cellD = inner / rows;
-
- for (let ci = 0; ci < cols; ci++) {
- for (let ri = 0; ri < rows; ri++) {
- if (r() < 0.12) continue; // occasionally leave a gap
-
- // Centre of this slot with slight jitter
- const cx = bCX - inner / 2 + cellW * (ci + 0.5) + (r() - 0.5) * cellW * 0.14;
- const cz = bCZ - inner / 2 + cellD * (ri + 0.5) + (r() - 0.5) * cellD * 0.14;
-
- const w = cellW * (0.60 + r() * 0.32);
- const d = cellD * (0.60 + r() * 0.32);
- // Height biased toward shorter buildings (urban density mix)
- const h = Math.pow(r(), 1.7) * 52 + 4;
-
- const palIdx = Math.floor(r() * PALETTE.length);
-
- if (!byColor.has(palIdx)) byColor.set(palIdx, []);
- byColor.get(palIdx).push({ cx, cz, w, h, d });
-
- buildingBoxes.push({
- minX: cx - w / 2, maxX: cx + w / 2,
- minZ: cz - d / 2, maxZ: cz + d / 2,
- h,
- });
- }
+// Build ExtrudeGeometry from OSM polygon already in world XZ coords.
+// Shape is defined in shape-XY (x→X, -z→Y) then rotateX(-PI/2) lays it flat.
+function buildingPolygon(nodes, height) {
+ try {
+ const shape = new THREE.Shape();
+ shape.moveTo(nodes[0].x, -nodes[0].z);
+ for (let i = 1; i < nodes.length; i++) shape.lineTo(nodes[i].x, -nodes[i].z);
+ shape.closePath();
+
+ const geo = new THREE.ExtrudeGeometry(shape, { depth: height, bevelEnabled: false });
+ geo.rotateX(-Math.PI / 2); // extrusion now goes up (world +Y)
+ return geo;
+ } catch {
+ return null;
}
}
-// Yellow dashed centre lines along every road
-function buildRoadMarkings(scene) {
+// Render road surface planes along OSM highway ways
+function buildRoads(scene, roadWays, nodeMap) {
+ if (roadWays.length === 0) return;
+
+ const roadMat = new THREE.MeshStandardMaterial({ color: 0x252530, roughness: 0.95, metalness: 0 });
const dashMat = new THREE.MeshStandardMaterial({
- color: 0xeecc00,
- emissive: 0x443300,
- emissiveIntensity: 0.15,
+ color: 0xddbb00,
+ emissive: 0x332a00,
+ emissiveIntensity: 0.2,
roughness: 0.9,
});
- // Vertical roads (parallel to Z)
- for (let i = 0; i <= GRID; i++) {
- const rx = -CITY_HALF + ROAD / 2 + i * CELL;
- addDashes(scene, dashMat, rx, true);
- }
- // Horizontal roads (parallel to X)
- for (let i = 0; i <= GRID; i++) {
- const rz = -CITY_HALF + ROAD / 2 + i * CELL;
- addDashes(scene, dashMat, rz, false);
- }
-}
-function addDashes(scene, mat, axisVal, alongZ) {
- const length = CITY_HALF * 2;
- const dashLen = 5;
- const dashGap = 5;
- const count = Math.floor(length / (dashLen + dashGap));
- // PlaneGeometry is in the XY plane; rotate -90° around X to lay flat on ground
- const geo = alongZ
- ? new THREE.PlaneGeometry(0.28, dashLen) // width × length along Z
- : new THREE.PlaneGeometry(dashLen, 0.28); // length along X × width
- const mesh = new THREE.InstancedMesh(geo, mat, count);
- // Rotation matrix: -90° around X lays the plane flat (normal faces +Y)
- const rot = new THREE.Matrix4().makeRotationX(-Math.PI / 2);
- const trans = new THREE.Matrix4();
- const m = new THREE.Matrix4();
- for (let k = 0; k < count; k++) {
- const along = -CITY_HALF + k * (dashLen + dashGap) + dashLen / 2;
- const px = alongZ ? axisVal : along;
- const pz = alongZ ? along : axisVal;
- trans.makeTranslation(px, 0.035, pz);
- m.multiplyMatrices(trans, rot);
- mesh.setMatrixAt(k, m);
+ const roadGeos = [];
+ const dashGeos = [];
+
+ for (const way of roadWays) {
+ const pts = way.nodes.map(id => nodeMap.get(id)).filter(Boolean);
+ if (pts.length < 2) continue;
+
+ const hw = way.tags.highway;
+ const halfW = hw === 'primary' ? 8 : hw === 'secondary' ? 6 : 4.5;
+
+ for (let i = 0; i < pts.length - 1; i++) {
+ const a = pts[i], b = pts[i + 1];
+ const dx = b.x - a.x, dz = b.z - a.z;
+ const len = Math.sqrt(dx * dx + dz * dz);
+ if (len < 0.5) continue;
+ const angle = Math.atan2(dx, dz);
+
+ const rGeo = new THREE.PlaneGeometry(halfW * 2, len);
+ rGeo.rotateX(-Math.PI / 2);
+ rGeo.rotateY(angle);
+ rGeo.translate((a.x + b.x) / 2, 0.02, (a.z + b.z) / 2);
+ roadGeos.push(rGeo);
+
+ // Centre-line dashes
+ const dashLen = 4, dashGap = 4;
+ const numDash = Math.floor(len / (dashLen + dashGap));
+ for (let k = 0; k < numDash; k++) {
+ const t = (k * (dashLen + dashGap) + dashLen / 2) / len;
+ const dGeo = new THREE.PlaneGeometry(0.28, dashLen);
+ dGeo.rotateX(-Math.PI / 2);
+ dGeo.rotateY(angle);
+ dGeo.translate(a.x + dx * t, 0.035, a.z + dz * t);
+ dashGeos.push(dGeo);
+ }
+ }
}
- mesh.instanceMatrix.needsUpdate = true;
- scene.add(mesh);
+
+ if (roadGeos.length > 0) scene.add(new THREE.Mesh(mergeGeometries(roadGeos, false), roadMat));
+ if (dashGeos.length > 0) scene.add(new THREE.Mesh(mergeGeometries(dashGeos, false), dashMat));
}
-// Street lights at every road intersection
-function buildStreetlights(scene) {
- const poleMat = new THREE.MeshStandardMaterial({ color: 0x484854, roughness: 0.6, metalness: 0.5 });
- const glowMat = new THREE.MeshStandardMaterial({ color: 0xfff0b8, emissive: 0xfff0b8, emissiveIntensity: 2.5 });
+// Street lights on road-like areas (not inside buildings)
+function buildStreetlights(scene, boxes) {
+ const poleMat = new THREE.MeshStandardMaterial({ color: 0x383844, roughness: 0.6, metalness: 0.55 });
+ const glowMat = new THREE.MeshStandardMaterial({ color: 0xfff0b8, emissive: 0xfff0b8, emissiveIntensity: 2.8 });
+
+ const step = 55;
+ const positions = [];
+ for (let x = -RADIUS_METERS; x < RADIUS_METERS; x += step) {
+ for (let z = -RADIUS_METERS; z < RADIUS_METERS; z += step) {
+ const inBuilding = boxes.some(b => x > b.minX && x < b.maxX && z > b.minZ && z < b.maxZ);
+ if (!inBuilding) positions.push({ x, z });
+ }
+ }
+ if (positions.length === 0) return;
- const intersections = (GRID + 1) * (GRID + 1);
- const poleMesh = new THREE.InstancedMesh(new THREE.CylinderGeometry(0.07, 0.09, 6.5, 6), poleMat, intersections);
- const glowMesh = new THREE.InstancedMesh(new THREE.SphereGeometry(0.15, 6, 6), glowMat, intersections);
+ const poleMesh = new THREE.InstancedMesh(new THREE.CylinderGeometry(0.06, 0.08, 6, 5), poleMat, positions.length);
+ const glowMesh = new THREE.InstancedMesh(new THREE.SphereGeometry(0.14, 5, 5), glowMat, positions.length);
poleMesh.castShadow = true;
const m = new THREE.Matrix4();
- let idx = 0;
- for (let bx = 0; bx <= GRID; bx++) {
- for (let bz = 0; bz <= GRID; bz++) {
- const x = -CITY_HALF + ROAD / 2 + bx * CELL - 3;
- const z = -CITY_HALF + ROAD / 2 + bz * CELL - 3;
- m.makeTranslation(x, 3.25, z);
- poleMesh.setMatrixAt(idx, m);
- m.makeTranslation(x, 6.7, z);
- glowMesh.setMatrixAt(idx, m);
- idx++;
- }
- }
+ positions.forEach(({ x, z }, i) => {
+ m.makeTranslation(x, 3, z);
+ poleMesh.setMatrixAt(i, m);
+ m.makeTranslation(x, 6.5, z);
+ glowMesh.setMatrixAt(i, m);
+ });
poleMesh.instanceMatrix.needsUpdate = true;
glowMesh.instanceMatrix.needsUpdate = true;
scene.add(poleMesh);
scene.add(glowMesh);
}
-// Pre-render a static overhead minimap canvas for the city layout.
-// Returns an HTMLCanvasElement you can drawImage() from every frame.
+// Pre-render static overhead minimap canvas
export function buildMinimapStatic(buildingBoxes) {
- const SCALE = 1.8; // pixels per metre
+ const SCALE = 0.46; // px per metre (700m * 2 * 0.46 ≈ 644px canvas)
const SIZE = Math.ceil(CITY_HALF * 2 * SCALE);
const c = document.createElement('canvas');
c.width = SIZE; c.height = SIZE;
const ctx = c.getContext('2d');
- // Road base
- ctx.fillStyle = '#18181e';
+ ctx.fillStyle = '#14141a';
ctx.fillRect(0, 0, SIZE, SIZE);
- // Sidewalk pads
- ctx.fillStyle = '#2a2a32';
- for (let bx = 0; bx < GRID; bx++) {
- for (let bz = 0; bz < GRID; bz++) {
- const cx = blockCenter(bx);
- const cz = blockCenter(bz);
- const sx = (cx - BLOCK / 2 + CITY_HALF) * SCALE;
- const sz = (cz - BLOCK / 2 + CITY_HALF) * SCALE;
- ctx.fillRect(sx, sz, BLOCK * SCALE, BLOCK * SCALE);
- }
- }
-
- // Buildings (taller = slightly lighter)
for (const b of buildingBoxes) {
- const brightness = Math.min(1, 0.3 + b.h / 60);
- ctx.fillStyle = `rgba(${Math.round(80 + brightness * 70)},${Math.round(85 + brightness * 65)},${Math.round(100 + brightness * 60)},0.9)`;
+ const brightness = Math.min(1, 0.3 + b.h / 80);
+ ctx.fillStyle = `rgba(${Math.round(60 + brightness * 90)},${Math.round(65 + brightness * 80)},${Math.round(80 + brightness * 90)},0.88)`;
const sx = (b.minX + CITY_HALF) * SCALE;
const sz = (b.minZ + CITY_HALF) * SCALE;
- const sw = (b.maxX - b.minX) * SCALE;
- const sd = (b.maxZ - b.minZ) * SCALE;
- ctx.fillRect(sx, sz, Math.max(1, sw), Math.max(1, sd));
+ ctx.fillRect(sx, sz, Math.max(1, (b.maxX - b.minX) * SCALE), Math.max(1, (b.maxZ - b.minZ) * SCALE));
}
return { canvas: c, scale: SCALE };
}
-// Canvas texture simulating lit/unlit office windows.
-// Tiled via repeat on the building emissive map — warm glow on every face.
+// Office window emissive canvas — warm/cool glow, deterministic per load
function buildWindowTex() {
const COLS = 6, ROWS = 10;
const W = 128, H = 200;
@@ -300,24 +316,22 @@ function buildWindowTex() {
c.width = W; c.height = H;
const ctx = c.getContext('2d');
- // Dark building face base
- ctx.fillStyle = '#000';
+ ctx.fillStyle = '#060608';
ctx.fillRect(0, 0, W, H);
const cw = W / COLS, rh = H / ROWS;
- const pw = cw * 0.56, ph = rh * 0.52;
+ const pw = cw * 0.54, ph = rh * 0.50;
const ox = (cw - pw) / 2, oy = (rh - ph) / 2;
- // Deterministic random for consistent look every load
let s = 0xc0ffee;
const rand = () => { s = (s * 1664525 + 1013904223) >>> 0; return s / 0xffffffff; };
for (let col = 0; col < COLS; col++) {
for (let row = 0; row < ROWS; row++) {
- if (rand() > 0.45) { // ~55% of windows lit
- // Vary between warm (office) and cool (fluorescent) light
- const warm = rand() > 0.4;
- ctx.fillStyle = warm ? `rgba(255,225,150,${0.6 + rand() * 0.4})` : `rgba(180,220,255,${0.5 + rand() * 0.4})`;
+ if (rand() > 0.44) {
+ const warm = rand() > 0.38;
+ const a = (0.55 + rand() * 0.45).toFixed(2);
+ ctx.fillStyle = warm ? `rgba(255,228,155,${a})` : `rgba(175,215,255,${a})`;
ctx.fillRect(col * cw + ox, row * rh + oy, pw, ph);
}
}
diff --git a/src/city/city-world.js b/src/city/city-world.js
index c36f59e2b..b1d8ed00d 100644
--- a/src/city/city-world.js
+++ b/src/city/city-world.js
@@ -1,19 +1,19 @@
import * as THREE from 'three';
import { Sky } from 'three/addons/objects/Sky.js';
-import { buildCity, buildMinimapStatic, CITY_HALF } from './city-map.js';
+import { fetchOSMData, buildCity, buildMinimapStatic, CITY_HALF } from './city-map.js';
import { CityPlayer } from './city-player.js';
import { CityCamera } from './city-camera.js';
-// ── DOM refs ─────────────────────────────────────────────────────────────────
+// ── DOM refs ──────────────────────────────────────────────────────────────────
-const canvas = document.getElementById('city-canvas');
-const loadingEl = document.getElementById('city-loading');
-const subEl = document.getElementById('city-loading-sub');
-const barEl = document.getElementById('city-boot-bar-fill');
-const hudEl = document.getElementById('city-hud');
-const coordsEl = document.getElementById('city-hud-coords');
-const mmCanvas = document.getElementById('city-minimap-canvas');
-const mmCtx = mmCanvas.getContext('2d');
+const canvas = document.getElementById('city-canvas');
+const loadingEl = document.getElementById('city-loading');
+const subEl = document.getElementById('city-loading-sub');
+const barEl = document.getElementById('city-boot-bar-fill');
+const hudEl = document.getElementById('city-hud');
+const coordsEl = document.getElementById('city-hud-coords');
+const mmCanvas = document.getElementById('city-minimap-canvas');
+const mmCtx = mmCanvas.getContext('2d');
function progress(pct, label) {
if (barEl) barEl.style.width = pct + '%';
@@ -23,116 +23,106 @@ function progress(pct, label) {
// ── Boot ──────────────────────────────────────────────────────────────────────
async function main() {
- progress(8, 'Setting up renderer…');
+ progress(5, 'Setting up renderer…');
- // Renderer
- const renderer = new THREE.WebGLRenderer({
- canvas,
- antialias: true,
- powerPreference: 'high-performance',
- });
+ const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, powerPreference: 'high-performance' });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
- renderer.shadowMap.type = THREE.PCFSoftShadowMap;
- renderer.toneMapping = THREE.ACESFilmicToneMapping;
- renderer.toneMappingExposure = 0.92;
- renderer.outputColorSpace = THREE.SRGBColorSpace;
+ renderer.shadowMap.type = THREE.PCFSoftShadowMap;
+ renderer.toneMapping = THREE.ACESFilmicToneMapping;
+ renderer.toneMappingExposure = 0.88;
+ renderer.outputColorSpace = THREE.SRGBColorSpace;
- // Scene
const scene = new THREE.Scene();
- scene.fog = new THREE.Fog(0x9aafbf, 110, 500);
+ scene.fog = new THREE.Fog(0x9aafbf, 200, 900);
- // Camera
- const camera = new THREE.PerspectiveCamera(58, window.innerWidth / window.innerHeight, 0.1, 600);
- camera.position.set(0, 12, 20);
+ const camera = new THREE.PerspectiveCamera(58, window.innerWidth / window.innerHeight, 0.1, 1200);
+ camera.position.set(0, 14, 24);
- progress(18, 'Adding lights…');
+ progress(12, 'Adding lights…');
- // Ambient — generous so shadowed areas stay readable
- scene.add(new THREE.AmbientLight(0xc0d4e8, 1.4));
+ scene.add(new THREE.AmbientLight(0xc0d4e8, 1.5));
- // Sun — warm afternoon angle, less overpowering than midday
- const sun = new THREE.DirectionalLight(0xffe8c0, 2.0);
- sun.position.set(60, 80, -50); // slightly behind camera = front-lit scene
+ const sun = new THREE.DirectionalLight(0xffe8c0, 2.2);
+ sun.position.set(80, 100, -60);
sun.castShadow = true;
- sun.shadow.mapSize.set(2048, 2048);
- sun.shadow.camera.near = 1;
- sun.shadow.camera.far = 500;
- sun.shadow.camera.left = -160;
- sun.shadow.camera.right = 160;
- sun.shadow.camera.top = 160;
- sun.shadow.camera.bottom = -160;
- sun.shadow.bias = -0.0008;
+ sun.shadow.mapSize.set(4096, 4096);
+ sun.shadow.camera.near = 1;
+ sun.shadow.camera.far = 1200;
+ sun.shadow.camera.left = -300;
+ sun.shadow.camera.right = 300;
+ sun.shadow.camera.top = 300;
+ sun.shadow.camera.bottom = -300;
+ sun.shadow.bias = -0.0006;
scene.add(sun);
- // Secondary fill from the opposite side — kills pitch-black shadows
- const fill = new THREE.DirectionalLight(0x90b8e0, 0.7);
- fill.position.set(-60, 50, 60);
+ const fill = new THREE.DirectionalLight(0x90b8e0, 0.75);
+ fill.position.set(-80, 60, 80);
scene.add(fill);
- // Hemisphere (sky/ground colour fill)
- scene.add(new THREE.HemisphereLight(0x90b8d8, 0x4a6040, 0.6));
+ scene.add(new THREE.HemisphereLight(0x92bada, 0x4a5e40, 0.65));
- progress(28, 'Building sky…');
+ progress(22, 'Building sky…');
- // Sky dome
const sky = new Sky();
- sky.scale.setScalar(5000);
+ sky.scale.setScalar(8000);
scene.add(sky);
const su = sky.material.uniforms;
- su.turbidity.value = 4.0;
- su.rayleigh.value = 2.2;
- su.mieCoefficient.value = 0.006;
- su.mieDirectionalG.value = 0.9;
- su.sunPosition.value.set(0.4, 0.35, -0.85).normalize();
-
- progress(40, 'Building city…');
-
- const { buildingBoxes } = buildCity(scene);
-
- progress(62, 'Building minimap…');
-
+ su.turbidity.value = 3.5;
+ su.rayleigh.value = 2.5;
+ su.mieCoefficient.value = 0.005;
+ su.mieDirectionalG.value = 0.92;
+ su.sunPosition.value.set(0.45, 0.38, -0.80).normalize();
+
+ // ── Fetch real-world Manhattan OSM data ───────────────────────────────────
+ let osmData;
+ try {
+ osmData = await fetchOSMData((frac, label) => {
+ progress(22 + frac * 30, label);
+ });
+ } catch (err) {
+ console.error('OSM fetch failed — loading empty world:', err);
+ osmData = { elements: [] };
+ }
+
+ progress(55, 'Building city geometry…');
+ const { buildingBoxes } = buildCity(scene, osmData);
+
+ progress(75, 'Building minimap…');
const minimap = buildMinimapStatic(buildingBoxes);
- progress(72, 'Loading avatar…');
+ progress(82, 'Loading avatar…');
- // Player — pick avatar from URL param or localStorage
const avatarInput = new URLSearchParams(location.search).get('avatar')
|| localStorage.getItem('kx-avatar')
|| '';
const player = new CityPlayer(scene);
await player.load(avatarInput);
- player.position.set(0, 0, 0);
+ player.position.set(0, 0, 10);
- progress(92, 'Entering world…');
+ progress(96, 'Entering city…');
- // Camera controller (attach after player exists)
const cityCamera = new CityCamera(camera, canvas);
+ canvas.addEventListener('contextmenu', e => e.preventDefault());
- // Block right-click context menu so RMB can orbit
- canvas.addEventListener('contextmenu', (e) => e.preventDefault());
-
- // Resize handler
window.addEventListener('resize', () => {
renderer.setSize(window.innerWidth, window.innerHeight);
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
});
- // Focus canvas so keyboard input works immediately
canvas.focus();
- // ── Reveal ──────────────────────────────────────────────────────────────────
progress(100, 'Ready');
- await delay(180);
+ await delay(150);
loadingEl.classList.add('hidden');
- await delay(480);
+ await delay(420);
loadingEl.style.display = 'none';
hudEl.style.display = '';
- // ── Game loop ────────────────────────────────────────────────────────────────
+ // ── Game loop ─────────────────────────────────────────────────────────────
const clock = new THREE.Clock();
(function tick() {
@@ -154,31 +144,22 @@ async function main() {
function drawMinimap(ctx, playerPos, minimap) {
const W = 120, H = 120;
const { canvas: src, scale } = minimap;
-
- // Player's position in the static minimap image
const px = (playerPos.x + CITY_HALF) * scale;
const pz = (playerPos.z + CITY_HALF) * scale;
ctx.clearRect(0, 0, W, H);
-
- // Clip to circle
ctx.save();
ctx.beginPath();
ctx.arc(W / 2, H / 2, W / 2, 0, Math.PI * 2);
ctx.clip();
-
- // Blit 120×120 region of the static image centred on player
ctx.drawImage(src, px - W / 2, pz - H / 2, W, H, 0, 0, W, H);
-
ctx.restore();
- // Player dot
ctx.fillStyle = 'rgba(255,255,255,0.95)';
ctx.beginPath();
ctx.arc(W / 2, H / 2, 3, 0, Math.PI * 2);
ctx.fill();
- // Heading tick (points up = north on the map)
ctx.strokeStyle = 'rgba(255,255,255,0.35)';
ctx.lineWidth = 1.5;
ctx.beginPath();
@@ -187,15 +168,20 @@ function drawMinimap(ctx, playerPos, minimap) {
ctx.stroke();
}
-// ── Coordinate HUD ────────────────────────────────────────────────────────────
+// ── Coordinate HUD ─────────────────────────────────────────────────────────────
+// Convert local XZ back to approximate real-world lat/lon for display
function updateCoords(pos) {
if (!coordsEl) return;
- coordsEl.textContent = `${pos.x.toFixed(1)}, ${pos.y.toFixed(1)}, ${pos.z.toFixed(1)}`;
+ const R = 6_371_000;
+ const cosC = Math.cos(40.7580 * Math.PI / 180);
+ const lat = 40.7580 - (pos.z / R) * (180 / Math.PI);
+ const lon = -73.9855 + (pos.x / (R * cosC)) * (180 / Math.PI);
+ coordsEl.textContent = `${lat.toFixed(5)}°N ${Math.abs(lon).toFixed(5)}°W`;
}
// ── Utility ───────────────────────────────────────────────────────────────────
-function delay(ms) { return new Promise((r) => setTimeout(r, ms)); }
+function delay(ms) { return new Promise(r => setTimeout(r, ms)); }
main().catch(console.error);
diff --git a/src/game/coincommunities-ui.js b/src/game/coincommunities-ui.js
index 45b7c3b5f..e29eae230 100644
--- a/src/game/coincommunities-ui.js
+++ b/src/game/coincommunities-ui.js
@@ -128,7 +128,7 @@ export class CommunityUI {
]),
]),
el('div', { class: 'cc-search' }, [el('span', { text: '🔎' }), this.searchInput]),
- el('a', { class: 'cc-adventure', href: '/game', title: 'Isometric MMO — gather, fight, level up' }, [
+ el('a', { class: 'cc-adventure', href: '/play', title: 'Isometric MMO — gather, fight, level up' }, [
el('span', { class: 'cc-adventure-ico', text: '⚔️' }),
el('span', { html: 'Adventure mode<small>Gather · fight · level up</small>' }),
]),
diff --git a/vercel.json b/vercel.json
index 9ced2ea45..2e021091f 100644
--- a/vercel.json
+++ b/vercel.json
@@ -327,11 +327,16 @@
},
{
"src": "/play/?",
- "dest": "/play.html"
+ "dest": "/game.html"
},
{
"src": "/game/?",
- "dest": "/game.html"
+ "headers": { "Location": "/play" },
+ "status": 301
+ },
+ {
+ "src": "/lobby/?",
+ "dest": "/play.html"
},
{
"src": "/walk/?",
diff --git a/vite.config.js b/vite.config.js
index 37ffb6c01..135e44a3b 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -284,8 +284,8 @@ const appConfig = {
communities: resolve(__dirname, 'pages/communities.html'),
'walk-embed': resolve(__dirname, 'pages/walk-embed.html'),
city: resolve(__dirname, 'pages/city.html'),
- play: resolve(__dirname, 'pages/play.html'),
- game: resolve(__dirname, 'pages/game.html'),
+ play: resolve(__dirname, 'pages/game.html'),
+ lobby: resolve(__dirname, 'pages/play.html'),
pose: resolve(__dirname, 'pages/pose.html'),
club: resolve(__dirname, 'pages/club.html'),
skills: resolve(__dirname, 'pages/skills.html'),
@@ -529,8 +529,10 @@ const appConfig = {
'/avatar-artifact/': resolve(root, 'pages/avatar-artifact.html'),
'/walk': resolve(root, 'pages/walk.html'),
'/walk/': resolve(root, 'pages/walk.html'),
- '/play': resolve(root, 'pages/play.html'),
- '/play/': resolve(root, 'pages/play.html'),
+ '/play': resolve(root, 'pages/game.html'),
+ '/play/': resolve(root, 'pages/game.html'),
+ '/lobby': resolve(root, 'pages/play.html'),
+ '/lobby/': resolve(root, 'pages/play.html'),
'/walk-embed': resolve(root, 'pages/walk-embed.html'),
'/walk-embed/': resolve(root, 'pages/walk-embed.html'),
'/pose': resolve(root, 'pages/pose.html'),