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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(x402.js): update resource_url to use absolute URL based on current location
nirholas967931097d66
diff --git a/multiplayer/src/index.js b/multiplayer/src/index.jsindex 5bcb3808b..f9f523f72 100644--- a/multiplayer/src/index.js+++ b/multiplayer/src/index.js@@ -138,13 +138,20 @@ const gameServer = new Server({ transport, ...(driver && { driver }), ...(presen// to the shared mainland world; a missing tier is the open General world (see// WalkRoom.onCreate / onAuth / schemas.js).gameServer.define('walk_world', WalkRoom).filterBy(['coin', 'tier']);-gameServer.define('game_mainland', GameRoom);+// One room definition per realm — each is its own instance, so players in+// different realms never see or affect each other. The realm name is baked into+// the definition's options and read by GameRoom.onCreate. Mainland/Whisperwood/+// Pond/Mine are safe; Wilderness is the danger+pvp realm that drops death-bags.+// Mine is the enclosed cave interior reached through the Mainland mine entrance.+for (const realm of ['mainland', 'wilderness', 'whisperwood', 'pond', 'mine']) {+ gameServer.define(`game_${realm}`, GameRoom, { realm });+}gameServer.listen(PORT, HOST).then(() => {console.log(`[multiplayer] listening on ws://${HOST}:${PORT}`);- console.log(`[multiplayer] rooms: walk_world, game_mainland`);+ console.log(`[multiplayer] rooms: walk_world, game_{mainland,wilderness,whisperwood,pond,mine}`);console.log(`[multiplayer] allowed origins: ${ALLOWED_ORIGINS.join(', ')}`);}).catch((err) => {diff --git a/multiplayer/src/items.js b/multiplayer/src/items.jsnew file mode 100644index 000000000..827c58b19--- /dev/null+++ b/multiplayer/src/items.js@@ -0,0 +1,180 @@+// Item registry — the single source of truth for what items exist in the+// Kintara realms and how they behave. Rooms read THIS instead of branching on+// item ids inline, so stacking, edibility, heal values, and mount tuning are+// data-driven and an item means the same thing everywhere it appears.+//+// Reused by the GameRoom (gather/cook/consume/banking/loot/mounts) and, going+// forward, by the marketplace and the shop — they all describe items in the+// same vocabulary so a "cookedFish" is identical whether it was cooked, looted,+// or bought.+//+// Each entry:+// stackable — stacks up to MAX_STACK in one slot (resources, food, potions).+// tool — equippable gather/combat tool; occupies the active slot, never+// stacks (qty stays 1).+// edible — can be eaten via the `consume` intent to restore HP.+// heal — base HP restored when eaten (edible items only).+// mount — rideable steed tuning { stepMs, color, accent, scale }. stepMs+// is the SERVER-enforced floor (ms between steps) while riding it;+// lower is faster. The client derives its send cadence from this+// so it can never out-pace what the server will accept.+// icon — emoji shown in the hotbar / tooltips (client convenience).+// label — human-facing name for toasts and tooltips.++export const ITEMS = {+ // Tools — non-stackable, one per slot.+ axe: { tool: true, stackable: false, icon: '🪓', label: 'Axe' },+ pickaxe: { tool: true, stackable: false, icon: '⛏️', label: 'Pickaxe' },+ rod: { tool: true, stackable: false, icon: '🎣', label: 'Fishing rod' },+ hammer: { tool: true, stackable: false, icon: '🔨', label: 'Hammer' },+ sword: { tool: true, stackable: false, icon: '⚔️', label: 'Sword' },++ // Gathered resources — stackable.+ wood: { stackable: true, icon: '🪵', label: 'Wood' },+ stone: { stackable: true, icon: '🪨', label: 'Stone' },+ coal: { stackable: true, icon: '⚫', label: 'Coal' },+ fish: { stackable: true, icon: '🐟', label: 'Raw fish' },++ // Monster drops — stackable trophy/material items from kills.+ bones: { stackable: true, icon: '🦴', label: 'Bones' },+ hide: { stackable: true, icon: '🟫', label: 'Beast hide' },++ // Cooked food — stackable and edible. Cooking raw fish at a Roast Pit yields+ // this; eating it restores HP.+ cookedFish: { stackable: true, edible: true, heal: 11, icon: '🍖', label: 'Cooked fish' },++ // Potions — stackable, edible, stronger heals. Introduced by the shop/loot;+ // defined here so the `consume` handler treats them correctly the moment they+ // enter a player's pack.+ healthPotion: { stackable: true, edible: true, heal: 28, icon: '🧪', label: 'Health potion' },++ // Mounts — rare drops you can ride for faster travel. Non-stackable; one per+ // slot. stepMs is the server-enforced step floor while riding (lower = faster+ // than the on-foot floor). The dire wolf is quick and light; the war boar is+ // a touch slower but a bigger, sturdier-looking steed.+ dire_wolf: {+ mount: { stepMs: 92, color: 0x6b7280, accent: 0xb9c2d0, scale: 1.0 },+ stackable: false, icon: '🐺', label: 'Dire Wolf',+ },+ war_boar: {+ mount: { stepMs: 104, color: 0x7a5230, accent: 0xd8b48a, scale: 1.15 },+ stackable: false, icon: '🐗', label: 'War Boar',+ },+};++// The set of item ids that stack — derived once from the registry so callers+// never hand-maintain a parallel list.+export const STACKABLE_ITEMS = new Set(+ Object.entries(ITEMS).filter(([, def]) => def.stackable).map(([id]) => id),+);++export function itemDef(item) {+ return ITEMS[item] || null;+}++export function isStackable(item) {+ return !!ITEMS[item]?.stackable;+}++export function isEdible(item) {+ return !!ITEMS[item]?.edible;+}++// Base HP restored when an edible item is eaten (0 for anything inedible).+export function healValue(item) {+ return ITEMS[item]?.heal || 0;+}++export function itemLabel(item) {+ return ITEMS[item]?.label || item;+}++// ---------------------------------------------------------------------------+// Mounts+// ---------------------------------------------------------------------------++export function isMount(item) {+ return !!ITEMS[item]?.mount;+}++// The server-enforced minimum ms between steps while riding `item` (null if the+// item isn't a mount). Lower than the on-foot floor → visibly faster travel.+export function mountStepMs(item) {+ return ITEMS[item]?.mount?.stepMs ?? null;+}++// ---------------------------------------------------------------------------+// Loot tables+// ---------------------------------------------------------------------------++// Drop tables keyed by mob `kind`. Each entry is one INDEPENDENT roll:+// { item, chance, min?, max? } (min/max default to 1; stackables roll a qty)+// Training dummies intentionally drop nothing. Rolls are independent, so a kill+// can yield several lines or none — and a lucky kill can drop a rare mount.+export const LOOT_TABLES = {+ dummy: [],+ goblin: [+ { item: 'bones', chance: 0.55, min: 1, max: 2 },+ { item: 'hide', chance: 0.30 },+ { item: 'coal', chance: 0.18 },+ { item: 'dire_wolf', chance: 0.05 },+ ],+ ogre: [+ { item: 'bones', chance: 0.75, min: 1, max: 3 },+ { item: 'hide', chance: 0.55, min: 1, max: 2 },+ { item: 'stone', chance: 0.40, min: 1, max: 3 },+ { item: 'dire_wolf', chance: 0.07 },+ { item: 'war_boar', chance: 0.10 },+ ],+};++// Roll a mob's loot table into a flat list of { item, qty }. Pure given `rng`+// (defaults to Math.random) so it stays unit-testable and deterministic under a+// seeded rng.+export function rollLoot(kind, rng = Math.random) {+ const table = LOOT_TABLES[kind];+ if (!table) return [];+ const out = [];+ for (const entry of table) {+ if (rng() >= entry.chance) continue;+ const min = entry.min ?? 1;+ const max = entry.max ?? min;+ const qty = min + Math.floor(rng() * (max - min + 1));+ out.push({ item: entry.item, qty });+ }+ return out;+}++// ---------------------------------------------------------------------------+// Client view+// ---------------------------------------------------------------------------++// The slim, serializable slice the client needs to label/render items (hotbar+// icons, loot toasts, mount meshes). Keeps the wire payload small — no loot+// tables or heal logic, since the client never rolls or resolves those.+// ---------------------------------------------------------------------------+// Cooking+// ---------------------------------------------------------------------------++// Burn chance when cooking raw fish: 40% at level 1, falling linearly to 0% by+// the high 30s, so a low-level cook loses some fish while a trained one never+// does. Clamped both ways. Pure and deterministic (the per-fish RNG roll lives+// in the cook handler) so the odds stay honest and unit-testable.+export function cookBurnChance(level) {+ const c = 0.4 - (Math.max(1, level) - 1) * 0.011;+ return Math.max(0, Math.min(0.4, c));+}++export function clientItemRegistry() {+ const out = {};+ for (const [id, it] of Object.entries(ITEMS)) {+ out[id] = {+ label: it.label || id,+ icon: it.icon || '📦',+ kind: it.mount ? 'mount' : it.tool ? 'tool' : it.edible ? 'food' : 'resource',+ stackable: !!it.stackable,+ };+ if (it.mount) out[id].mount = { ...it.mount };+ }+ return out;+}diff --git a/multiplayer/src/quests.js b/multiplayer/src/quests.jsnew file mode 100644index 000000000..13e62f10d--- /dev/null+++ b/multiplayer/src/quests.js@@ -0,0 +1,188 @@+// Quest engine — the authoritative definitions and helpers behind the Mainland+// tutorial and the daily-quest rotation. Pure data + pure functions: no Colyseus+// or network concerns live here, so the GameRoom can drive everything from real+// action hooks (gather/combat/movement/banking) and this module stays trivially+// testable and deterministic.+//+// Two systems share this file:+// • Tutorial — a fixed, ordered onboarding (TUTORIAL_STEPS). A fresh account+// walks it once; completion is persisted so it never replays.+// • Daily quests — three objectives rolled per account per UTC day from+// DAILY_POOL. The roll is DETERMINISTIC (hash of playerId + date) so the+// same player always sees the same set for a given day, a reconnect mid-day+// never reshuffles their quests, and there is no Math.random to make state+// unreproducible across a restart.+//+// Progress only ever moves from server-validated actions — never from a client+// claim — so a player cannot spoof a turn-in.++// ---------------------------------------------------------------------------+// Badges — cosmetic account achievements granted by quests. Surfaced on the+// player's nameplate and in the quest panel (the in-world "profile").+// ---------------------------------------------------------------------------+export const BADGES = {+ newcomer: { id: 'newcomer', label: 'Newcomer', icon: '🎓', desc: 'Finished the Mainland tutorial.' },+ warrior: { id: 'warrior', label: 'Warrior', icon: '⚔️', desc: 'Cleared a combat daily quest.' },+ forager: { id: 'forager', label: 'Forager', icon: '🧺', desc: 'Cleared a gathering daily quest.' },+ devoted: { id: 'devoted', label: 'Devoted', icon: '🌟', desc: 'Cleared every daily quest in one day.' },+};++// ---------------------------------------------------------------------------+// Tutorial — ordered steps. Each step advances only when the player performs+// the real action `kind` `count` times (validated server-side):+// move → successful tile steps+// talk → talking to the guide NPC+// gather → gathering a specific resource item+// combat → defeating a mob+// bank → depositing an item at the bank counter+// `slot` (when present) is the hotbar index the step is teaching the player to+// equip — the client highlights it.+// ---------------------------------------------------------------------------+export const TUTORIAL_STEPS = [+ {+ id: 'move', kind: 'move', count: 8,+ title: 'Find your footing',+ desc: 'Use WASD (or the joystick on touch) to walk. Take a few steps to get your bearings.',+ guide: "Welcome to the Mainland, traveler. First — get a feel for your feet. Walk around a little.",+ },+ {+ id: 'meet', kind: 'talk', count: 1,+ title: 'Meet Aldric',+ desc: 'Walk up to Aldric the Guide by the fountain and talk to him.',+ guide: "Good. I'm Aldric — I keep new arrivals from wandering into an ogre on day one. Let me show you the ropes.",+ },+ {+ id: 'chop', kind: 'gather', item: 'wood', count: 1, slot: 0,+ title: 'Chop a tree',+ desc: 'Equip your axe (hotbar slot 1), then click a tree to walk over and chop it for wood.',+ guide: 'See those trees to the west? Equip your axe — slot 1 — and click one. Bring back some wood.',+ },+ {+ id: 'mine', kind: 'gather', item: 'stone', count: 1, slot: 1,+ title: 'Mine some stone',+ desc: 'Switch to your pickaxe (hotbar slot 2) and click a rock to mine stone.',+ guide: 'Different tools for different jobs. Switch to your pickaxe — slot 2 — and chip at the rocks to the northeast.',+ },+ {+ id: 'fight', kind: 'combat', count: 1, slot: 3,+ title: 'Train your blade',+ desc: 'Equip your sword (hotbar slot 4) and click a training dummy to defeat it.',+ guide: 'Steel next. Equip your sword — slot 4 — and put a training dummy out of its misery. Mind, real beasts hit back.',+ },+ {+ id: 'bank', kind: 'bank', count: 1,+ title: 'Stash your loot',+ desc: 'Stand on the glowing bank counter, open the bank, and deposit an item to keep it safe.',+ guide: 'Carry too much and a death will scatter it. Step onto the bank counter — the gold tiles — and stash something.',+ },+ {+ id: 'report', kind: 'talk', count: 1,+ title: 'Report back',+ desc: 'Return to Aldric to complete your training and claim your reward.',+ guide: "You've got the loop: gather, fight, bank. Come see me to wrap up — there's a reward in it for you.",+ },+];++// The line Aldric speaks once the tutorial is finished (replay-safe; he keeps+// pointing the player at the daily board afterward).+export const GUIDE_DONE = "Training complete. Check the daily board — fresh bounties every day, and they pay. Safe travels.";++export const TUTORIAL_REWARD = { gold: 150, xp: { combat: 60, woodcutting: 60, mining: 60 }, badge: 'newcomer' };++// ---------------------------------------------------------------------------+// Daily quests — the pool three are drawn from each day. Every entry is+// completable on the Mainland realm alone (wood/stone/coal nodes + training+// dummies), so a rolled set is never impossible to clear here.+// ---------------------------------------------------------------------------+export const DAILY_POOL = [+ { id: 'd_wood', type: 'gather', item: 'wood', count: 15, title: 'Lumberjack', desc: 'Chop 15 wood.', reward: { gold: 120, xp: { woodcutting: 160 }, badge: 'forager' } },+ { id: 'd_haul', type: 'gather', item: 'wood', count: 30, title: 'Big Haul', desc: 'Chop 30 wood.', reward: { gold: 260, xp: { woodcutting: 320 } } },+ { id: 'd_stone', type: 'gather', item: 'stone', count: 12, title: 'Stonemason', desc: 'Mine 12 stone.', reward: { gold: 140, xp: { mining: 170 }, badge: 'forager' } },+ { id: 'd_coal', type: 'gather', item: 'coal', count: 6, title: 'Coal Run', desc: 'Mine 6 coal.', reward: { gold: 180, xp: { mining: 200 }, item: { id: 'coal', qty: 3 } } },+ { id: 'd_combat', type: 'combat', count: 8, title: 'Monster Hunter', desc: 'Defeat 8 foes.', reward: { gold: 200, xp: { combat: 240 }, badge: 'warrior' } },+ { id: 'd_train', type: 'combat', count: 3, title: 'Sparring', desc: 'Defeat 3 training dummies.', reward: { gold: 80, xp: { combat: 90 } } },+];++export const DAILY_COUNT = 3;++// A stable 32-bit hash of a string (FNV-1a). Deterministic across processes.+function hashString(s) {+ let h = 0x811c9dc5;+ for (let i = 0; i < s.length; i++) {+ h ^= s.charCodeAt(i);+ h = Math.imul(h, 0x01000193);+ }+ return h >>> 0;+}++// 'YYYY-MM-DD' in UTC for `now` (epoch ms). The daily boundary is UTC midnight.+export function dailyKey(now) {+ return new Date(now).toISOString().slice(0, 10);+}++// Epoch ms of the next UTC midnight after `now` — the moment the current+// dailies expire and a fresh set rolls. The client renders a live countdown to+// this and re-requests its quests when it passes.+export function nextResetAt(now) {+ const d = new Date(now);+ return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate() + 1, 0, 0, 0, 0);+}++// Deterministically pick DAILY_COUNT distinct quests for (playerId, dateKey).+// Seeded Fisher–Yates over the pool indices using a hash of playerId+date, so a+// player's set is fixed for the day and identical on every reconnect/restart.+export function rollDailies(playerId, dateKey) {+ const seed = hashString(`${playerId}|${dateKey}`);+ const idx = DAILY_POOL.map((_, i) => i);+ // xorshift32 PRNG seeded from the hash — pure, no global RNG.+ let state = seed || 1;+ const rand = () => {+ state ^= state << 13; state >>>= 0;+ state ^= state >> 17;+ state ^= state << 5; state >>>= 0;+ return state / 0xffffffff;+ };+ for (let i = idx.length - 1; i > 0; i--) {+ const j = Math.floor(rand() * (i + 1));+ [idx[i], idx[j]] = [idx[j], idx[i]];+ }+ return idx.slice(0, DAILY_COUNT).map((i) => ({ id: DAILY_POOL[i].id, progress: 0, claimed: false }));+}++export function dailyDef(id) {+ return DAILY_POOL.find((q) => q.id === id) || null;+}++// Fresh, never-started quest state for a brand-new account.+export function freshQuestState(playerId, now) {+ const date = dailyKey(now);+ return {+ tutorial: { step: 0, progress: 0, done: false },+ daily: { date, quests: rollDailies(playerId, date) },+ badges: [],+ };+}++// Bring a (possibly persisted) quest-state blob up to date: re-roll the dailies+// if the UTC day has turned over since it was saved, and backfill any missing+// shape so older/partial saves load cleanly. Mutates and returns `qs`.+export function normalizeQuestState(qs, playerId, now) {+ if (!qs || typeof qs !== 'object') return freshQuestState(playerId, now);+ if (!qs.tutorial || typeof qs.tutorial !== 'object') qs.tutorial = { step: 0, progress: 0, done: false };+ if (!Array.isArray(qs.badges)) qs.badges = [];+ const date = dailyKey(now);+ if (!qs.daily || qs.daily.date !== date || !Array.isArray(qs.daily.quests)) {+ qs.daily = { date, quests: rollDailies(playerId, date) };+ } else {+ // Drop any quest whose definition no longer exists (pool changed between+ // deploys) so the client never renders an orphan.+ qs.daily.quests = qs.daily.quests.filter((q) => dailyDef(q.id));+ if (!qs.daily.quests.length) qs.daily.quests = rollDailies(playerId, date);+ }+ return qs;+}++export function currentStep(qs) {+ if (qs.tutorial.done) return null;+ return TUTORIAL_STEPS[qs.tutorial.step] || null;+}diff --git a/multiplayer/src/rooms/GameRoom.js b/multiplayer/src/rooms/GameRoom.jsindex 4cc196b4d..0cca1f988 100644--- a/multiplayer/src/rooms/GameRoom.js+++ b/multiplayer/src/rooms/GameRoom.js@@ -13,16 +13,22 @@import { Room } from '@colyseus/core';-import { GameState, GamePlayer, ResourceNode, Mob, Slot } from '../schemas/game.js';-import { REALMS, isBlocked as _isBlocked, inBounds as _inBounds } from './realms.js';+import { GameState, GamePlayer, ResourceNode, Mob, Slot, Tombstone } from '../schemas/game.js';+import { REALMS, DEFAULT_REALM, isBlocked, inBounds, realmLayout, fishingSpotNear } from './realms.js';+import { runCommand } from './commands.js';+import { STACKABLE_ITEMS, isEdible, healValue, isMount, mountStepMs, rollLoot, itemLabel, clientItemRegistry, cookBurnChance } from '../items.js';import { cleanAvatarUrl } from '../avatar-url.js';--// The standalone isometric activity runs on the Mainland realm. The realms-// module now exposes every realm under REALMS with (realm, tx, ty) helpers, so-// bind the single-realm helpers this room expects to Mainland.-const MAINLAND = REALMS.mainland;-const isBlocked = (tx, ty) => _isBlocked(MAINLAND, tx, ty);-const inBounds = (tx, ty) => _inBounds(MAINLAND, tx, ty);+import { loadPlayer, savePlayer } from '../playerStore.js';+import {+ TUTORIAL_STEPS, TUTORIAL_REWARD, GUIDE_DONE, BADGES, DAILY_POOL,+ dailyDef, nextResetAt, freshQuestState, normalizeQuestState, currentStep,+} from '../quests.js';++// One GameRoom instance == one realm. The realm is selected by the room+// definition (`options.realm`, see index.js); every geometry / spawn / flag+// lookup reads `this.realm`, so the same class serves Mainland, Wilderness,+// Whisperwood, and Pond. A realm's `danger` flag is what gates death-bag drops+// (Task 02): dying in a danger realm spills part of your pack into a tombstone.const MAX_CLIENTS_PER_ROOM = 50;const PATCH_RATE_MS = 1000 / 15;@@ -33,12 +39,26 @@ const HOTBAR_SIZE = 6;const MAX_STACK = 999;const BANK_SIZE = 48;-const STACKABLE = new Set(['wood', 'stone', 'coal', 'fish']);+// Which items stack is owned by the item registry (items.js) so cooking, loot,+// banking, and the shop all agree. cookedFish + potions land here automatically.+const STACKABLE = STACKABLE_ITEMS;const TOOLS = new Set(['axe', 'pickaxe', 'rod', 'hammer', 'sword']);+// The five trainable skills, broadcast as integer levels on GamePlayer. The+// order here is the canonical display order the client renders. LEVEL_CAP is the+// shared ceiling — surfaced to the client so the UI never hard-codes it.+const SKILLS = ['combat', 'woodcutting', 'mining', 'fishing', 'cooking'];+const LEVEL_CAP = 99;+// Per-action rate limits (messages/sec) — generous vs. legit play, tight vs.-// floods. Movement is the hot path so it gets the most headroom.-const RATE_LIMITS = { step: 20, gather: 6, attack: 6, ui: 30 };+// floods. Movement is the hot path so it gets the most headroom. Chat sits low:+// a few lines a second is plenty for conversation and turns a scripted flood into+// dropped messages (with feedback — see _handleChat).+const RATE_LIMITS = { step: 20, gather: 6, attack: 6, fish: 6, cook: 6, consume: 6, ui: 30, chat: 4 };++// World chat: hard cap on a single message. Longer messages are rejected (not+// silently truncated) so the sender knows their line didn't go through whole.+const MAX_CHAT_LEN = 200;// Gathering: which tool + skill each node kind needs, and what it yields.const NODE_RULES = {@@ -49,8 +69,32 @@ const NODE_RULES = {const GATHER_COOLDOWN_MS = 900; // time between successful harvestsconst ATTACK_COOLDOWN_MS = 700;+const COOK_COOLDOWN_MS = 1200; // pace between cook actions+const COOK_BATCH_MAX = 5; // raw fish processed per cook action (one cooldown)+const COOK_XP = 12; // cooking XP per fish successfully cooked (burns yield none)+const CONSUME_COOLDOWN_MS = 1100; // pace between bites — no instant heal-spam+const FISH_COOLDOWN_MS = 1500; // per-cast reel time — sets casting cadence on the real clock+// Catch curve: chance rises with fishing level and the spot's quality, hard-capped+// so even the richest water is never a guaranteed haul.+const FISH_BASE_CHANCE = 0.40; // catch chance at level 1 on an average (quality 1) spot+const FISH_CHANCE_PER_LEVEL = 0.005; // +0.5% per fishing level+const FISH_CHANCE_CAP = 0.95;const RESPAWN_PLAYER_MS = 4000;const RESPAWN_MOB_MS = 8000;++// Movement speed is server-authoritative (Task 09). On foot, a player may take a+// step no more often than every ON_FOOT_STEP_MS; mounts lower this floor via the+// item registry (items.js `mount.stepMs`), so riding is visibly faster without+// ever trusting a client-claimed speed.+const ON_FOOT_STEP_MS = 140;++// Death-bags (danger realms only). A tombstone lives for TOMBSTONE_TTL_MS, then+// crumbles server-side (and the client view follows). For the first+// TTL - GRACE window only the owner may loot it; once inside the final+// TOMBSTONE_GRACE_MS before expiry, anyone standing adjacent may take what's+// left — a fair "claim it fast or share it" rule.+const TOMBSTONE_TTL_MS = 120000; // 2 minutes+const TOMBSTONE_GRACE_MS = 45000; // last 45s: open to anyone adjacentconst FOUNTAIN_HEAL_PER_TICK = 6; // hp restored per sim tick near the fountainconst REGEN_PER_TICK = 1; // passive hp regen out of combat@@ -59,10 +103,20 @@ const REGEN_PER_TICK = 1; // passive hp regen out of combatfunction levelForXp(xp) {// level n requires 50 * n^1.8 cumulative XP. Cap at 99.let lvl = 1;- while (lvl < 99 && xp >= Math.floor(50 * Math.pow(lvl, 1.8))) lvl++;+ while (lvl < LEVEL_CAP && xp >= Math.floor(50 * Math.pow(lvl, 1.8))) lvl++;return lvl;}+// Inverse of levelForXp: the cumulative XP required to *be* at a given level.+// Level 1 starts at 0; reaching level L needs 50 * (L-1)^1.8 cumulative XP — the+// same threshold levelForXp compares against. Used to send the client the+// boundaries of its current level so it can draw an exact progress bar without+// re-deriving the curve (one source of truth for the formula).+function xpForLevel(level) {+ const lvl = Math.max(1, Math.min(LEVEL_CAP, level | 0));+ return lvl <= 1 ? 0 : Math.floor(50 * Math.pow(lvl - 1, 1.8));+}+function clean(str, maxLen) {if (typeof str !== 'string') return '';// Strip control chars (incl. NUL/escape), collapse whitespace, trim, cap.@@ -90,9 +144,17 @@ export class GameRoom extends Room {this.priv = new Map(); // sessionId -> { xp, bank: Slot[], cooldowns, rate }}- onCreate() {+ onCreate(options) {+ // The room definition pins which realm this instance hosts. An unknown or+ // missing name falls back to the default realm so the room never boots into+ // an undefined map.+ const name = REALMS[options?.realm] ? options.realm : DEFAULT_REALM;+ this.realm = REALMS[name];+ // Monotonic id source for tombstones spawned by this room.+ this._tombSeq = 0;+this.setState(new GameState());- this.state.realm = MAINLAND.name;+ this.state.realm = this.realm.name;this.setPatchRate(PATCH_RATE_MS);this.autoDispose = true;@@ -101,18 +163,35 @@ export class GameRoom extends Room {this.onMessage('step', (c, p) => this._handleStep(c, p));this.onMessage('gather', (c, p) => this._handleGather(c, p));this.onMessage('attack', (c, p) => this._handleAttack(c, p));+ this.onMessage('fish', (c, p) => this._handleFish(c, p));+ this.onMessage('cook', (c, p) => this._handleCook(c, p));+ this.onMessage('consume', (c, p) => this._handleConsume(c, p));this.onMessage('invMove', (c, p) => this._handleInvMove(c, p));this.onMessage('equip', (c, p) => this._handleEquip(c, p));this.onMessage('bankDeposit', (c, p) => this._handleBank(c, p, 'deposit'));this.onMessage('bankWithdraw', (c, p) => this._handleBank(c, p, 'withdraw'));this.onMessage('bankOpen', (c) => this._sendBank(c));+ this.onMessage('skills', (c) => this._sendSkills(c));+ this.onMessage('tombLoot', (c, p) => this._handleTombLoot(c, p));this.onMessage('setAvatar', (c, p) => this._handleAvatar(c, p));+ // Mounts (Task 09): use the active hotbar item (ride a mount), leave the saddle,+ // and a generic slash-command channel (Task 13's chat forwards /dismount here).+ this.onMessage('use', (c, p) => this._handleUse(c, p));+ this.onMessage('dismount', (c) => this._handleDismount(c));+ this.onMessage('command', (c, p) => this._handleCommand(c, p));+ // Quests (tutorial + dailies). The client only ever requests a snapshot,+ // talks to the guide, or asks to turn a finished quest in — all progress is+ // driven from the real action hooks below, never from a client claim.+ this.onMessage('questOpen', (c) => this._sendQuests(c));+ this.onMessage('npcTalk', (c, p) => this._handleNpcTalk(c, p));+ this.onMessage('questTurnIn', (c, p) => this._handleTurnIn(c, p));+ this.onMessage('chat', (c, p) => this._handleChat(c, p));this.setSimulationInterval(() => this._tick(), SIM_TICK_MS);}_seedWorld() {- for (const n of MAINLAND.nodes) {+ for (const n of this.realm.nodes) {const node = new ResourceNode();node.id = n.id;node.kind = n.kind;@@ -120,7 +199,7 @@ export class GameRoom extends Room {node.ty = n.ty;this.state.nodes.set(n.id, node);}- for (const m of MAINLAND.mobs) {+ for (const m of this.realm.mobs) {const mob = new Mob();mob.id = m.id;mob.kind = m.kind;@@ -133,12 +212,21 @@ export class GameRoom extends Room {onJoin(client, options) {const name = clean(options?.name, 24) || `guest-${client.sessionId.slice(0, 4)}`;+ // Stable account key: the wallet address / persistent guest id the client+ // sends (Task 16), falling back to the ephemeral session id when absent.+ // Tutorial completion, daily assignment, progress, and badges are keyed to+ // it so they survive a disconnect/reconnect.+ const playerId = clean(options?.pid, 80) || client.sessionId;+ const now = Date.now();+ const saved = loadPlayer(playerId);+ const quests = normalizeQuestState(saved?.quests, playerId, now) || freshQuestState(playerId, now);+const p = new GamePlayer();p.id = client.sessionId;p.name = name;p.color = pickPlayerColor(client.sessionId);- p.tx = MAINLAND.spawn.tx;- p.ty = MAINLAND.spawn.ty;+ p.tx = this.realm.spawn.tx;+ p.ty = this.realm.spawn.ty;// Fixed-length inventory + hotbar so slot indices are stable drag targets.for (let i = 0; i < INV_SIZE; i++) p.inv.push(new Slot());@@ -157,39 +245,47 @@ export class GameRoom extends Room {// as a join option, validated against the same host allow-list as /walk so// every peer renders them as their real avatar, not the default capsule.p.cosmetic = cleanAvatarUrl(options?.avatar);- p.tsServer = Date.now();+ p.badges = (quests.badges || []).join(',');+ p.tsServer = now;this.state.players.set(client.sessionId, p);this.priv.set(client.sessionId, {- xp: { woodcutting: 0, mining: 0, fishing: 0, combat: 0 },+ playerId,+ // One XP bucket per trainable skill. Levels are broadcast on the schema;+ // raw XP stays server-side and is only ever sent to its owner.+ xp: Object.fromEntries(SKILLS.map((s) => [s, 0])),bank: Array.from({ length: BANK_SIZE }, () => ({ item: '', qty: 0 })),- cooldowns: { gather: 0, attack: 0 },+ cooldowns: { gather: 0, attack: 0, fish: 0, cook: 0, consume: 0, step: 0 },rate: new Map(),+ quests,});- // Hand the client the static realm layout so it renders buildings,- // fountain, and the bank counter on exactly the tiles the server treats- // as solid/interactive. Dynamic objects (nodes, mobs, players) arrive via- // the synced schema state instead.- client.send('realm', {- name: MAINLAND.name,- grid: MAINLAND.grid,- spawn: MAINLAND.spawn,- fountain: MAINLAND.fountain,- blocked: MAINLAND.blocked,- bankZone: MAINLAND.bankZone,- });-- console.log(`[${MAINLAND.name} ${this.roomId}] +join ${name} (n=${this.state.players.size})`);+ // Hand the client the full static realm layout (geometry, fountain, bank+ // counter, fishing/cooking tiles, safe camp, portals, and the+ // safe/pvp/danger flags) so it renders exactly the tiles the server treats+ // as solid/interactive — and knows whether this realm drops death-bags.+ // Dynamic objects (nodes, mobs, players, tombstones) arrive via synced+ // schema state instead.+ client.send('realm', realmLayout(this.realm));+ // Item catalogue (icons, labels, mount tuning) so the hotbar can label items and+ // the scene can render the right steed. Static — sent once per join.+ client.send('items', clientItemRegistry());+ // Hand over the player's quest state (tutorial step, today's dailies ++ // progress, reset countdown, earned badges) so the quest panel and the+ // guide's "!"/"?" marker render immediately on entry.+ this._sendQuests(client);++ console.log(`[${this.realm.name} ${this.roomId}] +join ${name} (n=${this.state.players.size})`);}onLeave(client) {+ this._persistPlayer(client.sessionId);this.state.players.delete(client.sessionId);this.priv.delete(client.sessionId);}onDispose() {- console.log(`[${MAINLAND.name} ${this.roomId}] disposed`);+ console.log(`[${this.realm.name} ${this.roomId}] disposed`);}// ----- movement --------------------------------------------------------@@ -212,16 +308,32 @@ export class GameRoom extends Room {// Don't allow cutting a diagonal between two blocked corners.if (dx === 1 && dy === 1 && (!this._isWalkable(tx, p.ty) && !this._isWalkable(p.tx, ty))) return;+ // Server-enforced step floor (Task 09): on foot you step no faster than+ // ON_FOOT_STEP_MS; a mount lowers the floor (items.js) for visibly faster but+ // still authoritative travel. Early steps are dropped and the client self-paces+ // to match, so a client claiming mount speed without a mount gains nothing.+ const sPriv = this.priv.get(client.sessionId);+ const sNow = Date.now();+ const stepFloor = p.mounted ? (mountStepMs(p.mount) || ON_FOOT_STEP_MS) : ON_FOOT_STEP_MS;+ if (sPriv && sNow < (sPriv.cooldowns.step || 0)) return;+ if (sPriv) sPriv.cooldowns.step = sNow + stepFloor;+p.tx = tx;p.ty = ty;if (typeof payload.yaw === 'number' && Number.isFinite(payload.yaw)) p.yaw = payload.yaw;p.motion = 'walk';p.tsServer = Date.now();+ // Tutorial: the very first step is simply learning to walk.+ this._questProgress(client, { kind: 'move', n: 1 });}_isWalkable(tx, ty) {- if (!inBounds(tx, ty)) return false;- if (isBlocked(tx, ty)) return false;+ if (!inBounds(this.realm, tx, ty)) return false;+ if (isBlocked(this.realm, tx, ty)) return false;+ // Fixed NPCs occupy their tile; players stand adjacent to talk.+ for (const n of this.realm.npcs || []) {+ if (n.tx === tx && n.ty === ty) return false;+ }// Non-depleted resource nodes occupy their tile.for (const [, n] of this.state.nodes) {if (!n.depleted && n.tx === tx && n.ty === ty) return false;@@ -238,6 +350,9 @@ export class GameRoom extends Room {_handleGather(client, payload) {const p = this.state.players.get(client.sessionId);if (!p || p.dead) return;+ // Mounted players ride; they can't swing a tool. Dismount to harvest. (Combat+ // stays allowed while mounted — cavalry can fight.)+ if (p.mounted) { client.send('notice', { kind: 'mount', text: 'Dismount before you gather.' }); return; }if (!this._rateOk(client.sessionId, 'gather')) return;const node = this.state.nodes.get(String(payload?.id ?? ''));if (!node || node.depleted) return;@@ -265,13 +380,228 @@ export class GameRoom extends Room {client.send('notice', { kind: 'full', text: 'Your inventory is full.' });return;}- if (node.kind === 'rock' && Math.random() < 0.15) this._addItem(p, 'coal', 1);+ let bonusCoal = false;+ if (node.kind === 'rock' && Math.random() < 0.15) { this._addItem(p, 'coal', 1); bonusCoal = true; }- this._grantXp(client.sessionId, p, rule.skill, 8 + Math.floor(Math.random() * 5));+ this._grantXp(client, p, rule.skill, 8 + Math.floor(Math.random() * 5));node.depleted = true;node.respawnAt = now + rule.respawnMs;priv.cooldowns.gather = now + GATHER_COOLDOWN_MS;p.tsServer = now;+ // Quest progress: the resource just harvested (plus any bonus coal from a+ // rock) counts toward gathering tutorial steps and dailies.+ this._questProgress(client, { kind: 'gather', item: rule.item, n: 1 });+ if (bonusCoal) this._questProgress(client, { kind: 'gather', item: 'coal', n: 1 });+ }++ // ----- fishing ---------------------------------------------------------++ // Cast a line. Validates (alive, rod equipped, beside fishable water, off+ // cooldown, room in the pack) then rolls a catch against fishing skill + spot+ // quality. Every cast — hit or miss — arms the per-cast cooldown so casting+ // has cadence on the real clock; the client renders the line/bobber while the+ // authoritative result rides back as a notice.+ _handleFish(client, payload) {+ const p = this.state.players.get(client.sessionId);+ if (!p || p.dead) return;+ if (!this._rateOk(client.sessionId, 'fish')) return;++ const priv = this.priv.get(client.sessionId);+ const now = Date.now();+ if (now < priv.cooldowns.fish) return; // still reeling in the previous cast++ // Need the rod on the active hotbar slot.+ const active = p.hotbar[p.activeSlot];+ if (!active || active.item !== 'rod') {+ client.send('notice', { kind: 'tool', text: 'Equip a fishing rod to cast.' });+ return;+ }++ // Need fishable water within one tile (8-way, including the player's tile).+ const spot = fishingSpotNear(this.realm, p.tx, p.ty);+ if (!spot) {+ client.send('notice', { kind: 'fish', text: 'Move next to the water to cast.' });+ return;+ }++ // Don't let a catch evaporate: reject the cast up front when there's no room+ // for even one fish — same notice the gather path uses.+ if (!this._hasRoomFor(p, 'fish')) {+ client.send('notice', { kind: 'full', text: 'Your inventory is full.' });+ return;+ }++ // Arm the cadence on the real cooldown clock (no fake timers).+ priv.cooldowns.fish = now + FISH_COOLDOWN_MS;++ const lvl = p.fishing;+ const quality = spot.quality || 1;+ const chance = Math.min(+ FISH_CHANCE_CAP,+ (FISH_BASE_CHANCE + FISH_CHANCE_PER_LEVEL * (lvl - 1)) * quality,+ );++ if (Math.random() < chance) {+ // Yield: usually one fish, with a skill/quality-scaled shot at a double haul.+ const doubleChance = Math.min(0.45, 0.02 * (lvl - 1) * quality);+ const want = 1 + (Math.random() < doubleChance ? 1 : 0);+ const leftover = this._addItem(p, 'fish', want);+ const caught = want - leftover;+ if (caught <= 0) {+ // Pack filled between the room check and now — be honest, no phantom catch.+ client.send('notice', { kind: 'full', text: 'Your inventory is full.' });+ p.tsServer = now;+ return;+ }+ // XP scales gently with level + quality so richer water trains faster.+ const xp = Math.round((10 + Math.floor(Math.random() * 6) + lvl * 0.3) * quality) * caught;+ this._grantXp(client, p, 'fishing', xp);+ client.send('notice', { kind: 'fish', text: caught > 1 ? `Caught ${caught} fish!` : 'Caught a fish.' });+ } else {+ // A miss still teaches the cast — a small XP trickle keeps progression smooth.+ this._grantXp(client, p, 'fishing', 2);+ client.send('notice', { kind: 'fish', text: 'The fish got away.' });+ }+ p.tsServer = now;+ }++ // Is there room in the backpack for at least one of `item`? For stackables, an+ // empty slot OR a non-full existing stack counts; otherwise an empty slot.+ _hasRoomFor(p, item) {+ if (STACKABLE.has(item)) {+ for (const s of p.inv) {+ if (!s.item) return true;+ if (s.item === item && s.qty < MAX_STACK) return true;+ }+ return false;+ }+ return p.inv.some((s) => !s.item);+ }++ // ----- cooking & consumables -------------------------------------------++ // Cook raw fish into cooked fish at a Roast Pit. Validates the player is+ // alive, standing on/next to a cooking tile of THIS realm, and actually holds+ // raw fish; then converts up to a small batch in one action (one cooldown).+ // Low cooking levels burn some fish — the raw fish is consumed with no result+ // and the player is told honestly; burns grant no XP. Never loses or dupes an+ // item: the cooked result is reserved (pack space checked) before the raw fish+ // is spent.+ _handleCook(client, payload) {+ const p = this.state.players.get(client.sessionId);+ if (!p || p.dead) return;+ if (!this._rateOk(client.sessionId, 'cook')) return;++ const priv = this.priv.get(client.sessionId);+ const now = Date.now();+ if (now < priv.cooldowns.cook) return;++ if (!this._atCookingSpot(p)) {+ client.send('notice', { kind: 'cook', text: 'Stand by the Roast Pit to cook.' });+ return;+ }++ const fish = this._findItemSlot(p, 'fish');+ if (!fish) {+ client.send('notice', { kind: 'cook', text: 'You have no raw fish to cook.' });+ return;+ }++ const want = Math.max(1, Math.min(COOK_BATCH_MAX, payload?.qty | 0 || 1));+ const level = p.cooking;+ let cooked = 0;+ let burned = 0;+ for (let i = 0; i < want; i++) {+ const slot = fish.slot;+ if (slot.item !== 'fish' || slot.qty <= 0) break; // stack exhausted+ if (Math.random() < cookBurnChance(level)) {+ // Burned: the raw fish is gone, nothing to store, no XP.+ slot.qty -= 1;+ if (slot.qty === 0) slot.item = '';+ burned++;+ continue;+ }+ // Success: reserve pack space for the cooked fish BEFORE spending the raw+ // one. If the pack is full, stop the batch with no item lost.+ const leftover = this._addItem(p, 'cookedFish', 1);+ if (leftover >= 1) {+ if (cooked === 0 && burned === 0) {+ client.send('notice', { kind: 'full', text: 'Your inventory is full.' });+ return;+ }+ break;+ }+ slot.qty -= 1;+ if (slot.qty === 0) slot.item = '';+ this._grantXp(client, p, 'cooking', COOK_XP);+ cooked++;+ }++ if (cooked === 0 && burned === 0) return;+ priv.cooldowns.cook = now + COOK_COOLDOWN_MS;+ p.tsServer = now;++ // Honest result: report exactly what the fire produced.+ const parts = [];+ if (cooked) parts.push(`Cooked ${cooked} fish`);+ if (burned) parts.push(`burned ${burned}`);+ client.send('cooked', { cooked, burned, level: p.cooking });+ client.send('notice', { kind: cooked ? 'cook' : 'burn', text: `${parts.join(', ')}.` });+ }++ // Eat an edible item (cooked fish, potions) from a referenced inv/hotbar slot+ // to restore HP. Server-authoritative: validates the slot really holds an+ // edible item, refuses at full health (so food is never silently wasted),+ // heals up to maxHp (never over), consumes one from the stack, and applies a+ // short cooldown. Works from both the backpack and the hotbar.+ _handleConsume(client, payload) {+ const p = this.state.players.get(client.sessionId);+ if (!p || p.dead) return;+ if (!this._rateOk(client.sessionId, 'consume')) return;++ const priv = this.priv.get(client.sessionId);+ const now = Date.now();+ if (now < priv.cooldowns.consume) return;++ const ref = this._resolveSlot(p, payload?.slot);+ if (!ref) return;+ const slot = ref.slot;+ if (!slot.item || !isEdible(slot.item)) {+ client.send('notice', { kind: 'eat', text: 'That can’t be eaten.' });+ return;+ }+ if (p.hp >= p.maxHp) {+ client.send('notice', { kind: 'eat', text: 'You’re already at full health.' });+ return;+ }++ const before = p.hp;+ p.hp = Math.min(p.maxHp, p.hp + healValue(slot.item));+ slot.qty -= 1;+ if (slot.qty === 0) slot.item = '';+ priv.cooldowns.consume = now + CONSUME_COOLDOWN_MS;+ p.tsServer = now;+ client.send('notice', { kind: 'eat', text: `+${p.hp - before} HP.` });+ }++ // True if the player is on or directly adjacent to any cooking tile (the Roast+ // Pit) of the current realm — you stand by the fire, not necessarily on it.+ _atCookingSpot(p) {+ const tiles = this.realm.cooking || [];+ for (const t of tiles) {+ if (Math.abs(p.tx - t.tx) <= 1 && Math.abs(p.ty - t.ty) <= 1) return true;+ }+ return false;+ }++ // Find a live slot holding `item`: the active hotbar slot first (what you're+ // "holding"), then the rest of the hotbar, then the backpack. Null if none.+ _findItemSlot(p, item) {+ const active = p.hotbar[p.activeSlot];+ if (active && active.item === item && active.qty > 0) return { slot: active };+ for (const s of p.hotbar) if (s.item === item && s.qty > 0) return { slot: s };+ for (const s of p.inv) if (s.item === item && s.qty > 0) return { slot: s };+ return null;}// ----- combat ----------------------------------------------------------@@ -302,12 +632,567 @@ export class GameRoom extends Room {mob.respawnAt = now + RESPAWN_MOB_MS;const reward = 5 + Math.floor(Math.random() * 6);p.gold = Math.min(0xffffffff, p.gold + reward);- this._grantXp(client.sessionId, p, 'combat', 14 + Math.floor(Math.random() * 8));+ this._grantXp(client, p, 'combat', 14 + Math.floor(Math.random() * 8));client.send('notice', { kind: 'kill', text: `Defeated ${mob.kind} (+${reward}g).` });+ // Task 09: roll the mob's loot table — materials and, rarely, a ridable mount.+ this._awardLoot(client, p, mob);+ // Quest progress: a defeated foe counts toward combat tutorial + dailies.+ this._questProgress(client, { kind: 'combat', n: 1 });+ }+ p.tsServer = now;+ }++ // ----- mounts & loot ---------------------------------------------------++ // Roll a slain mob's loot table and hand the killer their winnings. Mounts are+ // rare; everything else is gathered material. Items go to the pack (mounts prefer+ // a free HOTBAR slot so they're immediately rideable); anything that doesn't fit+ // spills into a ground bag on the mob's tile instead of vanishing — loot is never+ // silently lost on a full pack.+ _awardLoot(client, p, mob) {+ const drops = rollLoot(mob.kind);+ if (!drops.length) return;+ const spoils = []; // non-mount lines for the loot toast+ const overflow = []; // Slots that didn't fit anywhere → ground bag+ let mount = null; // { label, bagged } when a mount drops+ for (const d of drops) {+ const left = this._giveLoot(p, d.item, d.qty);+ const got = d.qty - left;+ if (isMount(d.item)) {+ if (got > 0 || left > 0) mount = { label: itemLabel(d.item), bagged: left > 0 };+ } else if (got > 0) {+ spoils.push(got > 1 ? `${got}× ${itemLabel(d.item)}` : itemLabel(d.item));+ }+ if (left > 0) overflow.push(new Slot(d.item, left));+ }+ if (overflow.length) this._spawnLootBag(p, mob.tx, mob.ty, overflow);++ if (mount) {+ const where = mount.bagged ? 'It dropped into the bag at your feet.' : 'It’s on your hotbar — ride out!';+ client.send('notice', { kind: 'mount', text: `The ${mob.kind} dropped a ${mount.label}! ${where}` });+ }+ if (spoils.length) client.send('notice', { kind: 'loot', text: `Looted ${spoils.join(', ')}.` });+ if (overflow.length && !(mount && mount.bagged)) {+ client.send('notice', { kind: 'full', text: 'Pack full — extra loot waits in a bag at your feet.' });+ }+ }++ // Give looted items to a player. Mounts are seated on a free HOTBAR slot first+ // (there is no inv→hotbar mover yet, and a mount you can't reach is useless),+ // then the backpack; everything else goes straight to the backpack. Returns the+ // quantity that didn't fit anywhere.+ _giveLoot(p, item, qty) {+ if (isMount(item)) {+ let placed = 0;+ for (const s of p.hotbar) {+ if (placed >= qty) break;+ if (!s.item) { s.item = item; s.qty = 1; placed++; }+ }+ if (placed >= qty) return 0;+ return this._addItem(p, item, qty - placed);+ }+ return this._addItem(p, item, qty);+ }++ // Spill overflow loot into a ground bag on (tx,ty) owned by the killer — the same+ // Tombstone vessel + tombLoot recovery path used by death-bags, so loot never+ // vanishes on a full pack and the client renders/recovers it identically.+ _spawnLootBag(p, tx, ty, slots) {+ const now = Date.now();+ const bag = new Tombstone();+ bag.id = `loot_${this.realm.name}_${p.id}_${++this._tombSeq}`;+ bag.owner = p.id;+ bag.ownerName = p.name;+ bag.tx = tx;+ bag.ty = ty;+ bag.expiresAt = now + TOMBSTONE_TTL_MS;+ for (const s of slots) bag.items.push(s);+ this.state.tombstones.set(bag.id, bag);+ return bag.items.length;+ }++ // Use the active hotbar item (or an explicit slot). Today that rides a mount; the+ // registry decides what "use" means per item, so future usable items slot in here+ // without a new intent. A stray click on a non-usable item is a harmless no-op.+ _handleUse(client, payload) {+ const p = this.state.players.get(client.sessionId);+ if (!p || p.dead) return;+ if (!this._rateOk(client.sessionId, 'ui')) return;+ let i = p.activeSlot;+ if (payload && Number.isInteger(payload.slot)) i = payload.slot | 0;+ if (i < 0 || i >= HOTBAR_SIZE) return;+ const slot = p.hotbar[i];+ if (!slot || !slot.item) return;+ if (isMount(slot.item)) {+ p.activeSlot = i; // hold the reins+ this._mount(client, p, slot.item);+ }+ }++ // Mount up: flip to the faster server-enforced cadence and record the steed so+ // peers render it. Re-mounting the same steed is a no-op; swapping steeds just+ // changes which creature you ride.+ _mount(client, p, item) {+ if (p.mounted && p.mount === item) return;+ p.mounted = true;+ p.mount = item;+ p.tsServer = Date.now();+ client.send('notice', { kind: 'mount', text: `Mounted your ${itemLabel(item)}.` });+ }++ // Leave the saddle, back to on-foot speed. Idempotent and friendly when already+ // on foot. Routed to by the 'dismount' intent and the /dismount command.+ _handleDismount(client) {+ const p = this.state.players.get(client.sessionId);+ if (!p) return;+ if (!this._rateOk(client.sessionId, 'ui')) return;+ if (!p.mounted) { client.send('notice', { kind: 'mount', text: 'You’re not mounted.' }); return; }+ const was = p.mount;+ p.mounted = false;+ p.mount = '';+ p.tsServer = Date.now();+ client.send('notice', { kind: 'mount', text: `Dismounted your ${itemLabel(was)}.` });+ }++ // ----- world chat ------------------------------------------------------++ // Realm-wide chat. This room IS one realm, so a broadcast reaches exactly the+ // players who can see each other — chat never leaks across realms/instances.+ // Leading-'/' messages are handed to the command router instead of broadcast+ // (Task 13); everything else is sanitized, length-capped, rate-limited, and+ // echoed to everyone (the sender included, so their own line is driven by the+ // same authoritative event their peers receive).+ _handleChat(client, payload) {+ const p = this.state.players.get(client.sessionId);+ if (!p) return;+ const now = Date.now();+ // Sanitize up front (strip control chars, collapse whitespace, trim). Cap+ // generously here so we can still measure "too long" against MAX_CHAT_LEN+ // rather than silently truncating to it.+ const text = clean(payload?.text, 2000);+ if (!text) return;++ // Slash-commands bypass chat entirely — the command router has its own+ // validation and rate limit, so route before charging a chat token.+ if (text[0] === '/') { this._handleCommand(client, { text }); return; }++ // Flood control. Tell the sender (throttled, so a flood can't be amplified+ // into a flood of error replies) instead of dropping silently.+ if (!this._rateOk(client.sessionId, 'chat')) {+ const priv = this.priv.get(client.sessionId);+ if (priv && now - (priv.chatNoticeAt || 0) > 1500) {+ priv.chatNoticeAt = now;+ client.send('chat', { system: true, kind: 'error', text: 'You’re sending messages too fast.', ts: now });+ }+ return;+ }++ // Length cap — reject rather than truncate so nothing is sent half-said.+ if (text.length > MAX_CHAT_LEN) {+ client.send('chat', { system: true, kind: 'error', text: `Message too long. Keep it under ${MAX_CHAT_LEN} characters.`, ts: now });+ return;+ }++ this.broadcast('chat', { id: client.sessionId, name: p.name, text, ts: now });+ }++ // Slash-command channel. Task 13's chat forwards any leading-'/' message here; the+ // game HUD also calls it directly. Handles /dismount and /mount today; unknown+ // commands get an honest reply rather than silence.+ _handleCommand(client, payload) {+ const p = this.state.players.get(client.sessionId);+ if (!p) return;+ if (!this._rateOk(client.sessionId, 'ui')) return;+ const text = clean(payload?.text, 64);+ const cmd = text.replace(/^\//, '').split(/\s+/)[0].toLowerCase();++ // /mount needs the hotbar + item registry, so it stays inline; every other+ // command is dispatched through the Task 13 registry — the single source of+ // truth for /help, /who, /pickup, /lock, /unlock, /dismount.+ if (cmd === 'mount') {+ const slot = p.hotbar[p.activeSlot];+ if (slot && isMount(slot.item)) this._mount(client, p, slot.item);+ else client.send('notice', { kind: 'mount', text: 'Select a mount on your hotbar first.' });+ return;+ }++ const reply = runCommand({ room: this, client, player: p }, text);+ // Command replies render as system chat lines — distinct from player chat —+ // so multi-line output (/help, /who) stays readable instead of flashing past+ // as a toast. A null reply means the handler already answered (e.g. /dismount).+ if (reply && reply.text) {+ client.send('chat', { system: true, kind: reply.kind || 'system', text: reply.text, ts: Date.now() });+ }+ }++ // ----- structure actions (Task 07 firepit/shack; invoked by /pickup /lock /unlock) ----+ // These operate on real synced state.structures and never throw on the empty+ // case: until Task 07's building action places a structure the map is empty, so+ // they honestly report "nothing placed" — and the moment structures exist they+ // work unchanged. Only the owner can act, and only on a structure beside them.++ pickupStructure(p) {+ const owned = [];+ for (const [, s] of this.state.structures) if (s.owner === p.id) owned.push(s);+ if (!owned.length) return { text: 'You have not placed a firepit or shack to pick up.', kind: 'error' };+ const near = owned.filter((s) => this._adjacent(p, s)).sort((a, b) => this._d2(p, a) - this._d2(p, b));+ if (!near.length) {+ const where = owned.map((s) => ` • ${s.kind} at (${s.tx}, ${s.ty})`).join('\n');+ return { text: `Stand next to one of your structures to pick it up:\n${where}`, kind: 'info' };+ }+ const s = near[0];+ if (s.locked) return { text: `Your ${s.kind} is locked — /unlock it first.`, kind: 'error' };+ this.state.structures.delete(s.id);+ return { text: `Picked up your ${s.kind}.`, kind: 'info' };+ }++ setStructureLock(p, locked) {+ let target = null;+ for (const [, s] of this.state.structures) {+ if (s.owner === p.id && this._adjacent(p, s) && (!target || this._d2(p, s) < this._d2(p, target))) target = s;+ }+ if (!target) return { text: `Stand next to your own firepit or shack to ${locked ? 'lock' : 'unlock'} it.`, kind: 'error' };+ if (target.locked === locked) return { text: `Your ${target.kind} is already ${locked ? 'locked' : 'unlocked'}.`, kind: 'info' };+ target.locked = locked;+ const k = target.kind.charAt(0).toUpperCase() + target.kind.slice(1);+ return { text: `${k} ${locked ? 'locked' : 'unlocked'}.`, kind: 'info' };+ }++ // Squared tile distance — cheap "nearest" ordering, no sqrt.+ _d2(a, b) { const dx = a.tx - b.tx, dy = a.ty - b.ty; return dx * dx + dy * dy; }++ // ----- death & tombstones ----------------------------------------------++ // Single funnel for all damage to a player (mob contact in Task 03, PvP in+ // Task 04, environment, …). Clamps HP at 0 and, when it lands the killing+ // blow, routes through _killPlayer so death/tombstone/respawn happen in+ // exactly one place. Returns true if the hit was fatal. `opts.byName` (and+ // `opts.by`) label the cause for the death notice.+ _damagePlayer(p, amount, opts = {}) {+ if (!p || p.dead) return false;+ const dmg = Math.max(0, Math.floor(amount));+ if (dmg <= 0) return false;+ p.hp = Math.max(0, p.hp - dmg);+ p.tsServer = Date.now();+ if (p.hp === 0) {+ this._killPlayer(p, opts);+ return true;+ }+ return false;+ }++ // Kill a player: freeze them, schedule a respawn, and — only in a danger+ // realm — spill the droppable part of their pack into a tombstone on the tile+ // they fell. Idempotent: a second call on an already-dead player is a no-op.+ _killPlayer(p, opts = {}) {+ if (!p || p.dead) return;+ const now = Date.now();+ p.dead = true;+ // Task 09: auto-dismount on death — no keeping the saddle through a respawn.+ if (p.mounted) { p.mounted = false; p.mount = ''; }+ p.motion = 'idle';+ p.hp = 0;+ p.respawnAt = now + RESPAWN_PLAYER_MS;++ let droppedCount = 0;+ if (this.realm.danger) droppedCount = this._dropTombstone(p, now);++ const client = this._clientFor(p.id);+ client?.send('died', {+ realm: this.realm.name,+ danger: !!this.realm.danger,+ respawnAt: p.respawnAt,+ dropped: droppedCount,+ byName: opts.byName || '',+ });+ p.tsServer = now;+ }++ // Drop rule (deterministic & fair): you KEEP your tools (axe/pickaxe/rod/+ // hammer/sword) wherever they sit — losing the means to recover would be+ // punishing and grief-prone — and you DROP everything else (gathered+ // resources, food, and any other non-tool item) from BOTH the backpack and+ // the hotbar into the bag. Gold is a currency, not an inventory item, so it+ // is never dropped. Returns the number of slots that landed in the tombstone.+ _dropTombstone(p, now) {+ const tomb = new Tombstone();+ tomb.id = `tomb_${this.realm.name}_${p.id}_${++this._tombSeq}`;+ tomb.owner = p.id;+ tomb.ownerName = p.name;+ tomb.tx = p.tx;+ tomb.ty = p.ty;+ tomb.expiresAt = now + TOMBSTONE_TTL_MS;++ for (const slot of [...p.inv, ...p.hotbar]) {+ if (!slot.item || TOOLS.has(slot.item)) continue;+ tomb.items.push(new Slot(slot.item, slot.qty));+ slot.item = '';+ slot.qty = 0;+ }++ if (tomb.items.length === 0) return 0; // nothing droppable — no empty bag+ this.state.tombstones.set(tomb.id, tomb);+ return tomb.items.length;+ }++ // Recover a tombstone's contents. Must be adjacent. Ownership holds for the+ // first part of the bag's life; once inside the final grace window before+ // expiry, anyone adjacent may loot. Items flow back through _addItem so a full+ // pack leaves the remainder in the bag (no duplication, no loss). An emptied+ // bag is removed immediately.+ _handleTombLoot(client, payload) {+ const p = this.state.players.get(client.sessionId);+ if (!p || p.dead) return;+ if (!this._rateOk(client.sessionId, 'ui')) return;+ const tomb = this.state.tombstones.get(String(payload?.id ?? ''));+ if (!tomb) return;++ if (!this._adjacent(p, tomb)) {+ client.send('notice', { kind: 'tomb', text: 'Walk up to the bag to loot it.' });+ return;+ }++ const now = Date.now();+ const isOwner = tomb.owner === p.id;+ const isPublic = now > tomb.expiresAt - TOMBSTONE_GRACE_MS;+ if (!isOwner && !isPublic) {+ client.send('notice', { kind: 'tomb', text: `This bag belongs to ${tomb.ownerName || 'someone'}.` });+ return;+ }++ // Pull each slot back into the pack; whatever doesn't fit stays in the bag.+ let taken = 0;+ for (const s of tomb.items) {+ if (!s.item || s.qty <= 0) continue;+ const before = s.qty;+ const leftover = this._addItem(p, s.item, s.qty);+ taken += before - leftover;+ s.qty = leftover;+ if (leftover === 0) s.item = '';+ }++ // Compact emptied slots; remove the bag entirely once nothing remains.+ for (let i = tomb.items.length - 1; i >= 0; i--) {+ if (!tomb.items[i].item) tomb.items.splice(i, 1);+ }+ if (tomb.items.length === 0) {+ this.state.tombstones.delete(tomb.id);+ client.send('notice', { kind: 'tomb', text: isOwner ? 'Recovered your belongings.' : 'Looted the bag.' });+ } else if (taken > 0) {+ client.send('notice', { kind: 'full', text: 'Pack full — some items remain in the bag.' });+ } else {+ client.send('notice', { kind: 'full', text: 'Your pack is full.' });}p.tsServer = now;}+ _clientFor(sessionId) {+ return this.clients?.find?.((c) => c.sessionId === sessionId) || null;+ }++ // ----- quests: tutorial + dailies --------------------------------------++ // Talk to a fixed NPC. Validates the player stands adjacent to it, advances a+ // tutorial 'talk' step if that's what's next, and replies with a fresh quest+ // snapshot (the guide's current line travels in it) flagged so the client+ // opens the dialog.+ _handleNpcTalk(client, payload) {+ const p = this.state.players.get(client.sessionId);+ if (!p || p.dead) return;+ if (!this._rateOk(client.sessionId, 'ui')) return;+ const npc = (this.realm.npcs || []).find((n) => n.id === String(payload?.id ?? ''));+ if (!npc) return;+ if (!this._adjacent(p, npc)) {+ client.send('notice', { kind: 'npc', text: `Walk up to ${npc.name} to talk.` });+ return;+ }+ // A talk only advances the tutorial when the next step IS a talk step;+ // otherwise it just opens the dialog (the snapshot already carries the line).+ this._questProgress(client, { kind: 'talk', n: 1 });+ this._sendQuests(client, { npc: npc.id });+ }++ // Drive all quest progress from a real, server-validated action. `ev` is+ // { kind, item?, n }. Advances the current tutorial step when it matches, and+ // every matching un-claimed daily. Persists + re-sends the snapshot on change.+ // Progress NEVER originates from a client claim — only from these hooks.+ _questProgress(client, ev) {+ const priv = this.priv.get(client.sessionId);+ const p = this.state.players.get(client.sessionId);+ if (!priv || !p || !priv.quests) return;+ const now = Date.now();+ const qs = normalizeQuestState(priv.quests, priv.playerId, now);+ const n = Math.max(1, ev.n | 0 || 1);+ let changed = false;++ // --- tutorial: only the current step, only if its kind (and item) match ---+ const step = currentStep(qs);+ if (step && step.kind === ev.kind && (step.item ? step.item === ev.item : true)) {+ qs.tutorial.progress = Math.min(step.count, qs.tutorial.progress + n);+ changed = true;+ if (qs.tutorial.progress >= step.count) {+ qs.tutorial.step += 1;+ qs.tutorial.progress = 0;+ if (qs.tutorial.step >= TUTORIAL_STEPS.length) {+ qs.tutorial.done = true;+ this._grantQuestReward(client, p, qs, TUTORIAL_REWARD, 'Training complete');+ } else {+ const next = TUTORIAL_STEPS[qs.tutorial.step];+ client.send('notice', { kind: 'quest', text: `Next: ${next.title}.` });+ }+ }+ }++ // --- dailies: every matching un-claimed quest advances together ---+ if (ev.kind === 'gather' || ev.kind === 'combat') {+ for (const q of qs.daily.quests) {+ if (q.claimed) continue;+ const def = dailyDef(q.id);+ if (!def || def.type !== ev.kind) continue;+ if (def.type === 'gather' && def.item !== ev.item) continue;+ const before = q.progress;+ q.progress = Math.min(def.count, q.progress + n);+ if (q.progress !== before) {+ changed = true;+ if (before < def.count && q.progress >= def.count) {+ client.send('notice', { kind: 'quest', text: `Daily ready: ${def.title} — turn it in for your reward.` });+ }+ }+ }+ }++ if (changed) {+ p.badges = (qs.badges || []).join(',');+ this._persistPlayer(client.sessionId);+ this._sendQuests(client);+ }+ }++ // Claim a finished daily. Server-authoritative: refuses unless the TRACKED+ // progress meets the target and it isn't already claimed — a forged turn-in+ // for an unfinished quest does nothing. Awards 'devoted' once the whole board+ // is cleared for the day.+ _handleTurnIn(client, payload) {+ const p = this.state.players.get(client.sessionId);+ const priv = this.priv.get(client.sessionId);+ if (!p || !priv || !priv.quests) return;+ if (!this._rateOk(client.sessionId, 'ui')) return;+ const qs = normalizeQuestState(priv.quests, priv.playerId, Date.now());+ const q = qs.daily.quests.find((x) => x.id === String(payload?.id ?? ''));+ const def = q && dailyDef(q.id);+ if (!q || !def) return;+ if (q.claimed) { this._sendQuests(client); return; }+ if (q.progress < def.count) {+ client.send('notice', { kind: 'quest', text: `${def.title} isn't finished yet.` });+ return;+ }+ q.claimed = true;+ this._grantQuestReward(client, p, qs, def.reward, def.title);+ if (qs.daily.quests.every((x) => x.claimed)) this._awardBadge(client, p, qs, 'devoted');+ p.badges = (qs.badges || []).join(',');+ this._persistPlayer(client.sessionId);+ this._sendQuests(client);+ }++ // Apply a reward bundle (gold / XP / item / badge) and announce it. An item+ // reward that doesn't fit the pack spills into the bank so a reward is never+ // silently lost.+ _grantQuestReward(client, p, qs, reward, label) {+ if (!reward) return;+ const bits = [];+ if (reward.gold) { p.gold = Math.min(0xffffffff, p.gold + reward.gold); bits.push(`+${reward.gold}g`); }+ if (reward.xp) {+ for (const [skill, amt] of Object.entries(reward.xp)) {+ this._grantXp(client, p, skill, amt);+ bits.push(`+${amt} ${skill} xp`);+ }+ }+ if (reward.item) {+ const left = this._addItem(p, reward.item.id, reward.item.qty);+ if (left > 0) this._bankAdd(this.priv.get(client.sessionId).bank, reward.item.id, left);+ bits.push(`+${reward.item.qty} ${reward.item.id}`);+ }+ if (reward.badge) this._awardBadge(client, p, qs, reward.badge);+ if (bits.length) client.send('notice', { kind: 'reward', text: `${label}: ${bits.join(', ')}.` });+ }++ _awardBadge(client, p, qs, id) {+ if (!BADGES[id] || qs.badges.includes(id)) return;+ qs.badges.push(id);+ p.badges = qs.badges.join(',');+ client.send('notice', { kind: 'badge', text: `Badge earned: ${BADGES[id].icon} ${BADGES[id].label}.` });+ }++ // Send the requesting player their full quest snapshot: tutorial step (or+ // done), today's dailies with live progress + reward previews, the next-reset+ // timestamp for a real countdown, earned badges, and the guide's current line.+ // `opts.npc` set => the client opens the NPC dialog on this snapshot.+ _sendQuests(client, opts = {}) {+ const p = this.state.players.get(client.sessionId);+ const priv = this.priv.get(client.sessionId);+ if (!p || !priv || !priv.quests) return;+ const now = Date.now();+ const qs = normalizeQuestState(priv.quests, priv.playerId, now);+ const badgeStr = (qs.badges || []).join(',');+ if (p.badges !== badgeStr) p.badges = badgeStr; // keep the synced field honest++ const step = currentStep(qs);+ const tutorial = qs.tutorial.done+ ? { done: true, total: TUTORIAL_STEPS.length }+ : {+ done: false,+ stepIndex: qs.tutorial.step,+ total: TUTORIAL_STEPS.length,+ progress: qs.tutorial.progress,+ step: step && {+ id: step.id, kind: step.kind, count: step.count, item: step.item || '',+ slot: typeof step.slot === 'number' ? step.slot : -1, title: step.title, desc: step.desc,+ },+ };++ const daily = {+ date: qs.daily.date,+ resetAt: nextResetAt(now),+ quests: qs.daily.quests.map((q) => {+ const def = dailyDef(q.id) || {};+ return {+ id: q.id, type: def.type, item: def.item || '', count: def.count || 0,+ title: def.title || q.id, desc: def.desc || '',+ progress: Math.min(q.progress, def.count || q.progress), claimed: !!q.claimed,+ reward: this._rewardPreview(def.reward),+ };+ }),+ };++ const badges = (qs.badges || []).map((id) => BADGES[id]).filter(Boolean);+ const guide = qs.tutorial.done ? GUIDE_DONE : (step?.guide || '');++ client.send('quests', { tutorial, daily, badges, guide, npc: opts.npc || '' });+ }++ // Compact, client-renderable reward summary (no server-only detail).+ _rewardPreview(reward) {+ if (!reward) return {};+ const out = {};+ if (reward.gold) out.gold = reward.gold;+ if (reward.xp) out.xp = reward.xp;+ if (reward.item) out.item = { id: reward.item.id, qty: reward.item.qty };+ if (reward.badge && BADGES[reward.badge]) {+ out.badge = { id: reward.badge, icon: BADGES[reward.badge].icon, label: BADGES[reward.badge].label };+ }+ return out;+ }++ // Persist the player's quest state through the Task 16 save interface, keyed+ // by the stable account id. Read-merge-write so we only ever own the quest+ // slice and never clobber other persisted fields.+ _persistPlayer(sessionId) {+ const priv = this.priv.get(sessionId);+ if (!priv || !priv.playerId || !priv.quests) return;+ const prev = loadPlayer(priv.playerId) || {};+ savePlayer(priv.playerId, { ...prev, quests: priv.quests });+ }+// ----- inventory / hotbar ----------------------------------------------_handleInvMove(client, payload) {@@ -361,7 +1246,7 @@ export class GameRoom extends Room {if (!p) return;if (!this._rateOk(client.sessionId, 'ui')) return;// Must be standing on a bank-counter tile.- if (!MAINLAND.bankZone.some((t) => t.tx === p.tx && t.ty === p.ty)) {+ if (!this.realm.bankZone.some((t) => t.tx === p.tx && t.ty === p.ty)) {client.send('notice', { kind: 'bank', text: 'Stand at the bank counter to use storage.' });return;}@@ -378,6 +1263,8 @@ export class GameRoom extends Room {const deposited = move - left;slot.qty -= deposited;if (slot.qty === 0) slot.item = '';+ // Tutorial: stashing an item teaches the bank. Only count a real deposit.+ if (deposited > 0) this._questProgress(client, { kind: 'bank', n: 1 });} else {if (i < 0 || i >= BANK_SIZE) return;const bslot = priv.bank[i];@@ -461,12 +1348,61 @@ export class GameRoom extends Room {return left;}- _grantXp(sessionId, p, skill, amount) {- const priv = this.priv.get(sessionId);+ _grantXp(client, p, skill, amount) {+ const priv = this.priv.get(client.sessionId);if (!priv) return;priv.xp[skill] = (priv.xp[skill] || 0) + amount;const lvl = levelForXp(priv.xp[skill]);- if (lvl !== p[skill]) p[skill] = lvl;+ // XP only accumulates, so a changed level is always a level-up. Broadcast+ // only the integer level on the schema; tell the earner privately so its+ // UI can both refresh the XP bar (via a 'skills' fetch) and celebrate.+ if (lvl > p[skill]) {+ p[skill] = lvl;+ client.send('levelup', { skill, level: lvl });+ }+ }++ // Reply to a 'skills' request with the requesting player's own XP detail: per+ // skill, the level plus the cumulative XP boundaries of the current level so+ // the client can draw an exact progress bar. Raw XP is never broadcast to+ // peers — it only ever travels back to its owner here.+ _sendSkills(client) {+ const p = this.state.players.get(client.sessionId);+ const priv = this.priv.get(client.sessionId);+ if (!p || !priv) return;+ const skills = {};+ for (const skill of SKILLS) {+ const level = p[skill];+ const xp = priv.xp[skill] || 0;+ const floorXp = xpForLevel(level);+ const maxed = level >= LEVEL_CAP;+ skills[skill] = {+ level,+ xp,+ levelXp: floorXp, // cumulative XP at the start of the current level+ nextXp: maxed ? null : xpForLevel(level + 1), // cumulative XP for next level+ };+ }+ client.send('skills', {+ cap: LEVEL_CAP,+ skills,+ total: this._totalLevel(p),+ average: this._averageLevel(p),+ });+ }++ // Authoritative average skill level — the mean of all five skill levels.+ // Returned precisely (a float) so callers choose their own rounding: a gate+ // can floor it (e.g. `Math.floor(avg) >= 20`) while the UI shows one decimal.+ // Reused by Task 19's spin gate and any future average-level content gate.+ _averageLevel(p) {+ return this._totalLevel(p) / SKILLS.length;+ }++ _totalLevel(p) {+ let sum = 0;+ for (const s of SKILLS) sum += p[s];+ return sum;}_adjacent(p, obj) {@@ -507,20 +1443,28 @@ export class GameRoom extends Room {}}- // Player healing + respawn.+ // Expire crumbled death-bags.+ for (const [id, t] of this.state.tombstones) {+ if (now >= t.expiresAt) this.state.tombstones.delete(id);+ }++ // Player healing + respawn — both keyed to THIS realm's spawn/fountain.+ const fountain = this.realm.fountain;for (const [, p] of this.state.players) {if (p.dead) {if (now >= p.respawnAt) {p.dead = false;p.hp = p.maxHp;- p.tx = MAINLAND.spawn.tx;- p.ty = MAINLAND.spawn.ty;+ p.motion = 'idle';+ p.tx = this.realm.spawn.tx;+ p.ty = this.realm.spawn.ty;+ p.tsServer = now;}continue;}if (p.hp < p.maxHp) {const nearFountain =- Math.abs(p.tx - MAINLAND.fountain.tx) <= 3 && Math.abs(p.ty - MAINLAND.fountain.ty) <= 3;+ !!fountain && Math.abs(p.tx - fountain.tx) <= 3 && Math.abs(p.ty - fountain.ty) <= 3;p.hp = Math.min(p.maxHp, p.hp + (nearFountain ? FOUNTAIN_HEAL_PER_TICK : REGEN_PER_TICK));}}diff --git a/multiplayer/src/rooms/commands.js b/multiplayer/src/rooms/commands.jsnew file mode 100644index 000000000..d55db2b3c--- /dev/null+++ b/multiplayer/src/rooms/commands.js@@ -0,0 +1,160 @@+// Chat slash-command registry + router (Task 13).+//+// Single source of truth for the documented player commands. GameRoom._handleChat+// forwards any chat line that begins with '/' to runCommand(), which parses the+// command + args, resolves the name (or an alias), validates it exists, and+// dispatches to its handler — returning a result the caller sees as a system+// message. Unknown commands return a helpful error with a "did you mean" hint.+//+// /help is GENERATED from this registry, so it can never drift from the real+// command set. /who reads the live realm roster (state.players). The stateful+// actions (pickup/lock/unlock/dismount) live on the GameRoom because they mutate+// synced state; the registry invokes them through ctx.room so the room stays the+// single authority over mutation.+//+// ctx = { room, client, player }+// handler(ctx, args) -> { text, kind } | string | null+// null → the handler already sent its own reply (e.g. /dismount's notice);+// the router sends nothing further.+// kind → styles the client bubble: 'info' (default) | 'error' | 'help' | 'who'.++export const COMMANDS = [+ {+ name: 'help',+ aliases: ['commands', 'h', '?'],+ args: '',+ desc: 'List the commands you can use',+ run: () => ({ text: formatHelp(), kind: 'help' }),+ },+ {+ name: 'who',+ aliases: ['players', 'online'],+ args: '',+ desc: 'List the players in your realm',+ run: (ctx) => ({ text: formatWho(ctx), kind: 'who' }),+ },+ {+ name: 'pickup',+ aliases: ['take'],+ args: '',+ desc: 'Pick up your firepit or shack you are standing beside',+ run: (ctx) => ctx.room.pickupStructure(ctx.player),+ },+ {+ name: 'lock',+ aliases: [],+ args: '',+ desc: 'Lock the structure beside you against stray clicks',+ run: (ctx) => ctx.room.setStructureLock(ctx.player, true),+ },+ {+ name: 'unlock',+ aliases: [],+ args: '',+ desc: 'Unlock the structure beside you',+ run: (ctx) => ctx.room.setStructureLock(ctx.player, false),+ },+ {+ name: 'dismount',+ aliases: ['unmount'],+ args: '',+ desc: 'Climb down from your mount',+ // Reuse the room's dismount action (shared with the dismount button); it+ // sends its own notice, so the router adds no second reply.+ run: (ctx) => { ctx.room._handleDismount(ctx.client); return null; },+ },+];++// Resolve a name or alias (case-insensitive) to its command, or null.+function resolve(name) {+ const n = String(name || '').toLowerCase();+ return COMMANDS.find((c) => c.name === n || c.aliases.includes(n)) || null;+}++// Nearest command for a "did you mean" hint on a typo. Small registry, so a plain+// Levenshtein over the names is more than fast enough.+function suggest(name) {+ const n = String(name || '').toLowerCase();+ let best = null, bestD = Infinity;+ for (const c of COMMANDS) {+ const d = editDistance(n, c.name);+ if (d < bestD) { bestD = d; best = c.name; }+ }+ return best && bestD <= Math.max(2, Math.ceil(best.length / 2)) ? best : null;+}++function editDistance(a, b) {+ const m = a.length, n = b.length;+ const row = Array.from({ length: n + 1 }, (_, i) => i);+ for (let i = 1; i <= m; i++) {+ let prev = row[0];+ row[0] = i;+ for (let j = 1; j <= n; j++) {+ const tmp = row[j];+ row[j] = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));+ prev = tmp;+ }+ }+ return row[n];+}++// Build /help from the registry so it always matches the real command set. Names+// are padded to a common width so the descriptions line up as a scannable column.+function formatHelp() {+ const width = COMMANDS.reduce((w, c) => Math.max(w, c.name.length + (c.args ? c.args.length + 1 : 0)), 0);+ const lines = COMMANDS.map((c) => {+ const sig = '/' + c.name + (c.args ? ' ' + c.args : '');+ return ' ' + sig.padEnd(width + 1) + ' ' + c.desc;+ });+ return 'Commands\n' + lines.join('\n');+}++// /who — real realm occupancy. Each GameRoom is a single realm, so state.players+// IS the realm roster. The caller is marked and the list is sorted for stability.+function formatWho(ctx) {+ const realm = cap(ctx.room.state.realm || 'realm');+ const rows = [];+ for (const [id, p] of ctx.room.state.players) {+ rows.push({ name: p.name || 'guest', me: id === ctx.client.sessionId });+ }+ rows.sort((a, b) => (a.me === b.me ? a.name.localeCompare(b.name) : a.me ? -1 : 1));+ const n = rows.length;+ const head = `${n} ${n === 1 ? 'player' : 'players'} in ${realm}`;+ const list = rows.map((r) => ' • ' + r.name + (r.me ? ' (you)' : '')).join('\n');+ return head + (list ? '\n' + list : '');+}++function cap(s) {+ return String(s || '').replace(/^\w/, (m) => m.toUpperCase());+}++// Parse + dispatch a raw chat line beginning with '/'. The room has already+// rate-limited and looked up the player. Returns { text, kind } for the caller to+// ship as a system message, or null when the handler already replied itself.+export function runCommand(ctx, raw) {+ const without = String(raw || '').trim().replace(/^\//, '');+ const parts = without.split(/\s+/).filter(Boolean);+ const name = (parts.shift() || '').toLowerCase();++ if (!name) return { text: 'Type a command after the slash — try /help.', kind: 'error' };++ const cmd = resolve(name);+ if (!cmd) {+ const hint = suggest(name);+ return {+ text: `Unknown command /${name}.` + (hint ? ` Did you mean /${hint}?` : '') + ' Type /help for the list.',+ kind: 'error',+ };+ }++ let result;+ try {+ result = cmd.run(ctx, parts);+ } catch (err) {+ console.error(`[commands] /${cmd.name} threw:`, err);+ return { text: `Something went wrong running /${cmd.name}.`, kind: 'error' };+ }+ if (result == null) return null; // handler replied itself+ if (typeof result === 'string') return { text: result, kind: 'info' };+ return { text: String(result.text ?? ''), kind: result.kind || 'info' };+}diff --git a/multiplayer/src/rooms/realm-transfer.js b/multiplayer/src/rooms/realm-transfer.jsnew file mode 100644index 000000000..c39cddc53--- /dev/null+++ b/multiplayer/src/rooms/realm-transfer.js@@ -0,0 +1,108 @@+// Realm-transfer tokens — the trust boundary for portal traversal.+//+// When a player steps onto a portal, the source GameRoom snapshots their full+// state (inventory, hotbar, bank, gold, skills, hp, cosmetic) and reserves a+// seat in the destination realm room. The snapshot can't ride along as plain+// join options: a client could call client.joinOrCreate('game', { realm, carry })+// directly and mint gold or items out of thin air. So we seal the snapshot into+// an HMAC-SHA256 token here — identical construction to holder-pass.js — and the+// destination room refuses any carry that isn't signed with the shared secret.+//+// The token is short-lived (TTL below): a transfer is consumed within a couple+// of network round-trips, so a long window only widens the replay surface (e.g.+// banking a token at high gold, spending, then replaying to restore it).++import crypto from 'node:crypto';++const DEV_SECRET = 'three-ws-realm-transfer-dev-secret';+const TTL_SECONDS = 60; // a transfer is consumed in milliseconds; 60s covers any reconnect hiccup++let _warned = false;+function secret() {+ // Prefer a dedicated secret, but fall back to the holder-pass secret so a+ // single env var secures both gates in the common single-secret deployment.+ const s = process.env.REALM_TRANSFER_SECRET || process.env.HOLDER_PASS_SECRET;+ if (s) return s;+ if (process.env.NODE_ENV === 'production') {+ throw new Error(+ '[realm-transfer] REALM_TRANSFER_SECRET (or HOLDER_PASS_SECRET) is required in production — ' ++ 'refusing to sign transfers with the dev secret.',+ );+ }+ if (!_warned) {+ _warned = true;+ console.warn(+ '[realm-transfer] no REALM_TRANSFER_SECRET/HOLDER_PASS_SECRET set — using the insecure dev secret. ' ++ 'Set one in production or portal carries can be forged.',+ );+ }+ return DEV_SECRET;+}++function b64url(buf) {+ return Buffer.from(buf).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');+}+function b64urlDecode(str) {+ return Buffer.from(str.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8');+}+function hmac(body) {+ return b64url(crypto.createHmac('sha256', secret()).update(body).digest());+}+function safeEqual(a, b) {+ const ba = Buffer.from(a);+ const bb = Buffer.from(b);+ if (ba.length !== bb.length) return false;+ return crypto.timingSafeEqual(ba, bb);+}++/**+ * Seal a portal transfer into a signed token.+ * @param {{ to: string, tx: number, ty: number, carry: object }} payload+ * @returns {string} `${base64url(body)}.${signature}`+ */+export function signTransfer(payload) {+ const now = Math.floor(Date.now() / 1000);+ const body = b64url(+ JSON.stringify({+ to: payload.to,+ tx: payload.tx,+ ty: payload.ty,+ carry: payload.carry,+ iat: now,+ exp: now + TTL_SECONDS,+ }),+ );+ return `${body}.${hmac(body)}`;+}++/**+ * Verify a transfer token and return its payload, or null if missing, malformed,+ * tampered with, or expired.+ * @param {unknown} token+ * @returns {{ to: string, tx: number, ty: number, carry: object, iat: number, exp: number } | null}+ */+export function verifyTransfer(token) {+ if (typeof token !== 'string' || token.length < 16 || token.length > 65536) return null;+ const dot = token.indexOf('.');+ if (dot <= 0) return null;+ const body = token.slice(0, dot);+ const sig = token.slice(dot + 1);+ if (!safeEqual(sig, hmac(body))) return null;++ let payload;+ try {+ payload = JSON.parse(b64urlDecode(body));+ } catch {+ return null;+ }+ if (!payload || typeof payload !== 'object') return null;+ if (typeof payload.to !== 'string' || !payload.to) return null;+ if (!Number.isFinite(payload.tx) || !Number.isFinite(payload.ty)) return null;+ if (!payload.carry || typeof payload.carry !== 'object') return null;++ const now = Date.now() / 1000;+ if (typeof payload.exp !== 'number' || payload.exp < now) return null;+ if (typeof payload.iat !== 'number' || payload.iat > now + 60) return null;+ if (payload.exp - payload.iat > TTL_SECONDS + 5) return null;+ return payload;+}diff --git a/multiplayer/src/rooms/realms.js b/multiplayer/src/rooms/realms.jsindex 6b7644c20..fe4334d33 100644--- a/multiplayer/src/rooms/realms.js+++ b/multiplayer/src/rooms/realms.js@@ -4,10 +4,19 @@//// Every realm shares one shape:// { name, grid, spawn:{tx,ty}, safe:bool, pvp:bool, danger:bool,-// blocked:[{x0,y0,x1,y1}], bankZone:[{tx,ty}], fountain:{tx,ty}|null,-// nodes:[{id,kind,tx,ty}], mobs:[{id,kind,tx,ty,hp,roam,aggro}],-// fishing:[{tx,ty}], cooking:[{tx,ty}], safeCamp:{x0,y0,x1,y1}|null,-// portals:[{x0,y0,x1,y1,to,toTx,toTy}] }+// blocked:[{x0,y0,x1,y1}], water:[{x0,y0,x1,y1}], bankZone:[{tx,ty}],+// fountain:{tx,ty}|null, nodes:[{id,kind,tx,ty}],+// mobs:[{id,kind,tx,ty,hp,roam,aggro}], fishing:[{tx,ty,quality}],+// cooking:[{tx,ty}], safeCamp:{x0,y0,x1,y1}|null,+// structures:['firepit'|'shack'], portals:[{x0,y0,x1,y1,to,toTx,toTy}] }+//+// `structures` lists which player-built structure kinds this realm permits. A+// firepit (temporary healing) is allowed wherever building makes sense; the+// shack (permanent landmark) is Whisperwood-only by design.+//+// `water` rects are a visual subset of `blocked` (non-walkable, rendered as+// water on the client). `fishing` tiles are walkable shore spots beside water,+// each carrying a `quality` multiplier that scales catch rate + yield.//// `danger` realms drop a tombstone on death. `pvp` realms allow player combat// outside any safeCamp. Resource node ids must be unique WITHIN a realm.@@ -18,6 +27,11 @@ function nodesFrom(coords, kind, prefix) {function tiles(coords) {return coords.map(([tx, ty]) => ({ tx, ty }));}+// Fishing shore spots with a per-tile catch-quality multiplier (1 = average).+// Higher quality = better catch rate and a higher chance of a double haul.+function fishSpots(coords, quality = 1) {+ return coords.map(([tx, ty]) => ({ tx, ty, quality }));+}// ---------------------------------------------------------------- Mainlandconst MAINLAND = {@@ -28,9 +42,19 @@ const MAINLAND = {blocked: [{ x0: 8, y0: 8, x1: 12, y1: 11 }, // bank building{ x0: 23, y0: 23, x1: 24, y1: 24 }, // fountain+ { x0: 31, y0: 38, x1: 34, y1: 41 }, // the millpond (water — also in `water` below)+ ],+ water: [+ { x0: 31, y0: 38, x1: 34, y1: 41 }, // the millpond, fishable from its banks],fountain: { tx: 23, ty: 23 },bankZone: tiles([[8, 12], [9, 12], [10, 12], [11, 12], [12, 12]]),+ // Fixed, interactable characters. Aldric the Guide stands just off the spawn+ // and drives the tutorial + daily-quest turn-ins. NPCs occupy their tile+ // (players stand adjacent to talk), validated like resource nodes.+ npcs: [+ { id: 'aldric', name: 'Aldric the Guide', kind: 'guide', tx: 26, ty: 29 },+ ],nodes: [...nodesFrom([[12, 28], [14, 30], [16, 29], [13, 33], [15, 35], [11, 31], [18, 34], [20, 30],[17, 37], [19, 38], [10, 36], [22, 36], [8, 30], [9, 33], [21, 40], [13, 40]], 'tree', 't'),@@ -41,14 +65,34 @@ const MAINLAND = {{ id: 'd0', kind: 'dummy', tx: 36, ty: 34, hp: 50, roam: false, aggro: false },{ id: 'd1', kind: 'dummy', tx: 38, ty: 34, hp: 50, roam: false, aggro: false },{ id: 'd2', kind: 'dummy', tx: 37, ty: 36, hp: 50, roam: false, aggro: false },+ // Loot mobs (Task 09): a docile monster glade in the SE so mounts are+ // obtainable on the hub today. roam/aggro stay false — even once mob AI+ // (Task 03) lands, these stand their ground and never harass the safe town.+ { id: 'gm0', kind: 'goblin', tx: 41, ty: 32, hp: 34, roam: false, aggro: false },+ { id: 'gm1', kind: 'goblin', tx: 44, ty: 34, hp: 34, roam: false, aggro: false },+ { id: 'gm2', kind: 'goblin', tx: 42, ty: 38, hp: 34, roam: false, aggro: false },+ { id: 'om0', kind: 'ogre', tx: 44, ty: 39, hp: 80, roam: false, aggro: false },],- fishing: [],+ // Millpond banks — a calm starter spot (average quality) so a fresh player can+ // learn the cast on the Mainland before the richer realms open up.+ fishing: fishSpots([+ [30, 38], [30, 39], [30, 40], [30, 41], // west bank+ [35, 38], [35, 39], [35, 40], [35, 41], // east bank+ [31, 37], [32, 37], [33, 37], [34, 37], // north bank+ [31, 42], [32, 42], [33, 42], [34, 42], // south bank+ ], 1.0),cooking: [],safeCamp: null,+ structures: ['firepit'],portals: [{ x0: 23, y0: 0, x1: 25, y1: 0, to: 'wilderness', toTx: 20, toTy: 36 }, // north → wilderness safe camp{ x0: 23, y0: 47, x1: 25, y1: 47, to: 'whisperwood', toTx: 20, toTy: 2 }, // south → whisperwood{ x0: 47, y0: 23, x1: 47, y1: 25, to: 'pond', toTx: 2, toTy: 18 }, // east → pond+ // Mine entrance — a cave mouth cut into the rocky NE hills, just north of+ // the surface ore field. Steps down into the enclosed `mine` interior; the+ // mine's return portal lands the player back at (43,11), a tile clear of+ // this rect so they don't immediately bounce back in.+ { x0: 43, y0: 9, x1: 44, y1: 9, to: 'mine', toTx: 16, toTy: 28 }, // NE → mine interior],};@@ -59,6 +103,7 @@ const WILDERNESS = {spawn: { tx: 20, ty: 36 },safe: false, pvp: true, danger: true,blocked: [],+ water: [],fountain: null,bankZone: [],nodes: [@@ -77,6 +122,7 @@ const WILDERNESS = {cooking: [],// southern fenced safe camp: no PvP, mobs won't enter.safeCamp: { x0: 14, y0: 32, x1: 26, y1: 39 },+ structures: ['firepit'],portals: [{ x0: 19, y0: 39, x1: 21, y1: 39, to: 'mainland', toTx: 24, toTy: 2 }, // south → mainland],@@ -88,7 +134,16 @@ const WHISPERWOOD = {grid: 40,spawn: { tx: 20, ty: 3 },safe: true, pvp: false, danger: false,- blocked: [],+ blocked: [+ { x0: 20, y0: 18, x1: 21, y1: 18 }, // forest pool (north)+ { x0: 10, y0: 35, x1: 11, y1: 35 }, // brook (southwest)+ { x0: 30, y0: 36, x1: 31, y1: 36 }, // brook (southeast)+ ],+ water: [+ { x0: 20, y0: 18, x1: 21, y1: 18 },+ { x0: 10, y0: 35, x1: 11, y1: 35 },+ { x0: 30, y0: 36, x1: 31, y1: 36 },+ ],fountain: null,bankZone: [],nodes: [@@ -97,9 +152,11 @@ const WHISPERWOOD = {...nodesFrom([[34, 10], [6, 26], [35, 30], [7, 33]], 'rock', 'r'),],mobs: [],- fishing: tiles([[20, 17], [21, 17], [19, 19], [22, 19], [10, 34], [11, 34], [30, 35], [31, 35]]),+ // Shaded woodland pools — modest quality vs. the open pond.+ fishing: fishSpots([[20, 17], [21, 17], [19, 19], [22, 19], [10, 34], [11, 34], [30, 35], [31, 35]], 0.9),cooking: [],safeCamp: null,+ structures: ['firepit', 'shack'],portals: [{ x0: 19, y0: 0, x1: 21, y1: 0, to: 'mainland', toTx: 24, toTy: 45 }, // north → mainland],@@ -114,29 +171,95 @@ const POND = {blocked: [{ x0: 14, y0: 12, x1: 22, y1: 22 }, // the large pond (water, non-walkable)],+ water: [+ { x0: 14, y0: 12, x1: 22, y1: 22 }, // open water — the richest fishing in the world+ ],fountain: null,bankZone: [],nodes: [...nodesFrom([[6, 6], [9, 9], [27, 8], [30, 12], [7, 26], [28, 26], [11, 29], [25, 30]], 'tree', 't'),],mobs: [],- // fishable shoreline around the pond rectangle (walk adjacent and cast)- fishing: tiles([+ // fishable shoreline around the open pond — deep water, the best yields anywhere.+ fishing: fishSpots([[13, 14], [13, 16], [13, 18], [13, 20], [23, 14], [23, 16], [23, 18], [23, 20],[15, 11], [17, 11], [19, 11], [21, 11], [15, 23], [17, 23], [19, 23], [21, 23],- ]),+ ], 1.3),cooking: tiles([[10, 18], [11, 18], [10, 19], [11, 19]]), // the Roast PitsafeCamp: null,+ structures: ['firepit'],portals: [{ x0: 0, y0: 17, x1: 0, y1: 19, to: 'mainland', toTx: 45, toTy: 24 }, // west → mainland],};+// ---------------------------------------------------------------- Mine+// An enclosed cave interior reached through the Mainland mine entrance. It is a+// Mainland-side resource area, so it is `safe` (no PvP, no death-bags) — a place+// to mine in peace. There is no bank or fountain down here; you carry your haul+// back up to the Mainland bank. The edge is fully walled; thin interior ridges+// and pillars split it into an upper and a lower chamber joined by three gaps,+// giving the space a cave read without trapping any node. The mine is a markedly+// better mining spot than the surface by DENSITY: ~27 rock + ~12 coal nodes+// versus the Mainland's 8 + 4. Respawn timers stay the shared defaults+// (NODE_RULES in GameRoom), so the edge is "more to mine, less waiting" rather+// than faster individual nodes — better without trivializing progression.+const MINE = {+ name: 'mine',+ grid: 32,+ spawn: { tx: 16, ty: 28 }, // just inside the entrance, on the central corridor+ safe: true, pvp: false, danger: false,+ blocked: [+ // Cave shell — a one-tile rock wall around the whole interior, with a+ // three-tile gap at the bottom (x15..17) for the entrance/return opening.+ { x0: 0, y0: 0, x1: 31, y1: 0 }, // north wall+ { x0: 0, y0: 1, x1: 0, y1: 31 }, // west wall+ { x0: 31, y0: 1, x1: 31, y1: 31 }, // east wall+ { x0: 1, y0: 31, x1: 14, y1: 31 }, // south wall (west of the mouth)+ { x0: 18, y0: 31, x1: 30, y1: 31 }, // south wall (east of the mouth)+ // Central ridge dividing the upper and lower chambers, broken by three+ // gaps (x1..3 left, x14..17 centre, x28..30 right) so both chambers and+ // the entrance corridor stay connected.+ { x0: 4, y0: 11, x1: 13, y1: 12 },+ { x0: 18, y0: 11, x1: 27, y1: 12 },+ // Pillars in the lower chamber — cover to mine around.+ { x0: 8, y0: 19, x1: 9, y1: 21 },+ { x0: 22, y0: 19, x1: 23, y1: 21 },+ // Short stubs in the upper chamber for a rougher cave outline.+ { x0: 13, y0: 4, x1: 13, y1: 6 },+ { x0: 19, y0: 4, x1: 19, y1: 6 },+ ],+ water: [],+ fountain: null,+ bankZone: [],+ nodes: [+ // Upper chamber.+ ...nodesFrom([[3, 3], [6, 2], [9, 4], [12, 3], [15, 3], [21, 3], [24, 2], [28, 4],+ [5, 7], [10, 8], [25, 7], [29, 8]], 'rock', 'r'),+ ...nodesFrom([[7, 5], [18, 4], [27, 5], [14, 8]], 'coal', 'cu'),+ // Lower chamber.+ ...nodesFrom([[3, 14], [6, 16], [11, 14], [14, 15], [19, 14], [24, 15], [28, 16],+ [4, 24], [12, 25], [20, 24], [26, 25], [8, 27], [24, 27], [3, 29], [29, 28]], 'rock', 'rl'),+ ...nodesFrom([[5, 18], [12, 20], [18, 18], [21, 20], [27, 21], [9, 25], [17, 22], [25, 28]], 'coal', 'cl'),+ ],+ mobs: [],+ fishing: [],+ cooking: [],+ safeCamp: null,+ structures: [], // a working mine, not a campsite — no player building down here+ portals: [+ // Return to the Mainland mine entrance. Lands at (43,11), a tile clear of+ // the Mainland entrance rect (y=9) so stepping out doesn't bounce back in.+ { x0: 15, y0: 31, x1: 17, y1: 31, to: 'mainland', toTx: 43, toTy: 11 },+ ],+};+export const REALMS = {mainland: MAINLAND,wilderness: WILDERNESS,whisperwood: WHISPERWOOD,pond: POND,+ mine: MINE,};export const DEFAULT_REALM = 'mainland';@@ -163,6 +286,19 @@ export function inRect(rect, tx, ty) {return rect && tx >= rect.x0 && tx <= rect.x1 && ty >= rect.y0 && ty <= rect.y1;}+// The best fishing spot within one tile (8-way, including the player's own tile)+// of (tx,ty), or null if there's no fishable water in reach. "Best" = highest+// quality, so standing where two spots overlap rewards the richer water.+export function fishingSpotNear(realm, tx, ty) {+ let best = null;+ for (const f of realm.fishing) {+ if (Math.abs(f.tx - tx) <= 1 && Math.abs(f.ty - ty) <= 1) {+ if (!best || (f.quality || 1) > (best.quality || 1)) best = f;+ }+ }+ return best;+}+// Serializable layout sent to the client on join (static geometry only;// dynamic objects sync via schema state).export function realmLayout(realm) {@@ -172,10 +308,13 @@ export function realmLayout(realm) {spawn: realm.spawn,fountain: realm.fountain,blocked: realm.blocked,+ water: realm.water || [],bankZone: realm.bankZone,fishing: realm.fishing,cooking: realm.cooking,safeCamp: realm.safeCamp,+ npcs: (realm.npcs || []).map((n) => ({ id: n.id, name: n.name, kind: n.kind, tx: n.tx, ty: n.ty })),+ structures: realm.structures || [],portals: realm.portals.map((p) => ({ x0: p.x0, y0: p.y0, x1: p.x1, y1: p.y1, to: p.to })),safe: realm.safe,pvp: realm.pvp,diff --git a/multiplayer/src/schemas/game.js b/multiplayer/src/schemas/game.jsindex e45da0e23..8b3163671 100644--- a/multiplayer/src/schemas/game.js+++ b/multiplayer/src/schemas/game.js@@ -58,6 +58,10 @@ export class GamePlayer extends Schema {this.fishing = 1;this.cooking = 1;this.cosmetic = ''; // equipped cosmetic id ('' = default)+ // Quest-awarded badges, as a comma-separated list of badge ids. Synced so+ // every peer renders the achievement on the player's nameplate (the+ // in-world "profile"). Server-authoritative — only the quest engine writes it.+ this.badges = '';// 24-slot backpack + 6 hotbar slots. Fixed length so indices are stable// references the client can drag between.@@ -65,6 +69,12 @@ export class GamePlayer extends Schema {this.hotbar = new ArraySchema();this.activeSlot = -1; // index into hotbar; -1 = nothing equipped+ // Mount state. `mounted` flips locomotion to the faster cadence the server+ // enforces; `mount` is the registry id of the steed being ridden ('' = on+ // foot) so peers render the right creature underneath the avatar.+ this.mounted = false;+ this.mount = '';+this.tsServer = 0;}}@@ -87,9 +97,12 @@ defineTypes(GamePlayer, {fishing: 'uint16',cooking: 'uint16',cosmetic: 'string',+ badges: 'string',inv: [Slot],hotbar: [Slot],activeSlot: 'int8',+ mounted: 'boolean',+ mount: 'string',tsServer: 'float64',});@@ -173,6 +186,35 @@ defineTypes(Tombstone, {expiresAt: 'float64',});+// A player-placed structure occupying a single tile. `firepit` heals players who+// stand adjacent (like the fountain) and decays at `expiresAt`; `shack` is a+// permanent landmark (`expiresAt === 0`) until its owner picks it up. `locked`+// makes a structure ignore stray pickup/interaction clicks. Like the fountain,+// a structure's tile is solid — players cannot walk onto it.+export class Structure extends Schema {+ constructor() {+ super();+ this.id = '';+ this.kind = 'firepit'; // 'firepit' | 'shack'+ this.owner = ''; // session id of the placer+ this.ownerName = '';+ this.tx = 0;+ this.ty = 0;+ this.expiresAt = 0; // epoch ms it decays; 0 = permanent+ this.locked = false;+ }+}+defineTypes(Structure, {+ id: 'string',+ kind: 'string',+ owner: 'string',+ ownerName: 'string',+ tx: 'int16',+ ty: 'int16',+ expiresAt: 'float64',+ locked: 'boolean',+});+// ---------------------------------------------------------------------------// Root state// ---------------------------------------------------------------------------@@ -185,6 +227,7 @@ export class GameState extends Schema {this.nodes = new MapSchema();this.mobs = new MapSchema();this.tombstones = new MapSchema();+ this.structures = new MapSchema();}}defineTypes(GameState, {@@ -193,4 +236,5 @@ defineTypes(GameState, {nodes: { map: ResourceNode },mobs: { map: Mob },tombstones: { map: Tombstone },+ structures: { map: Structure },});diff --git a/pages/game.html b/pages/game.htmlindex b39bf4d21..25287957d 100644--- a/pages/game.html+++ b/pages/game.html@@ -19,14 +19,20 @@(see defaultServerUrl in src/game/game-net.js), so`npm run dev:walk-all` works out of the box.-->- <meta name="game-server" content="wss://three-ws-multiplayer-93741856042.us-central1.run.app" />+ <meta+ name="game-server"+ content="wss://three-ws-multiplayer-93741856042.us-central1.run.app"+ /><link rel="shortcut icon" href="/favicon.ico" /><meta property="og:type" content="website" /><meta property="og:site_name" content="three.ws" /><meta property="og:title" content="Adventure · three.ws" />- <meta property="og:description" content="An isometric MMO on three.ws — gather, fight, level up, and explore a shared world." />+ <meta+ property="og:description"+ content="An isometric MMO on three.ws — gather, fight, level up, and explore a shared world."+ /><meta property="og:url" content="https://three.ws/game" /><link rel="stylesheet" href="/src/game/iso-game.css" />@@ -41,14 +47,195 @@<header id="kg-topbar" hidden><span id="kg-realm">Mainland</span><span class="kg-stat">online <b id="kg-online">0</b></span>+ <button+ id="kg-skills-btn"+ class="kg-hud-btn"+ type="button"+ aria-haspopup="dialog"+ aria-expanded="false"+ aria-controls="kg-skills"+ title="Skills (K)"+ >+ <svg class="kg-hud-ico" viewBox="0 0 24 24" aria-hidden="true">+ <path d="M4 19V9m5 10V5m5 14v-7m5 7V11" />+ </svg>+ <span>Skills</span>+ </button><span id="kg-status" data-status="connecting">connecting</span></header>+ <!-- Skills panel — per-skill level, XP-to-next, and the cap. Populated live+ from the server's 'skills' reply; updates on every 'levelup'. -->+ <aside+ id="kg-skills"+ class="kg-skills"+ hidden+ role="dialog"+ aria-label="Skills"+ aria-modal="false"+ >+ <header class="kg-skills-head">+ <h2 class="kg-skills-title">Skills</h2>+ <button+ id="kg-skills-close"+ class="kg-skills-close"+ type="button"+ aria-label="Close skills"+ >+ <svg viewBox="0 0 24 24" aria-hidden="true">+ <path d="M6 6l12 12M18 6L6 18" />+ </svg>+ </button>+ </header>+ <div class="kg-skills-summary">+ <div class="kg-skills-sum">+ <span class="kg-skills-sum-val" id="kg-skills-total">—</span>+ <span class="kg-skills-sum-lbl">Total level</span>+ </div>+ <div class="kg-skills-sum">+ <span class="kg-skills-sum-val" id="kg-skills-avg">—</span>+ <span class="kg-skills-sum-lbl">Average</span>+ </div>+ </div>+ <ul id="kg-skills-list" class="kg-skills-list" aria-busy="true">+ <li class="kg-skills-loading">Loading your progress…</li>+ </ul>+ <p class="kg-skills-foot">+ Level cap <b id="kg-skills-cap">99</b> · earn XP by gathering and fighting.+ </p>+ </aside>++ <!-- Level-up celebrations (real server 'levelup' events) -->+ <div id="kg-levelups" aria-live="polite"></div>++ <!-- World chat — per-realm. Focus with C (or Enter); send with Enter; Esc to+ close. Collapsed by default so it never blocks the world; clicking a+ sender name opens a Mute menu, and the Muted button lists who's hidden. -->+ <section id="kg-chat" class="kg-chat" hidden aria-label="World chat">+ <header class="kg-chat-head">+ <span class="kg-chat-title">Chat</span>+ <button+ id="kg-chat-muted-btn"+ class="kg-chat-muted-btn"+ type="button"+ aria-haspopup="dialog"+ aria-expanded="false"+ aria-controls="kg-chat-muted"+ title="Muted players"+ >+ Muted <b id="kg-chat-muted-n">0</b>+ </button>+ </header>+ <div+ id="kg-chat-log"+ class="kg-chat-log"+ role="log"+ aria-live="polite"+ aria-label="Chat messages"+ ></div>+ <form id="kg-chat-form" class="kg-chat-form" autocomplete="off">+ <input+ id="kg-chat-input"+ class="kg-chat-input"+ type="text"+ maxlength="200"+ autocomplete="off"+ aria-label="Type a message"+ placeholder="Press Enter to chat…"+ />+ </form>+ <!-- Muted-players view (toggled by the Muted button) -->+ <div+ id="kg-chat-muted"+ class="kg-chat-muted"+ hidden+ role="dialog"+ aria-label="Muted players"+ ></div>+ </section>+<div id="kg-toasts"></div><div id="kg-joystick"></div>+ <!-- Mount status — shown only while riding (Task 09). Names the steed and+ lets you dismount; the hotbar and /dismount work too. -->+ <div id="kg-mount" class="kg-mount" hidden>+ <span class="kg-mount-ico" aria-hidden="true">🐎</span>+ <span class="kg-mount-txt">Riding <b id="kg-mount-name">mount</b></span>+ <button id="kg-dismount" class="kg-mount-btn" type="button" aria-label="Dismount">Dismount</button>+ </div>++ <!-- Contextual world actions. Shown only when the action is actually+ available (near a Roast Pit with raw fish; hurt while carrying food);+ see _updateActions in src/game/iso-game.js. -->+ <div id="kg-actions" hidden>+ <button+ id="kg-cook"+ class="kg-action kg-action--cook"+ type="button"+ hidden+ aria-label="Cook raw fish at the Roast Pit"+ >+ <i class="kg-action-dot" aria-hidden="true"></i+ ><span class="kg-action-lbl">Cook fish</span>+ </button>+ <button+ id="kg-eat"+ class="kg-action kg-action--eat"+ type="button"+ hidden+ aria-label="Eat food to restore health"+ >+ <i class="kg-action-dot" aria-hidden="true"></i+ ><span class="kg-action-lbl">Eat</span>+ </button>+ <button+ id="kg-cast"+ class="kg-action kg-action--cast"+ type="button"+ hidden+ aria-label="Cast a fishing line into the water"+ >+ <i class="kg-action-dot" aria-hidden="true"></i+ ><span class="kg-action-lbl">Cast line</span>+ </button>+ </div>++ <!-- Death-bag recovery panel — opens when you tap an adjacent tombstone.+ Lists the bag's contents (or a designed empty state), a live expiry+ countdown, and a Take-all button (re-loots once the pack has room). -->+ <aside id="kg-tomb-panel" class="kg-tomb-panel" hidden role="dialog" aria-label="Death-bag">+ <header class="kg-tomb-head">+ <span class="kg-tomb-owner" id="kg-tomb-owner">Bag</span>+ <span class="kg-tomb-ttl" id="kg-tomb-ttl"></span>+ <button+ id="kg-tomb-close"+ class="kg-tomb-close"+ type="button"+ aria-label="Close bag"+ >+ <svg viewBox="0 0 24 24" aria-hidden="true">+ <path d="M6 6l12 12M18 6L6 18" />+ </svg>+ </button>+ </header>+ <div id="kg-tomb-items" class="kg-tomb-items"></div>+ <button id="kg-tomb-take" class="kg-tomb-take" type="button">Take all</button>+ </aside>++ <!-- Respawn overlay — shown while dead, with a real countdown to the synced+ respawn deadline. Pointer-transparent so it never blocks the world. -->+ <div id="kg-death" class="kg-death" hidden aria-live="assertive">+ <div class="kg-death-card">+ <div class="kg-death-eyebrow">You died</div>+ <p class="kg-death-msg" id="kg-death-msg">You died.</p>+ <div class="kg-death-count" id="kg-death-count">Respawning…</div>+ </div>+ </div>+<div id="kg-hint" hidden><kbd>W</kbd><kbd>A</kbd><kbd>S</kbd><kbd>D</kbd> move · drag to rotate · scroll to zoom+ · tap the water to fish · tap a bag to loot · <kbd>K</kbd> skills · <kbd>C</kbd> chat</div><!-- Start overlay -->@@ -56,9 +243,19 @@<div class="kg-card"><div class="kg-eyebrow">three.ws · adventure</div><h1 class="kg-title">Enter the world</h1>- <p class="kg-sub">Gather, fight, and level up across a shared isometric realm. Pick a name and drop in.</p>+ <p class="kg-sub">+ Gather, fight, and level up across a shared isometric realm. Pick a name and+ drop in.+ </p><label class="kg-field">- <input id="kg-name" type="text" maxlength="24" autocomplete="off" aria-label="Display name" placeholder="guest" />+ <input+ id="kg-name"+ type="text"+ maxlength="24"+ autocomplete="off"+ aria-label="Display name"+ placeholder="guest"+ /></label><button id="kg-start-btn" class="kg-btn" type="button">Enter world</button><div class="kg-feats">@@ -81,5 +278,7 @@</div><script type="module" src="/src/game/iso-game.js"></script>+ <!-- Controls layer (Task 12): hotbar number keys, panel toggles, rebindable keybindings. -->+ <script type="module" src="/src/game/iso-controls.js"></script></body></html>diff --git a/public/badges/assertions/quest-master-demo.json b/public/badges/assertions/quest-master-demo.jsonnew file mode 100644index 000000000..7d70d8aae--- /dev/null+++ b/public/badges/assertions/quest-master-demo.json@@ -0,0 +1,16 @@+{+ "@context": "https://w3id.org/openbadges/v2",+ "type": "Assertion",+ "id": "https://three.ws/badges/assertions/quest-master-demo.json",+ "recipient": {+ "type": "email",+ "hashed": true,+ "salt": "three-ws-demo",+ "identity": "sha256$eade00449e2266066ee43400fe4d1d1626380afb0e7de086e3b9c84faa685225"+ },+ "badge": "https://three.ws/badges/quest-master.json",+ "issuedOn": "2026-06-01T02:40:09Z",+ "verification": {+ "type": "HostedBadge"+ }+}diff --git a/public/badges/issuer.json b/public/badges/issuer.jsonnew file mode 100644index 000000000..aad5634a1--- /dev/null+++ b/public/badges/issuer.json@@ -0,0 +1,10 @@+{+ "@context": "https://w3id.org/openbadges/v2",+ "type": "Issuer",+ "id": "https://three.ws/badges/issuer.json",+ "name": "three.ws",+ "url": "https://three.ws",+ "email": "[email protected]",+ "description": "three.ws issues verifiable Open Badges 2.0 for achievements earned across its realms, quests, and creator tools.",+ "image": "https://three.ws/pwa-icon.svg"+}diff --git a/public/badges/quest-master-baked.png b/public/badges/quest-master-baked.pngnew file mode 100644index 000000000..5a5fdd37aBinary files /dev/null and b/public/badges/quest-master-baked.png differdiff --git a/public/badges/quest-master.json b/public/badges/quest-master.jsonnew file mode 100644index 000000000..6bb6b34ef--- /dev/null+++ b/public/badges/quest-master.json@@ -0,0 +1,13 @@+{+ "@context": "https://w3id.org/openbadges/v2",+ "type": "BadgeClass",+ "id": "https://three.ws/badges/quest-master.json",+ "name": "Quest Master",+ "description": "Awarded to players who complete every quest across all three.ws realms.",+ "image": "https://three.ws/badges/quest-master.png",+ "criteria": {+ "narrative": "Earned by completing all available quests in every realm of three.ws. Progress is tracked server-side; the badge is issued automatically on full completion."+ },+ "issuer": "https://three.ws/badges/issuer.json",+ "tags": ["three.ws", "mmo", "quest", "achievement"]+}diff --git a/public/badges/quest-master.png b/public/badges/quest-master.pngnew file mode 100644index 000000000..3f5d39b6cBinary files /dev/null and b/public/badges/quest-master.png differdiff --git a/public/features.json b/public/features.jsonindex d32416c32..df629ec59 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-05-31T05:54:30.931Z",+ "generated_at": "2026-05-31T08:37:15.832Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/public/x402.js b/public/x402.jsindex 507458d7f..575857011 100644--- a/public/x402.js+++ b/public/x402.js@@ -953,7 +953,7 @@ class CheckoutModal {const enc = await postJson(`${ORIGIN}/api/x402-checkout?action=encode`, {accept,signed_tx_base64: signedB64,- resource_url: this.opts.endpoint,+ resource_url: new URL(this.opts.endpoint, location.href).href,...(builderCodeBlock ? { builder_code: builderCodeBlock } : {}),});diff --git a/scripts/demo-pose.mjs b/scripts/demo-pose.mjsnew file mode 100644index 000000000..968de3c78--- /dev/null+++ b/scripts/demo-pose.mjs@@ -0,0 +1,349 @@+#!/usr/bin/env node+// Record a hands-free product demo of the Pose Studio (/pose).+//+// Drives the *real* UI with Playwright — applies preset poses, FK-rotates a+// bone, switches to IK, tweaks the environment, drops a prop, then builds and+// plays a keyframed animation on the timeline. A synthetic cursor is rendered+// into the page so the recording shows the pointer gliding and clicking like a+// person is doing it live. Playwright records native webm; we transcode to mp4.+//+// Output: pose-demo.mp4 at the repo root.+//+// Prereqs: dev server running at http://localhost:3000 (`npm run dev`)+// Usage: node scripts/demo-pose.mjs+// node scripts/demo-pose.mjs --url http://localhost:3000/pose++import fs from 'node:fs/promises';+import path from 'node:path';+import { spawn } from 'node:child_process';+import { chromium } from 'playwright';++const ROOT = path.resolve(import.meta.dirname, '..');+const argv = Object.fromEntries(+ process.argv.slice(2).reduce((acc, cur, i, arr) => {+ if (cur.startsWith('--')) acc.push([cur.slice(2), arr[i + 1]]);+ return acc;+ }, []),+);++const URL = argv.url || 'http://localhost:3000/pose';+const WIDTH = parseInt(argv.width || '1440', 10);+const HEIGHT = parseInt(argv.height || '900', 10);+const VIDEO_DIR = path.join(ROOT, '.pose-demo-raw');+const OUT_MP4 = path.join(ROOT, 'pose-demo.mp4');++// ── Synthetic cursor: injected before page scripts so it tracks every real+// mouse event Playwright dispatches. Renders a ring + dot and a click ripple. ──+const CURSOR_SCRIPT = `+(() => {+ function mount() {+ if (!document.body || document.getElementById('__demo_cursor')) return;+ const style = document.createElement('style');+ style.textContent = \`+ #__demo_cursor{position:fixed;left:0;top:0;width:26px;height:26px;+ margin:-13px 0 0 -13px;border-radius:50%;+ border:2px solid rgba(255,255,255,.9);+ box-shadow:0 0 0 1px rgba(0,0,0,.45), 0 2px 10px rgba(0,0,0,.5);+ background:rgba(255,255,255,.08);z-index:2147483647;pointer-events:none;+ transition:transform .08s ease;will-change:left,top;}+ #__demo_cursor::after{content:"";position:absolute;left:50%;top:50%;+ width:5px;height:5px;margin:-2.5px 0 0 -2.5px;border-radius:50%;+ background:#fff;}+ #__demo_cursor.__down{transform:scale(.8);background:rgba(255,255,255,.25);}+ .__demo_ripple{position:fixed;width:14px;height:14px;margin:-7px 0 0 -7px;+ border-radius:50%;border:2px solid rgba(120,220,255,.9);+ z-index:2147483646;pointer-events:none;animation:__demo_rip .5s ease-out forwards;}+ @keyframes __demo_rip{from{transform:scale(.4);opacity:.9;}+ to{transform:scale(3.4);opacity:0;}}+ \`;+ document.head.appendChild(style);+ const cur = document.createElement('div');+ cur.id = '__demo_cursor';+ cur.style.left = (window.innerWidth/2)+'px';+ cur.style.top = (window.innerHeight/2)+'px';+ document.body.appendChild(cur);+ addEventListener('mousemove', (e) => {+ cur.style.left = e.clientX+'px';+ cur.style.top = e.clientY+'px';+ }, true);+ addEventListener('mousedown', (e) => {+ cur.classList.add('__down');+ const r = document.createElement('div');+ r.className = '__demo_ripple';+ r.style.left = e.clientX+'px'; r.style.top = e.clientY+'px';+ document.body.appendChild(r);+ setTimeout(() => r.remove(), 520);+ }, true);+ addEventListener('mouseup', () => cur.classList.remove('__down'), true);+ }+ if (document.body) mount();+ else addEventListener('DOMContentLoaded', mount);+ new MutationObserver(mount).observe(document.documentElement, {childList:true,subtree:true});+})();+`;++const sleep = (ms) => new Promise((r) => setTimeout(r, ms));+let pageRef = null;+let cursor = { x: WIDTH / 2, y: HEIGHT / 2 };++// Glide the mouse from its current position to (x,y) with eased steps so the+// motion reads as human, not a teleport.+async function glide(x, y, steps = 26) {+ const sx = cursor.x, sy = cursor.y;+ for (let i = 1; i <= steps; i++) {+ const t = i / steps;+ const e = t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2; // easeInOutQuad+ await pageRef.mouse.move(sx + (x - sx) * e, sy + (y - sy) * e);+ await sleep(8);+ }+ cursor = { x, y };+}++// Resolve a selector to the centre of its bounding box (first visible match).+async function boxCenter(selector) {+ const el = pageRef.locator(selector).first();+ const box = await el.boundingBox();+ if (!box) throw new Error(`no box for ${selector}`);+ return { x: box.x + box.width / 2, y: box.y + box.height / 2, box };+}++// Move to a selector and click it. Returns false (and logs) if it's missing,+// so the tour keeps flowing rather than aborting on one stray control.+async function clickSel(selector, { pause = 320, label } = {}) {+ try {+ const c = await boxCenter(selector);+ await glide(c.x, c.y);+ await sleep(140);+ await pageRef.mouse.down();+ await sleep(70);+ await pageRef.mouse.up();+ if (label) log(` · ${label}`);+ await sleep(pause);+ return true;+ } catch (e) {+ log(` ! skip ${label || selector} (${e.message.slice(0, 60)})`);+ return false;+ }+}++// Drag a range slider's thumb to a fraction of its track (0..1), live.+async function dragSlider(selector, frac) {+ try {+ const { box } = await boxCenter(selector);+ const y = box.y + box.height / 2;+ const startX = box.x + 8;+ const endX = box.x + 8 + (box.width - 16) * frac;+ await glide(startX, y);+ await pageRef.mouse.down();+ const steps = 22;+ for (let i = 1; i <= steps; i++) {+ const cx = startX + (endX - startX) * (i / steps);+ await pageRef.mouse.move(cx, y);+ await sleep(18);+ }+ cursor = { x: endX, y };+ await pageRef.mouse.up();+ await sleep(260);+ return true;+ } catch (e) {+ log(` ! slider ${selector} (${e.message.slice(0, 50)})`);+ return false;+ }+}++// A camera orbit: press-drag across the 3D canvas to spin the view.+async function orbit(dx, dy) {+ const { box } = await boxCenter('#pose-canvas');+ const cx = box.x + box.width / 2;+ const cy = box.y + box.height / 2;+ await glide(cx, cy);+ await pageRef.mouse.down();+ const steps = 30;+ for (let i = 1; i <= steps; i++) {+ await pageRef.mouse.move(cx + (dx * i) / steps, cy + (dy * i) / steps);+ await sleep(16);+ }+ cursor = { x: cx + dx, y: cy + dy };+ await pageRef.mouse.up();+ await sleep(200);+}++// Set a value on a native input we can't realistically drag (color pickers),+// then fire input/change so the 3D scene reacts. Cursor hovers it for context.+async function setInput(selector, value) {+ try {+ const c = await boxCenter(selector);+ await glide(c.x, c.y);+ await sleep(120);+ await pageRef.locator(selector).first().evaluate((el, v) => {+ el.value = v;+ el.dispatchEvent(new Event('input', { bubbles: true }));+ el.dispatchEvent(new Event('change', { bubbles: true }));+ }, value);+ await sleep(300);+ } catch (e) {+ log(` ! setInput ${selector} (${e.message.slice(0, 50)})`);+ }+}++const logs = [];+function log(m) {+ logs.push(m);+ console.log(m);+}++async function main() {+ await fs.rm(VIDEO_DIR, { recursive: true, force: true });+ await fs.mkdir(VIDEO_DIR, { recursive: true });++ const browser = await chromium.launch({+ args: ['--use-gl=swiftshader', '--enable-unsafe-swiftshader', '--no-sandbox'],+ });+ const context = await browser.newContext({+ viewport: { width: WIDTH, height: HEIGHT },+ deviceScaleFactor: 1,+ recordVideo: { dir: VIDEO_DIR, size: { width: WIDTH, height: HEIGHT } },+ });+ await context.addInitScript(CURSOR_SCRIPT);+ const page = await context.newPage();+ pageRef = page;+ page.on('pageerror', (e) => log(`PAGEERROR: ${e.message.slice(0, 200)}`));++ log(`→ ${URL} (${WIDTH}x${HEIGHT})`);+ await page.goto(URL, { waitUntil: 'domcontentloaded', timeout: 30000 });++ // Wait until the mannequin is rendered (status leaves the "Loading…" state).+ await page.waitForSelector('#pose-canvas', { timeout: 20000 });+ await page+ .waitForFunction(+ () => {+ const s = document.getElementById('pose-status');+ return s && !/loading/i.test(s.textContent || '');+ },+ { timeout: 20000 },+ )+ .catch(() => log(' (status never cleared; continuing)'));+ await sleep(1400);++ // Discover the real preset / bone ids present in the DOM so we never click+ // a control that doesn't exist.+ const presets = await page.$$eval('[data-preset]', (els) =>+ els.map((e) => e.getAttribute('data-preset')),+ );+ const bones = await page.$$eval('[data-bone]', (els) =>+ els.map((e) => e.getAttribute('data-bone')),+ );+ log(` presets: ${presets.length} · bones: ${bones.length}`);+ const pick = (...wanted) => wanted.filter((w) => presets.includes(w));+ const armBone = bones.find((b) => /upper.?arm.?l|shoulderl|arml/i.test(b)) || bones.find((b) => /arm/i.test(b)) || bones[0];++ // ── Act 1 — preset poses, with a camera orbit to show it's real 3D ──────+ log('Act 1: preset poses');+ for (const p of pick('contrapposto', 'hands-on-hips', 'wave', 'dance')) {+ await clickSel(`[data-preset="${p}"]`, { label: `preset ${p}`, pause: 950 });+ }+ await orbit(150, -30);+ await orbit(-220, 20);+ for (const p of pick('run', 'jump')) {+ await clickSel(`[data-preset="${p}"]`, { label: `preset ${p}`, pause: 950 });+ }++ // ── Act 2 — FK: select a bone, rotate it with a slider ──────────────────+ log('Act 2: FK posing');+ await clickSel('[data-posemode="fk"]', { label: 'FK mode' });+ if (armBone) {+ await clickSel(`[data-bone="${armBone}"]`, { label: `select ${armBone}`, pause: 600 });+ const slider = '#pose-controls-host input[type="range"]';+ await dragSlider(slider, 0.85);+ await dragSlider(slider, 0.2);+ }++ // ── Act 3 — IK mode ─────────────────────────────────────────────────────+ log('Act 3: IK mode');+ await clickSel('[data-posemode="ik"]', { label: 'IK mode', pause: 700 });+ await orbit(120, 0);+ await clickSel('[data-posemode="fk"]', { label: 'back to FK', pause: 400 });++ // ── Act 4 — environment + prop ──────────────────────────────────────────+ log('Act 4: environment & props');+ await dragSlider('#pose-fov', 0.7);+ await dragSlider('#pose-light-intensity', 0.85);+ await setInput('#pose-bg', '#101826');+ await setInput('#pose-skin', '#c98a5a');+ await clickSel('[data-prop="chair"]', { label: 'prop chair', pause: 500 });+ if (pick('sit').length) await clickSel('[data-preset="sit"]', { label: 'preset sit', pause: 1100 });+ await clickSel('[data-prop="none"]', { label: 'clear prop', pause: 300 });++ // ── Act 5 — build a keyframed animation on the timeline, then play it ────+ log('Act 5: timeline animation');+ await clickSel('#pose-reset', { label: 'reset pose', pause: 500 });+ const trackBox = (await boxCenter('#tl-track')).box;+ const seekTrack = async (frac) => {+ const x = trackBox.x + 14 + (trackBox.width - 28) * frac;+ const y = trackBox.y + trackBox.height - 14;+ await glide(x, y);+ await pageRef.mouse.down();+ await sleep(60);+ await pageRef.mouse.up();+ cursor = { x, y };+ await sleep(260);+ };++ const beats = [+ { frac: 0.0, preset: pick('relaxed', 'apose', 'tpose')[0] },+ { frac: 0.33, preset: pick('wave', 'hands-up')[0] },+ { frac: 0.66, preset: pick('run', 'walk-step')[0] },+ { frac: 1.0, preset: pick('jump', 'dance')[0] },+ ].filter((b) => b.preset);++ for (const b of beats) {+ await seekTrack(b.frac);+ await clickSel(`[data-preset="${b.preset}"]`, { label: `pose ${b.preset} @${Math.round(b.frac * 100)}%`, pause: 350 });+ await clickSel('#tl-add-key', { label: 'add keyframe', pause: 450 });+ }++ // Rewind and play the finished clip a couple of loops.+ await clickSel('#tl-start', { label: 'rewind' });+ await clickSel('#tl-play', { label: '▶ play', pause: 200 });+ await sleep(8200);+ await clickSel('#tl-play', { label: '⏸ pause', pause: 400 });+ await orbit(180, -20);+ await sleep(1200);++ log('Closing — finalizing video…');+ await context.close(); // flushes the webm+ await browser.close();++ const files = (await fs.readdir(VIDEO_DIR)).filter((f) => f.endsWith('.webm'));+ if (!files.length) throw new Error('no webm produced');+ const webm = path.join(VIDEO_DIR, files[0]);++ log('Transcoding → pose-demo.mp4');+ await new Promise((resolve, reject) => {+ const ff = spawn(+ 'ffmpeg',+ [+ '-y',+ '-i', webm,+ '-c:v', 'libx264',+ '-preset', 'medium',+ '-crf', '20',+ '-pix_fmt', 'yuv420p',+ '-vf', 'scale=trunc(iw/2)*2:trunc(ih/2)*2',+ '-movflags', '+faststart',+ OUT_MP4,+ ],+ { stdio: ['ignore', 'ignore', 'inherit'] },+ );+ ff.on('exit', (c) => (c === 0 ? resolve() : reject(new Error(`ffmpeg exit ${c}`))));+ });++ await fs.rm(VIDEO_DIR, { recursive: true, force: true });+ const st = await fs.stat(OUT_MP4);+ log(`\n✓ ${path.relative(ROOT, OUT_MP4)} — ${(st.size / 1024 / 1024).toFixed(1)} MB · ${WIDTH}x${HEIGHT}`);+}++main().catch((e) => {+ console.error('\nFAILED:', e);+ process.exit(1);+});diff --git a/scripts/openbadge/art.mjs b/scripts/openbadge/art.mjsnew file mode 100644index 000000000..c818ed1b4--- /dev/null+++ b/scripts/openbadge/art.mjs@@ -0,0 +1,115 @@+// Render the three.ws Open Badge medallion PNG from the brand cube logo.+// Produces a square badge image suitable for Open Badges 2.0 (baked separately).+//+// node scripts/openbadge/art.mjs "Quest Master" public/badges/quest-master.png+//+// The cube geometry mirrors public/pwa-icon.svg so the badge stays on-brand.+import sharp from 'sharp';+import { writeFileSync } from 'node:fs';++const SIZE = 512;++// Escape text for safe inclusion in SVG.+const esc = (s) =>+ String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));++// The isometric cube, drawn centred and scaled into the medallion field.+// Source vertices (from pwa-icon.svg, 512 box) translated up + scaled to 0.62.+function cube() {+ const cx = 256, cy = 232, s = 0.62;+ const map = (x, y) => `${(cx + (x - 256) * s).toFixed(1)},${(cy + (y - 256) * s).toFixed(1)}`;+ const P = {+ top: [256, 110], fl: [116, 182], fr: [396, 182],+ midL: [116, 330], midR: [396, 330], front: [256, 254], bottom: [256, 402],+ };+ const p = (pts) => pts.map(([x, y]) => map(x, y)).join(' ');+ return `+ <polygon points="${p([P.top, P.fl, P.midL, P.bottom])}" fill="url(#faceLeft)"/>+ <polygon points="${p([P.top, P.fr, P.midR, P.bottom])}" fill="url(#faceRight)"/>+ <polygon points="${p([P.top, P.fl, P.front, P.fr])}" fill="url(#faceTop)"/>+ <g stroke-linecap="round" filter="url(#edgeGlow)">+ <line x1="${map(256,110).split(',')[0]}" y1="${map(256,110).split(',')[1]}" x2="${map(116,182).split(',')[0]}" y2="${map(116,182).split(',')[1]}" stroke="#7ec8e3" stroke-width="2.4" opacity="0.85"/>+ <line x1="${map(256,110).split(',')[0]}" y1="${map(256,110).split(',')[1]}" x2="${map(396,182).split(',')[0]}" y2="${map(396,182).split(',')[1]}" stroke="#7ec8e3" stroke-width="2.4" opacity="0.85"/>+ <line x1="${map(116,182).split(',')[0]}" y1="${map(116,182).split(',')[1]}" x2="${map(256,254).split(',')[0]}" y2="${map(256,254).split(',')[1]}" stroke="#5aadcf" stroke-width="1.8" opacity="0.6"/>+ <line x1="${map(396,182).split(',')[0]}" y1="${map(396,182).split(',')[1]}" x2="${map(256,254).split(',')[0]}" y2="${map(256,254).split(',')[1]}" stroke="#5aadcf" stroke-width="1.8" opacity="0.6"/>+ <line x1="${map(116,182).split(',')[0]}" y1="${map(116,182).split(',')[1]}" x2="${map(116,330).split(',')[0]}" y2="${map(116,330).split(',')[1]}" stroke="#5aadcf" stroke-width="2.2" opacity="0.6"/>+ <line x1="${map(396,182).split(',')[0]}" y1="${map(396,182).split(',')[1]}" x2="${map(396,330).split(',')[0]}" y2="${map(396,330).split(',')[1]}" stroke="#5aadcf" stroke-width="2.2" opacity="0.6"/>+ <line x1="${map(256,254).split(',')[0]}" y1="${map(256,254).split(',')[1]}" x2="${map(256,402).split(',')[0]}" y2="${map(256,402).split(',')[1]}" stroke="#4a9abf" stroke-width="1.8" opacity="0.5"/>+ <line x1="${map(116,330).split(',')[0]}" y1="${map(116,330).split(',')[1]}" x2="${map(256,402).split(',')[0]}" y2="${map(256,402).split(',')[1]}" stroke="#5aadcf" stroke-width="2.2" opacity="0.65"/>+ <line x1="${map(396,330).split(',')[0]}" y1="${map(396,330).split(',')[1]}" x2="${map(256,402).split(',')[0]}" y2="${map(256,402).split(',')[1]}" stroke="#5aadcf" stroke-width="2.2" opacity="0.65"/>+ </g>+ <g filter="url(#vtxGlow)">+ <circle cx="${map(256,110).split(',')[0]}" cy="${map(256,110).split(',')[1]}" r="9" fill="url(#vglow)"/>+ <circle cx="${map(116,182).split(',')[0]}" cy="${map(116,182).split(',')[1]}" r="6" fill="url(#vglow)" opacity="0.7"/>+ <circle cx="${map(396,182).split(',')[0]}" cy="${map(396,182).split(',')[1]}" r="6" fill="url(#vglow)" opacity="0.7"/>+ <circle cx="${map(256,402).split(',')[0]}" cy="${map(256,402).split(',')[1]}" r="5" fill="url(#vglow)" opacity="0.45"/>+ </g>`;+}++export function badgeSvg(title = 'three.ws') {+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${SIZE} ${SIZE}" width="${SIZE}" height="${SIZE}">+ <defs>+ <radialGradient id="field" cx="50%" cy="42%" r="62%">+ <stop offset="0%" stop-color="#0e2236"/>+ <stop offset="70%" stop-color="#0a1726"/>+ <stop offset="100%" stop-color="#060e18"/>+ </radialGradient>+ <linearGradient id="ring" x1="0" y1="0" x2="1" y2="1">+ <stop offset="0%" stop-color="#9fe6ff"/>+ <stop offset="45%" stop-color="#4aa6cf"/>+ <stop offset="100%" stop-color="#1d4f6e"/>+ </linearGradient>+ <radialGradient id="vglow" cx="50%" cy="50%" r="50%">+ <stop offset="0%" stop-color="#ffffff" stop-opacity="0.95"/>+ <stop offset="35%" stop-color="#b8e8ff" stop-opacity="0.5"/>+ <stop offset="100%" stop-color="#b8e8ff" stop-opacity="0"/>+ </radialGradient>+ <linearGradient id="faceTop" x1="0" y1="0" x2="0" y2="1">+ <stop offset="0%" stop-color="#234055" stop-opacity="0.95"/>+ <stop offset="100%" stop-color="#0f2030" stop-opacity="0.95"/>+ </linearGradient>+ <linearGradient id="faceRight" x1="0" y1="0" x2="1" y2="1">+ <stop offset="0%" stop-color="#13283c" stop-opacity="0.95"/>+ <stop offset="100%" stop-color="#091420" stop-opacity="0.95"/>+ </linearGradient>+ <linearGradient id="faceLeft" x1="1" y1="0" x2="0" y2="1">+ <stop offset="0%" stop-color="#102234" stop-opacity="0.92"/>+ <stop offset="100%" stop-color="#0a131f" stop-opacity="0.95"/>+ </linearGradient>+ <filter id="edgeGlow" x="-20%" y="-20%" width="140%" height="140%">+ <feGaussianBlur stdDeviation="2" result="b"/><feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge>+ </filter>+ <filter id="vtxGlow" x="-100%" y="-100%" width="300%" height="300%">+ <feGaussianBlur stdDeviation="6" result="b"/><feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge>+ </filter>+ <path id="arc" d="M 96 256 A 160 160 0 0 1 416 256" fill="none"/>+ </defs>++ <circle cx="256" cy="256" r="248" fill="url(#ring)"/>+ <circle cx="256" cy="256" r="236" fill="#060e18"/>+ <circle cx="256" cy="256" r="232" fill="url(#field)"/>+ <circle cx="256" cy="256" r="232" fill="none" stroke="#7ec8e3" stroke-width="1" opacity="0.35"/>++ ${cube()}++ <!-- wordmark -->+ <text x="256" y="372" text-anchor="middle" font-family="'Segoe UI',system-ui,-apple-system,sans-serif"+ font-size="34" font-weight="700" letter-spacing="1" fill="#eaf6ff">three.ws</text>+ <!-- achievement title -->+ <text x="256" y="408" text-anchor="middle" font-family="'Segoe UI',system-ui,-apple-system,sans-serif"+ font-size="20" font-weight="600" letter-spacing="3" fill="#7ec8e3">${esc(title.toUpperCase())}</text>+ <line x1="196" y1="424" x2="316" y2="424" stroke="#4aa6cf" stroke-width="1.5" opacity="0.5"/>+</svg>`;+}++export async function renderBadge(title, outPath) {+ const png = await sharp(Buffer.from(badgeSvg(title))).png().toBuffer();+ writeFileSync(outPath, png);+ return outPath;+}++// CLI: node art.mjs "<title>" <out.png>+if (import.meta.url === `file://${process.argv[1]}`) {+ const [, , title = 'three.ws', out = 'public/badges/badge.png'] = process.argv;+ renderBadge(title, out).then((p) => console.log('wrote', p));+}diff --git a/scripts/openbadge/cli.mjs b/scripts/openbadge/cli.mjsnew file mode 100644index 000000000..53d89c73c--- /dev/null+++ b/scripts/openbadge/cli.mjs@@ -0,0 +1,221 @@+#!/usr/bin/env node+// three.ws — Open Badges 2.0 issuing / baking / verification CLI.+//+// Implements the parts of the spec that produce a portable credential:+// - Assertion creation with hashed recipient identity (sha256 + salt)+// - PNG "baking": embeds the Assertion JSON in an iTXt chunk keyed `openbadges`+// (per https://www.imsglobal.org/sites/default/files/Badges/OBv2p0/baking/index.html)+// - Extraction + structural verification of a baked badge+//+// Usage:+// node scripts/openbadge/cli.mjs issue --badge <badgeclass-url> --recipient <email> \+// --id <assertion-url> [--salt <salt>] [--out <assertion.json>]+// node scripts/openbadge/cli.mjs bake --image <in.png> --assertion <assertion.json> --out <baked.png>+// node scripts/openbadge/cli.mjs verify --image <baked.png>+// node scripts/openbadge/cli.mjs extract --image <baked.png>+import { readFileSync, writeFileSync } from 'node:fs';+import { createHash, randomBytes } from 'node:crypto';+import zlib from 'node:zlib';++// ---------- arg parsing ----------+function parseArgs(argv) {+ const out = {};+ for (let i = 0; i < argv.length; i++) {+ if (argv[i].startsWith('--')) {+ const key = argv[i].slice(2);+ const val = argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[++i] : true;+ out[key] = val;+ }+ }+ return out;+}++// ISO-8601 without sub-second noise.+const nowIso = () => new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');++// ---------- Assertion ----------+// Hash a recipient identity per the spec: sha256$<hex(sha256(identity + salt))>.+function hashIdentity(identity, salt) {+ const digest = createHash('sha256').update(identity + salt).digest('hex');+ return `sha256$${digest}`;+}++function buildAssertion({ badge, recipient, id, salt, identityType = 'email' }) {+ return {+ '@context': 'https://w3id.org/openbadges/v2',+ type: 'Assertion',+ id,+ recipient: {+ type: identityType,+ hashed: true,+ salt,+ identity: hashIdentity(recipient, salt),+ },+ badge,+ issuedOn: nowIso(),+ verification: { type: 'HostedBadge' },+ };+}++// ---------- PNG chunk plumbing ----------+const PNG_SIG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);++// CRC-32 (PNG polynomial), table built once.+const CRC_TABLE = (() => {+ const t = new Uint32Array(256);+ for (let n = 0; n < 256; n++) {+ let c = n;+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;+ t[n] = c >>> 0;+ }+ return t;+})();+function crc32(buf) {+ let c = 0xffffffff;+ for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);+ return (c ^ 0xffffffff) >>> 0;+}++function* readChunks(png) {+ if (!png.subarray(0, 8).equals(PNG_SIG)) throw new Error('not a PNG file');+ let off = 8;+ while (off < png.length) {+ const len = png.readUInt32BE(off);+ const type = png.toString('ascii', off + 4, off + 8);+ const data = png.subarray(off + 8, off + 8 + len);+ yield { type, data, start: off, end: off + 12 + len };+ off += 12 + len;+ }+}++function makeChunk(type, data) {+ const len = Buffer.alloc(4);+ len.writeUInt32BE(data.length, 0);+ const typeBuf = Buffer.from(type, 'ascii');+ const crcBuf = Buffer.alloc(4);+ crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])), 0);+ return Buffer.concat([len, typeBuf, data, crcBuf]);+}++// Build an iTXt chunk. Open Badges uses keyword "openbadges", uncompressed.+function makeITXtOpenBadges(text) {+ const keyword = Buffer.from('openbadges', 'latin1');+ const data = Buffer.concat([+ keyword,+ Buffer.from([0x00]), // null separator+ Buffer.from([0x00]), // compression flag: 0 = uncompressed+ Buffer.from([0x00]), // compression method+ Buffer.from([0x00]), // language tag (empty) + null+ Buffer.from([0x00]), // translated keyword (empty) + null+ Buffer.from(text, 'utf8'),+ ]);+ return makeChunk('iTXt', data);+}++// Bake: strip any existing openbadges iTXt, insert ours right after IHDR.+function bake(pngPath, assertionPath, outPath) {+ const png = readFileSync(pngPath);+ const assertion = readFileSync(assertionPath, 'utf8').trim();+ JSON.parse(assertion); // validate it is JSON before embedding++ const head = [PNG_SIG];+ let inserted = false;+ for (const ch of readChunks(png)) {+ if (ch.type === 'iTXt' && ch.data.toString('latin1').startsWith('openbadges\x00')) continue; // drop stale bake+ head.push(png.subarray(ch.start, ch.end));+ if (ch.type === 'IHDR' && !inserted) {+ head.push(makeITXtOpenBadges(assertion));+ inserted = true;+ }+ }+ if (!inserted) throw new Error('no IHDR chunk found; not a valid PNG');+ writeFileSync(outPath, Buffer.concat(head));+ return outPath;+}++// Extract the baked Open Badges payload (JSON or URL).+function extract(pngPath) {+ const png = readFileSync(pngPath);+ for (const ch of readChunks(png)) {+ if (ch.type !== 'iTXt') continue;+ const d = ch.data;+ if (!d.toString('latin1').startsWith('openbadges\x00')) continue;+ // layout: keyword \0 compFlag compMethod langTag \0 transKeyword \0 text+ let p = d.indexOf(0x00); // after keyword+ const compFlag = d[p + 1];+ p += 3; // skip compFlag + compMethod+ p = d.indexOf(0x00, p) + 1; // end of language tag+ p = d.indexOf(0x00, p) + 1; // end of translated keyword+ let text = d.subarray(p);+ if (compFlag === 1) text = zlib.inflateSync(text);+ return text.toString('utf8');+ }+ return null;+}++// Structural verification of a baked badge.+function verify(pngPath) {+ const payload = extract(pngPath);+ const problems = [];+ if (!payload) return { ok: false, problems: ['no `openbadges` iTXt chunk found in PNG'] };++ let assertion;+ if (/^https?:\/\//.test(payload.trim())) {+ return {+ ok: true,+ mode: 'url',+ payload: payload.trim(),+ problems: [],+ note: 'Badge is baked with a hosted Assertion URL. Fetch it to complete verification.',+ };+ }+ try { assertion = JSON.parse(payload); } catch { return { ok: false, problems: ['baked payload is neither a URL nor valid JSON'] }; }++ const ctx = assertion['@context'];+ if (ctx !== 'https://w3id.org/openbadges/v2') problems.push(`@context is not Open Badges 2.0 (got ${JSON.stringify(ctx)})`);+ if (assertion.type !== 'Assertion') problems.push(`type is not "Assertion" (got ${JSON.stringify(assertion.type)})`);+ if (!assertion.id) problems.push('missing Assertion id');+ if (!assertion.badge) problems.push('missing badge reference');+ if (!assertion.issuedOn) problems.push('missing issuedOn');+ const r = assertion.recipient;+ if (!r || !r.identity) problems.push('missing recipient identity');+ else if (r.hashed && !/^sha256\$[0-9a-f]{64}$/.test(r.identity)) problems.push('hashed recipient identity is malformed');+ if (!assertion.verification?.type) problems.push('missing verification type');++ return { ok: problems.length === 0, mode: 'embedded', assertion, problems };+}++// ---------- main ----------+const [cmd, ...rest] = process.argv.slice(2);+const a = parseArgs(rest);++try {+ if (cmd === 'issue') {+ if (!a.badge || !a.recipient || !a.id) throw new Error('issue requires --badge --recipient --id');+ const salt = a.salt || randomBytes(8).toString('hex');+ const assertion = buildAssertion({ badge: a.badge, recipient: a.recipient, id: a.id, salt, identityType: a.type || 'email' });+ const json = JSON.stringify(assertion, null, 2);+ if (a.out) { writeFileSync(a.out, json + '\n'); console.error('wrote', a.out, '(salt:', salt + ')'); }+ else console.log(json);+ } else if (cmd === 'bake') {+ if (!a.image || !a.assertion || !a.out) throw new Error('bake requires --image --assertion --out');+ bake(a.image, a.assertion, a.out);+ console.error('baked', a.out);+ } else if (cmd === 'extract') {+ if (!a.image) throw new Error('extract requires --image');+ const p = extract(a.image);+ if (p == null) { console.error('no openbadges payload found'); process.exit(1); }+ console.log(p);+ } else if (cmd === 'verify') {+ if (!a.image) throw new Error('verify requires --image');+ const res = verify(a.image);+ console.log(JSON.stringify(res, null, 2));+ process.exit(res.ok ? 0 : 1);+ } else {+ console.error('commands: issue | bake | extract | verify');+ process.exit(2);+ }+} catch (err) {+ console.error('error:', err.message);+ process.exit(1);+}diff --git a/scripts/test-tombstone.mjs b/scripts/test-tombstone.mjsnew file mode 100644index 000000000..286051135--- /dev/null+++ b/scripts/test-tombstone.mjs@@ -0,0 +1,238 @@+// Verifies Task 02 (player death & tombstone death-bags) server logic directly+// against GameRoom's real methods — no mocks of the logic, only thin stubs for+// the Colyseus transport (client.send / this.clients) that the methods touch.+//+// We drive _killPlayer / _damagePlayer / _handleTombLoot / _tick exactly as the+// live room would and assert the invariants from the task's Definition of Done:+// • danger realm drops a tombstone with the right items; safe realm does not+// • tools are kept, non-tool items dropped, gold untouched+// • ownership holds until the grace window, then anyone adjacent may loot+// • adjacency is enforced+// • inventory math is exact (no duplication, no loss) including a full pack+// • expired bags vanish in the sim tick; respawn returns to the realm spawn+//+// Run: node scripts/test-tombstone.mjs++import { GameRoom } from '../multiplayer/src/rooms/GameRoom.js';+import { REALMS } from '../multiplayer/src/rooms/realms.js';+import { GameState, GamePlayer, Slot } from '../multiplayer/src/schemas/game.js';++const INV_SIZE = 24;+const HOTBAR_SIZE = 6;+const TTL = 120000;+const GRACE = 45000;++let passed = 0;+let failed = 0;+function ok(cond, label) {+ if (cond) { passed++; console.log(` ✓ ${label}`); }+ else { failed++; console.error(` ✗ ${label}`); }+}+function eq(a, b, label) { ok(a === b, `${label} (got ${a}, want ${b})`); }++// Build a GameRoom without running Colyseus' lifecycle: we only need its+// methods + a state container + the priv/clients maps the methods read.+function makeRoom(realmName) {+ const room = Object.create(GameRoom.prototype);+ room.realm = REALMS[realmName];+ room.state = new GameState();+ room.state.realm = realmName;+ room.priv = new Map();+ room.clients = [];+ room._tombSeq = 0;+ return room;+}++function addPlayer(room, id, name, tx, ty) {+ const p = new GamePlayer();+ p.id = id; p.name = name; p.tx = tx; p.ty = ty;+ p.hp = p.maxHp = 100; p.gold = 1234;+ for (let i = 0; i < INV_SIZE; i++) p.inv.push(new Slot());+ for (let i = 0; i < HOTBAR_SIZE; i++) p.hotbar.push(new Slot());+ room.state.players.set(id, p);+ const messages = [];+ const client = { sessionId: id, send: (type, data) => messages.push({ type, data }), messages };+ room.clients.push(client);+ room.priv.set(id, { xp: {}, bank: [], cooldowns: { gather: 0, attack: 0 }, rate: new Map() });+ return { p, client };+}++function firstTomb(room) {+ for (const [, t] of room.state.tombstones) return t;+ return null;+}+function tombItems(t) {+ const out = {};+ for (const s of t.items) if (s.item) out[s.item] = (out[s.item] || 0) + s.qty;+ return out;+}+function invCount(p, item) {+ let n = 0;+ for (const s of [...p.inv, ...p.hotbar]) if (s.item === item) n += s.qty;+ return n;+}++// --------------------------------------------------------------------------+console.log('Test 1 — danger realm drops a tombstone (tools kept, loot dropped)');+{+ const room = makeRoom('wilderness');+ const { p, client } = addPlayer(room, 'A', 'Alice', 12, 12);+ p.inv[0].item = 'wood'; p.inv[0].qty = 500;+ p.inv[1].item = 'stone'; p.inv[1].qty = 10;+ p.inv[2].item = 'pickaxe'; p.inv[2].qty = 1; // a TOOL sitting in the backpack+ p.hotbar[0].item = 'axe'; p.hotbar[0].qty = 1;+ p.hotbar[1].item = 'sword'; p.hotbar[1].qty = 1;+ p.hotbar[2].item = 'fish'; p.hotbar[2].qty = 3;+ const goldBefore = p.gold;++ room._killPlayer(p, { byName: 'a goblin' });++ ok(p.dead === true, 'player is dead');+ ok(p.respawnAt > 0, 'respawnAt scheduled');+ eq(p.gold, goldBefore, 'gold is NOT dropped');+ ok(invCount(p, 'axe') === 1 && invCount(p, 'sword') === 1 && invCount(p, 'pickaxe') === 1, 'all tools kept');+ ok(invCount(p, 'wood') === 0 && invCount(p, 'stone') === 0 && invCount(p, 'fish') === 0, 'non-tool items removed from pack');+ const t = firstTomb(room);+ ok(!!t, 'tombstone created');+ eq(t.owner, 'A', 'tombstone owner');+ eq(t.ownerName, 'Alice', 'tombstone ownerName');+ eq(t.tx, 12, 'tombstone tx = death tile'); eq(t.ty, 12, 'tombstone ty = death tile');+ ok(Math.abs(t.expiresAt - (p.respawnAt - 4000 + TTL)) < 5, 'expiresAt ~ now + TTL');+ const items = tombItems(t);+ ok(items.wood === 500 && items.stone === 10 && items.fish === 3, 'bag holds exactly the dropped loot');+ eq(t.items.length, 3, 'bag has 3 slots');+ const died = client.messages.find((m) => m.type === 'died');+ ok(!!died && died.data.dropped === 3 && died.data.danger === true, "'died' notice carries dropped count + danger");+}++console.log('Test 2 — safe realm: no tombstone, no items lost');+{+ const room = makeRoom('mainland');+ const { p, client } = addPlayer(room, 'B', 'Bob', 24, 30);+ p.inv[0].item = 'wood'; p.inv[0].qty = 99;+ room._killPlayer(p);+ ok(p.dead === true, 'player is dead');+ eq(room.state.tombstones.size, 0, 'no tombstone in a safe realm');+ eq(invCount(p, 'wood'), 99, 'items retained in a safe realm');+ const died = client.messages.find((m) => m.type === 'died');+ ok(!!died && died.data.danger === false && died.data.dropped === 0, "'died' notice marks safe realm");+}++console.log('Test 3 — _damagePlayer funnels into death at 0 HP');+{+ const room = makeRoom('wilderness');+ const { p } = addPlayer(room, 'C', 'Cara', 5, 5);+ p.hp = 8;+ const fatal1 = room._damagePlayer(p, 3);+ ok(fatal1 === false && p.hp === 5 && !p.dead, 'non-fatal hit reduces HP');+ const fatal2 = room._damagePlayer(p, 999);+ ok(fatal2 === true && p.hp === 0 && p.dead, 'lethal hit kills + clamps HP at 0');+ const again = room._damagePlayer(p, 10);+ ok(again === false, 'damaging an already-dead player is a no-op');+}++console.log('Test 4 — ownership: only owner loots before grace; adjacency enforced');+{+ const room = makeRoom('wilderness');+ const { p: owner } = addPlayer(room, 'O', 'Owner', 10, 10);+ owner.inv[0].item = 'wood'; owner.inv[0].qty = 50;+ room._killPlayer(owner);+ const t = firstTomb(room);++ // A thief joins, NOT adjacent → denied with an adjacency notice.+ const { p: thief, client: thiefC } = addPlayer(room, 'T', 'Thief', 20, 20);+ room._handleTombLoot(thiefC, { id: t.id });+ ok(thiefC.messages.some((m) => m.data?.text?.includes('Walk up')), 'far player told to walk up');+ eq(tombItems(t).wood, 50, 'bag untouched when not adjacent');++ // Thief walks adjacent but it's still the owner-only window → ownership notice.+ thief.tx = 11; thief.ty = 10;+ room._handleTombLoot(thiefC, { id: t.id });+ ok(thiefC.messages.some((m) => m.data?.text?.includes('belongs to Owner')), 'adjacent non-owner blocked pre-grace');+ eq(tombItems(t).wood, 50, 'bag untouched by non-owner pre-grace');++ // Owner respawns far away (cannot loot until they walk back).+ owner.dead = false; owner.hp = 100; owner.tx = 20; owner.ty = 36;+ const ownerC = room.clients.find((c) => c.sessionId === 'O');+ room._handleTombLoot(ownerC, { id: t.id });+ ok(ownerC.messages.some((m) => m.data?.text?.includes('Walk up')), 'owner must be adjacent too');++ // Owner walks back adjacent → recovers everything, bag removed.+ owner.tx = 10; owner.ty = 11;+ room._handleTombLoot(ownerC, { id: t.id });+ eq(invCount(owner, 'wood'), 50, 'owner recovered all wood');+ eq(room.state.tombstones.size, 0, 'emptied bag removed');+}++console.log('Test 5 — grace window opens the bag to anyone adjacent');+{+ const room = makeRoom('wilderness');+ const { p: owner } = addPlayer(room, 'O', 'Owner', 10, 10);+ owner.inv[0].item = 'coal'; owner.inv[0].qty = 20;+ room._killPlayer(owner);+ const t = firstTomb(room);+ // Force the bag into its final grace window.+ t.expiresAt = Date.now() + GRACE - 1000;+ const { p: looter, client: looterC } = addPlayer(room, 'L', 'Looter', 11, 10);+ room._handleTombLoot(looterC, { id: t.id });+ eq(invCount(looter, 'coal'), 20, 'non-owner loots during grace window');+ eq(room.state.tombstones.size, 0, 'emptied bag removed');+}++console.log('Test 6 — inventory math is exact (full pack + partial fit)');+{+ const { Tombstone } = await import('../multiplayer/src/schemas/game.js');+ // Full pack: every backpack + hotbar slot maxed with wood. Nothing can fit;+ // the bag must keep everything (no loss) and survive.+ const room = makeRoom('wilderness');+ const { p: owner, client } = addPlayer(room, 'O', 'Owner', 10, 11);+ for (const s of [...owner.inv, ...owner.hotbar]) { s.item = 'wood'; s.qty = 999; }+ const t = new Tombstone();+ t.id = 'tomb_manual'; t.owner = 'O'; t.ownerName = 'Owner'; t.tx = 10; t.ty = 10;+ t.expiresAt = Date.now() + TTL; t.items.push(new Slot('wood', 500));+ room.state.tombstones.set(t.id, t);++ const totalBefore = invCount(owner, 'wood') + 500;+ room._handleTombLoot(client, { id: t.id });+ eq(invCount(owner, 'wood') + (tombItems(t).wood || 0), totalBefore, 'no duplication/loss with a full pack');+ eq(tombItems(t).wood, 500, 'full pack leaves all 500 in the bag');+ ok(room.state.tombstones.has(t.id), 'bag remains when nothing could be taken');+ ok(client.messages.some((m) => m.data?.text?.includes('pack is full')), 'full-pack notice shown');++ // Partial fit: free exactly 499 of room in one backpack stack.+ owner.inv[0].qty = 500; // room for 499 more in this stack+ const total2 = invCount(owner, 'wood') + (tombItems(t).wood || 0);+ room._handleTombLoot(client, { id: t.id });+ eq(invCount(owner, 'wood') + (tombItems(t).wood || 0), total2, 'conserved across a partial recovery');+ eq(tombItems(t).wood || 0, 1, 'exactly the overflow (1) remains in the bag');+ ok(room.state.tombstones.has(t.id), 'partially-emptied bag remains');+}++console.log('Test 7 — expiry in _tick + realm-aware respawn');+{+ const room = makeRoom('wilderness');+ const { p } = addPlayer(room, 'O', 'Owner', 10, 10);+ p.inv[0].item = 'wood'; p.inv[0].qty = 5;+ room._killPlayer(p);+ const t = firstTomb(room);+ t.expiresAt = Date.now() - 1; // already crumbled+ p.respawnAt = Date.now() - 1; // due to respawn+ room._tick();+ eq(room.state.tombstones.size, 0, 'expired bag removed in the sim tick');+ ok(!p.dead && p.hp === p.maxHp, 'player respawned at full HP');+ eq(p.tx, REALMS.wilderness.spawn.tx, 'respawn tx = THIS realm spawn');+ eq(p.ty, REALMS.wilderness.spawn.ty, 'respawn ty = THIS realm spawn');+}++console.log('Test 8 — a bag with zero droppable loot is never created');+{+ const room = makeRoom('wilderness');+ const { p } = addPlayer(room, 'O', 'Owner', 10, 10);+ // Only tools on board — nothing to drop.+ p.hotbar[0].item = 'axe'; p.hotbar[0].qty = 1;+ room._killPlayer(p);+ eq(room.state.tombstones.size, 0, 'no empty bag spawned');+}++console.log(`\n${passed} passed, ${failed} failed`);+process.exit(failed ? 1 : 0);diff --git a/src/game/community-net.js b/src/game/community-net.jsindex aaa45f494..764eaeb89 100644--- a/src/game/community-net.js+++ b/src/game/community-net.js@@ -94,6 +94,7 @@ export class CommunityNet {this._reconnectTimer = null;this._reconnectAttempts = 0;this._destroyed = false;+ this._connectGen = 0;}on(event, fn) {@@ -131,6 +132,11 @@ export class CommunityNet {async connect() {if (this._destroyed) return;this._closeRoom();+ // Bump a generation token so a slower in-flight connect (e.g. a manual+ // retry racing the auto-reconnect timer) can detect it's been superseded+ // after its await resolves and discard the room it joined, rather than+ // orphaning a second live socket — the same duplicate-chat leak.+ const gen = ++this._connectGen;this._setStatus('connecting');try {this.client = new Client(this.url);@@ -154,7 +160,12 @@ export class CommunityNet {options.holderPass = this.holderPass;options.holderMinUsd = this.holderMinUsd;}- this.room = await this.client.joinOrCreate(ROOM_NAME, options);+ const room = await this.client.joinOrCreate(ROOM_NAME, options);+ if (this._destroyed || gen !== this._connectGen) {+ try { room.leave(); } catch {}+ return;+ }+ this.room = room;this.sessionId = this.room.sessionId;this.room.onMessage('chat', (msg) => this._emit('chat', msg));diff --git a/src/game/game-hud.js b/src/game/game-hud.jsnew file mode 100644index 000000000..425f29201--- /dev/null+++ b/src/game/game-hud.js@@ -0,0 +1,431 @@+// GameHud — the DOM HUD layer for the /game isometric client: the hotbar, the+// quest panel (tutorial + daily quests), Aldric's dialog, and the bank panel.+//+// It owns only DOM + presentation. Every player intent flows back out through+// callbacks passed in `opts` (onEquip, onDeposit, onWithdraw, onTurnIn, …) so+// the scene controller (iso-game.js) stays the single owner of the network and+// world state. The HUD is told what to render via setHotbar/setInventory/+// setBank/setQuests and never reaches into the scene itself.+//+// All quest state shown here is the server's authoritative snapshot — progress+// bars, reward previews, turn-in availability, and the reset countdown are+// derived from it. The countdown ticks on the real clock and, when it elapses,+// asks the controller to re-fetch (onReset) so a new day's board appears+// without a reconnect.++// Item presentation. Icons are emoji so there is no asset pipeline to miss; the+// server's item registry (the 'items' message) can override labels later, but+// these cover everything the world produces today.+const ITEM_META = {+ axe: { icon: '🪓', label: 'Axe' },+ pickaxe: { icon: '⛏️', label: 'Pickaxe' },+ rod: { icon: '🎣', label: 'Fishing Rod' },+ hammer: { icon: '🔨', label: 'Hammer' },+ sword: { icon: '⚔️', label: 'Sword' },+ wood: { icon: '🪵', label: 'Wood' },+ stone: { icon: '🪨', label: 'Stone' },+ coal: { icon: '⚫', label: 'Coal' },+ fish: { icon: '🐟', label: 'Raw Fish' },+ cookedFish: { icon: '🍤', label: 'Cooked Fish' },+ bones: { icon: '🦴', label: 'Bones' },+ hide: { icon: '🟫', label: 'Beast Hide' },+ healthPotion: { icon: '🧪', label: 'Health Potion' },+ dire_wolf: { icon: '🐺', label: 'Dire Wolf' },+ war_boar: { icon: '🐗', label: 'War Boar' },+};+export function itemMeta(id) {+ return ITEM_META[id] || { icon: '📦', label: id ? id[0].toUpperCase() + id.slice(1) : '' };+}++const SKILL_LABEL = { combat: 'Combat', woodcutting: 'Woodcutting', mining: 'Mining', fishing: 'Fishing', cooking: 'Cooking' };++function fmtCountdown(ms) {+ if (ms <= 0) return 'now';+ const s = Math.floor(ms / 1000);+ const h = Math.floor(s / 3600);+ const m = Math.floor((s % 3600) / 60);+ const sec = s % 60;+ if (h > 0) return `${h}h ${m}m`;+ if (m > 0) return `${m}m ${sec}s`;+ return `${sec}s`;+}++function el(tag, cls, html) {+ const e = document.createElement(tag);+ if (cls) e.className = cls;+ if (html != null) e.innerHTML = html;+ return e;+}++export class GameHud {+ constructor(opts = {}) {+ this.opts = opts;+ this.snapshot = null; // latest quest snapshot+ this.inv = []; // local player's backpack slots+ this.bank = []; // bank contents+ this.hotbarSlots = [];+ this.activeSlot = -1;+ this._questOpen = false;+ this._bankOpen = false;+ this._npcOpen = false;+ this._resetAt = 0;+ this._build();+ // One shared 1Hz ticker drives the live reset countdown wherever it shows.+ this._tick = this._tick.bind(this);+ this._timer = setInterval(this._tick, 1000);+ }++ // ---------------------------------------------------------------- build+ _build() {+ const root = el('div', 'kq-root');+ root.innerHTML = `+ <div id="kq-toolbar" class="kq-toolbar" hidden>+ <button id="kq-quest-btn" class="kq-tool-btn" type="button" aria-label="Quests (Q)" title="Quests (Q)">+ <span class="kq-tool-ic">📜</span><span class="kq-tool-lbl">Quests</span>+ <span id="kq-quest-dot" class="kq-dot" hidden></span>+ </button>+ <button id="kq-bank-btn" class="kq-tool-btn" type="button" aria-label="Open bank" title="Open bank" hidden>+ <span class="kq-tool-ic">🏦</span><span class="kq-tool-lbl">Bank</span>+ </button>+ </div>++ <div id="kq-hotbar" class="kq-hotbar" hidden role="toolbar" aria-label="Hotbar"></div>++ <aside id="kq-quests" class="kq-panel" hidden aria-label="Quests">+ <header class="kq-panel-head">+ <h2>Quests</h2>+ <button class="kq-x" id="kq-quests-x" type="button" aria-label="Close">✕</button>+ </header>+ <div class="kq-panel-body" id="kq-quests-body"></div>+ </aside>++ <div id="kq-npc" class="kq-modal" hidden>+ <div class="kq-modal-card kq-npc-card" role="dialog" aria-modal="true" aria-label="Conversation">+ <button class="kq-x" id="kq-npc-x" type="button" aria-label="Close">✕</button>+ <div class="kq-npc-head"><span class="kq-npc-portrait">🧙</span><div><div class="kq-npc-name" id="kq-npc-name">Aldric the Guide</div><div class="kq-npc-role">Mainland Guide</div></div></div>+ <p class="kq-npc-line" id="kq-npc-line"></p>+ <div class="kq-npc-body" id="kq-npc-body"></div>+ <button class="kq-btn kq-btn-ghost" id="kq-npc-quests" type="button">Open quest log</button>+ </div>+ </div>++ <div id="kq-bank" class="kq-modal" hidden>+ <div class="kq-modal-card kq-bank-card" role="dialog" aria-modal="true" aria-label="Bank">+ <button class="kq-x" id="kq-bank-x" type="button" aria-label="Close">✕</button>+ <header class="kq-bank-head"><span class="kq-tool-ic">🏦</span><h2>Bank</h2><span class="kq-bank-hint">Click an item to move it</span></header>+ <div class="kq-bank-cols">+ <section class="kq-bank-col"><h3>Backpack</h3><div class="kq-grid" id="kq-bank-inv"></div></section>+ <section class="kq-bank-col"><h3>Stored</h3><div class="kq-grid" id="kq-bank-store"></div></section>+ </div>+ </div>+ </div>+ `;+ document.body.appendChild(root);+ this.root = root;+ this.elToolbar = root.querySelector('#kq-toolbar');+ this.elQuestBtn = root.querySelector('#kq-quest-btn');+ this.elQuestDot = root.querySelector('#kq-quest-dot');+ this.elBankBtn = root.querySelector('#kq-bank-btn');+ this.elHotbar = root.querySelector('#kq-hotbar');+ this.elQuests = root.querySelector('#kq-quests');+ this.elQuestsBody = root.querySelector('#kq-quests-body');+ this.elNpc = root.querySelector('#kq-npc');+ this.elNpcName = root.querySelector('#kq-npc-name');+ this.elNpcLine = root.querySelector('#kq-npc-line');+ this.elNpcBody = root.querySelector('#kq-npc-body');+ this.elBank = root.querySelector('#kq-bank');+ this.elBankInv = root.querySelector('#kq-bank-inv');+ this.elBankStore = root.querySelector('#kq-bank-store');++ this.elQuestBtn.addEventListener('click', () => this.toggleQuests());+ root.querySelector('#kq-quests-x').addEventListener('click', () => this.closeQuests());+ this.elBankBtn.addEventListener('click', () => { this.opts.onBankOpen?.(); this.openBank(); });+ root.querySelector('#kq-bank-x').addEventListener('click', () => this.closeBank());+ root.querySelector('#kq-npc-x').addEventListener('click', () => this.closeNpc());+ root.querySelector('#kq-npc-quests').addEventListener('click', () => { this.closeNpc(); this.openQuests(); });+ // Click the backdrop (outside the card) to dismiss modals.+ this.elNpc.addEventListener('click', (e) => { if (e.target === this.elNpc) this.closeNpc(); });+ this.elBank.addEventListener('click', (e) => { if (e.target === this.elBank) this.closeBank(); });+ }++ // Reveal the toolbar + hotbar once the player is in the world.+ enterWorld() {+ this.elToolbar.hidden = false;+ this.elHotbar.hidden = false;+ }++ // ---------------------------------------------------------------- hotbar+ setHotbar(slots, activeSlot) {+ this.hotbarSlots = slots || [];+ this.activeSlot = activeSlot;+ this._renderHotbar();+ }++ _renderHotbar() {+ const frag = document.createDocumentFragment();+ for (let i = 0; i < this.hotbarSlots.length; i++) {+ const s = this.hotbarSlots[i] || { item: '', qty: 0 };+ const active = i === this.activeSlot;+ const slot = el('button', 'kq-slot' + (active ? ' kq-slot--active' : '') + (s.item ? '' : ' kq-slot--empty'));+ slot.type = 'button';+ slot.setAttribute('aria-label', s.item ? `${itemMeta(s.item).label} (slot ${i + 1})` : `Empty slot ${i + 1}`);+ slot.setAttribute('aria-pressed', String(active));+ slot.innerHTML =+ `<span class="kq-key">${i + 1}</span>` ++ (s.item ? `<span class="kq-ic">${itemMeta(s.item).icon}</span>` : '') ++ (s.item && s.qty > 1 ? `<span class="kq-qty">${s.qty}</span>` : '');+ slot.addEventListener('click', () => this.opts.onEquip?.(i));+ frag.appendChild(slot);+ }+ this.elHotbar.replaceChildren(frag);+ }++ // ---------------------------------------------------------------- quests+ setQuests(snapshot) {+ this.snapshot = snapshot || null;+ this._resetAt = snapshot?.daily?.resetAt || 0;+ this._renderQuestDot();+ if (this._questOpen) this._renderQuests();+ if (this._npcOpen) this._renderNpc();+ }++ // A pulsing dot on the Quests button when there's something to do: tutorial in+ // progress, or a daily finished and waiting to be claimed.+ _renderQuestDot() {+ this.elQuestDot.hidden = !this._hasActionableQuest();+ }++ _hasActionableQuest() {+ const s = this.snapshot;+ if (!s) return false;+ if (s.tutorial && !s.tutorial.done) return true;+ return (s.daily?.quests || []).some((q) => q.progress >= q.count && !q.claimed);+ }++ // True when a daily is finished and unclaimed — drives Aldric's "?" marker.+ hasTurnInReady() {+ return (this.snapshot?.daily?.quests || []).some((q) => q.progress >= q.count && !q.claimed);+ }++ tutorialActive() {+ return !!(this.snapshot?.tutorial && !this.snapshot.tutorial.done);+ }++ toggleQuests() { this._questOpen ? this.closeQuests() : this.openQuests(); }+ openQuests() { this._questOpen = true; this.elQuests.hidden = false; this.elQuests.classList.add('kq-in'); this._renderQuests(); }+ closeQuests() { this._questOpen = false; this.elQuests.classList.remove('kq-in'); this.elQuests.hidden = true; }++ _renderQuests() {+ const s = this.snapshot;+ const body = this.elQuestsBody;+ if (!s) { body.replaceChildren(el('p', 'kq-empty', 'Loading your quests…')); return; }+ const frag = document.createDocumentFragment();++ // Tutorial section.+ const tut = s.tutorial || {};+ const tutWrap = el('section', 'kq-section');+ if (tut.done) {+ tutWrap.appendChild(el('h3', 'kq-h3', 'Tutorial'));+ tutWrap.appendChild(el('div', 'kq-tut-done', '🎓 Training complete — you know the ropes.'));+ } else if (tut.step) {+ tutWrap.appendChild(el('h3', 'kq-h3', `Tutorial · step ${tut.stepIndex + 1} of ${tut.total}`));+ const card = el('div', 'kq-card-q kq-card-tut');+ card.appendChild(el('div', 'kq-q-title', tut.step.title));+ card.appendChild(el('div', 'kq-q-desc', tut.step.desc));+ if (tut.step.count > 1) card.appendChild(this._bar(tut.progress, tut.step.count));+ tutWrap.appendChild(card);+ }+ frag.appendChild(tutWrap);++ // Daily section.+ const daily = s.daily || { quests: [] };+ const dWrap = el('section', 'kq-section');+ const head = el('div', 'kq-daily-head');+ head.appendChild(el('h3', 'kq-h3', 'Daily quests'));+ const reset = el('span', 'kq-reset');+ reset.id = 'kq-reset-q';+ reset.textContent = this._resetText();+ head.appendChild(reset);+ dWrap.appendChild(head);++ const allClaimed = daily.quests.length > 0 && daily.quests.every((q) => q.claimed);+ if (allClaimed) {+ const done = el('div', 'kq-empty kq-empty-good');+ done.innerHTML = `🌟 All dailies complete — back tomorrow.<br><span class="kq-reset-inline">${this._resetText()}</span>`;+ dWrap.appendChild(done);+ }+ for (const q of daily.quests) dWrap.appendChild(this._questCard(q));+ frag.appendChild(dWrap);++ // Badges.+ const badges = s.badges || [];+ const bWrap = el('section', 'kq-section');+ bWrap.appendChild(el('h3', 'kq-h3', 'Badges'));+ if (badges.length) {+ const row = el('div', 'kq-badges');+ for (const b of badges) {+ const chip = el('span', 'kq-badge', `<span class="kq-badge-ic">${b.icon}</span>${b.label}`);+ chip.title = b.desc || b.label;+ row.appendChild(chip);+ }+ bWrap.appendChild(row);+ } else {+ bWrap.appendChild(el('p', 'kq-empty', 'No badges yet — clear daily quests to earn them.'));+ }+ frag.appendChild(bWrap);++ body.replaceChildren(frag);+ }++ _questCard(q) {+ const complete = q.progress >= q.count;+ const card = el('div', 'kq-card-q' + (q.claimed ? ' kq-claimed' : complete ? ' kq-ready' : ''));+ card.appendChild(el('div', 'kq-q-title', q.title));+ card.appendChild(el('div', 'kq-q-desc', q.desc));+ card.appendChild(this._bar(q.progress, q.count));+ const footer = el('div', 'kq-q-foot');+ footer.appendChild(this._rewardChips(q.reward));+ if (q.claimed) {+ footer.appendChild(el('span', 'kq-claimed-tag', '✓ Claimed'));+ } else {+ const btn = el('button', 'kq-btn kq-turnin' + (complete ? '' : ' kq-btn-disabled'), complete ? 'Turn in' : `${q.progress}/${q.count}`);+ btn.type = 'button';+ btn.disabled = !complete;+ btn.addEventListener('click', () => this.opts.onTurnIn?.(q.id));+ footer.appendChild(btn);+ }+ card.appendChild(footer);+ return card;+ }++ _bar(progress, count) {+ const pct = count > 0 ? Math.max(0, Math.min(1, progress / count)) : 0;+ const wrap = el('div', 'kq-progress');+ wrap.innerHTML = `<i style="width:${(pct * 100).toFixed(1)}%"></i><span class="kq-progress-txt">${Math.min(progress, count)} / ${count}</span>`;+ return wrap;+ }++ _rewardChips(reward) {+ const row = el('div', 'kq-rewards');+ if (!reward) return row;+ if (reward.gold) row.appendChild(el('span', 'kq-rw', `🪙 ${reward.gold}`));+ if (reward.xp) {+ for (const [skill, amt] of Object.entries(reward.xp)) {+ row.appendChild(el('span', 'kq-rw', `✦ ${amt} ${SKILL_LABEL[skill] || skill}`));+ }+ }+ if (reward.item) row.appendChild(el('span', 'kq-rw', `${itemMeta(reward.item.id).icon} ${reward.item.qty}`));+ if (reward.badge) {+ const chip = el('span', 'kq-rw kq-rw-badge', `${reward.badge.icon} ${reward.badge.label}`);+ chip.title = `Badge: ${reward.badge.label}`;+ row.appendChild(chip);+ }+ return row;+ }++ _resetText() {+ return this._resetAt ? `Resets in ${fmtCountdown(this._resetAt - Date.now())}` : '';+ }++ // ---------------------------------------------------------------- NPC dialog+ openNpc(name) {+ this._npcOpen = true;+ if (name) this.elNpcName.textContent = name;+ this.elNpc.hidden = false;+ this._renderNpc();+ }+ closeNpc() { this._npcOpen = false; this.elNpc.hidden = true; }++ _renderNpc() {+ const s = this.snapshot;+ this.elNpcLine.textContent = s?.guide || '…';+ const frag = document.createDocumentFragment();++ // Current tutorial objective, phrased as the guide's instruction.+ if (s?.tutorial && !s.tutorial.done && s.tutorial.step) {+ const obj = el('div', 'kq-npc-objective');+ obj.innerHTML = `<span class="kq-npc-obj-label">Your task</span>${s.tutorial.step.title}<span class="kq-npc-obj-desc">${s.tutorial.step.desc}</span>`;+ frag.appendChild(obj);+ }++ // Any daily ready to be turned in, with a claim button right here.+ const ready = (s?.daily?.quests || []).filter((q) => q.progress >= q.count && !q.claimed);+ if (ready.length) {+ frag.appendChild(el('div', 'kq-npc-sub', 'Bounties ready to settle'));+ for (const q of ready) {+ const row = el('div', 'kq-npc-turnin');+ row.appendChild(el('span', 'kq-npc-turnin-name', q.title));+ const btn = el('button', 'kq-btn kq-turnin', 'Claim');+ btn.type = 'button';+ btn.addEventListener('click', () => this.opts.onTurnIn?.(q.id));+ row.appendChild(btn);+ frag.appendChild(row);+ }+ }+ this.elNpcBody.replaceChildren(frag);+ }++ // ---------------------------------------------------------------- bank+ setBankAvailable(available) {+ this.elBankBtn.hidden = !available;+ if (!available && this._bankOpen) this.closeBank();+ }+ setInventory(inv) { this.inv = inv || []; if (this._bankOpen) this._renderBank(); }+ setBank(slots) { this.bank = slots || []; if (this._bankOpen) this._renderBank(); }++ openBank() { this._bankOpen = true; this.elBank.hidden = false; this._renderBank(); }+ closeBank() { this._bankOpen = false; this.elBank.hidden = true; }++ _renderBank() {+ // Backpack (deposit on click).+ const invFrag = document.createDocumentFragment();+ let invItems = 0;+ this.inv.forEach((s, i) => {+ if (!s || !s.item) return;+ invItems++;+ invFrag.appendChild(this._bankCell(s, () => this.opts.onDeposit?.(i)));+ });+ if (!invItems) invFrag.appendChild(el('p', 'kq-empty', 'Your backpack is empty.'));+ this.elBankInv.replaceChildren(invFrag);++ // Stored (withdraw on click).+ const stFrag = document.createDocumentFragment();+ let stItems = 0;+ this.bank.forEach((s, i) => {+ if (!s || !s.item) return;+ stItems++;+ stFrag.appendChild(this._bankCell(s, () => this.opts.onWithdraw?.(i)));+ });+ if (!stItems) stFrag.appendChild(el('p', 'kq-empty', 'Nothing stored yet.'));+ this.elBankStore.replaceChildren(stFrag);+ }++ _bankCell(slot, onClick) {+ const m = itemMeta(slot.item);+ const cell = el('button', 'kq-cell');+ cell.type = 'button';+ cell.title = m.label;+ cell.setAttribute('aria-label', `${m.label}${slot.qty > 1 ? ' ×' + slot.qty : ''}`);+ cell.innerHTML = `<span class="kq-ic">${m.icon}</span>${slot.qty > 1 ? `<span class="kq-qty">${slot.qty}</span>` : ''}`;+ cell.addEventListener('click', onClick);+ return cell;+ }++ // ---------------------------------------------------------------- ticker+ _tick() {+ if (!this._resetAt) return;+ const remaining = this._resetAt - Date.now();+ if (remaining <= 0) { this.opts.onReset?.(); return; }+ if (this._questOpen) {+ const q = this.elQuestsBody.querySelector('#kq-reset-q');+ if (q) q.textContent = this._resetText();+ const inline = this.elQuestsBody.querySelector('.kq-reset-inline');+ if (inline) inline.textContent = this._resetText();+ }+ }++ destroy() {+ clearInterval(this._timer);+ this.root?.remove();+ }+}diff --git a/src/game/game-net.js b/src/game/game-net.jsindex edc6f5bd8..5f75a05a0 100644--- a/src/game/game-net.js+++ b/src/game/game-net.js@@ -10,7 +10,8 @@import { Client, getStateCallbacks } from 'colyseus.js';-const ROOM_NAME = 'game_mainland';+const REALMS = ['mainland', 'wilderness', 'whisperwood', 'pond'];+const DEFAULT_REALM = 'mainland';const RECONNECT_BASE_MS = 3000;const RECONNECT_MAX_MS = 60_000;const MAX_RECONNECT_ATTEMPTS = 6;@@ -44,6 +45,12 @@ export class GameNet {constructor(opts = {}) {this.name = opts.name || 'guest';this.avatar = opts.avatar || ''; // loadable GLB/VRM URL or path; '' = default+ this.pid = opts.pid || ''; // stable account id (wallet / persistent guest) — keys persistence+ // One Colyseus room definition per realm (game_mainland, game_wilderness,+ // …). Each realm is its own instance, so players in different realms never+ // see or affect one another. Defaults to Mainland.+ this.realm = REALMS.includes(opts.realm) ? opts.realm : DEFAULT_REALM;+ this.roomName = `game_${this.realm}`;this.url = opts.url || defaultServerUrl();this.client = null;this.room = null;@@ -53,8 +60,14 @@ export class GameNet {this._handlers = {status: new Set(),realm: new Set(), // (layout)+ items: new Set(), // (registry) — server item catalogue: icons, labels, mount tuningnotice: new Set(), // ({kind, text})+ chat: new Set(), // ({id, name, text, ts}) player msg | ({system, kind, text, ts}) system/command replybank: new Set(), // ({slots})+ skills: new Set(), // ({cap, skills, total, average}) — requester's own XP detail+ levelup: new Set(), // ({skill, level}) — a skill the local player just raised+ died: new Set(), // ({realm, danger, respawnAt, dropped, byName}) — local death+ cooked: new Set(), // ({cooked, burned, level}) — result of a cook action at the Roast PitplayerAdd: new Set(), // (player, id)playerChange: new Set(), // (player, id)playerRemove: new Set(), // (id)@@ -64,6 +77,10 @@ export class GameNet {mobAdd: new Set(),mobChange: new Set(),mobRemove: new Set(),+ tombAdd: new Set(), // (tombstone, id)+ tombChange: new Set(), // (tombstone, id)+ tombRemove: new Set(), // (id)+ quests: new Set(), // ({tutorial, daily, badges, guide, npc}) — requester's own quest snapshot};this._reconnectTimer = null;this._reconnectAttempts = 0;@@ -94,12 +111,19 @@ export class GameNet {this._setStatus('connecting');try {this.client = new Client(this.url);- this.room = await this.client.joinOrCreate(ROOM_NAME, { name: this.name, avatar: this.avatar });+ this.room = await this.client.joinOrCreate(this.roomName, { name: this.name, avatar: this.avatar, pid: this.pid });this.sessionId = this.room.sessionId;this.room.onMessage('realm', (layout) => this._emit('realm', layout));+ this.room.onMessage('items', (r) => this._emit('items', r));this.room.onMessage('notice', (n) => this._emit('notice', n));+ this.room.onMessage('chat', (m) => this._emit('chat', m));this.room.onMessage('bank', (b) => this._emit('bank', b));+ this.room.onMessage('skills', (s) => this._emit('skills', s));+ this.room.onMessage('levelup', (l) => this._emit('levelup', l));+ this.room.onMessage('died', (d) => this._emit('died', d));+ this.room.onMessage('cooked', (c) => this._emit('cooked', c));+ this.room.onMessage('quests', (q) => this._emit('quests', q));const $ = getStateCallbacks(this.room);const wire = (mapName, addEv, changeEv, removeEv) => {@@ -112,6 +136,7 @@ export class GameNet {wire('players', 'playerAdd', 'playerChange', 'playerRemove');wire('nodes', 'nodeAdd', 'nodeChange', 'nodeRemove');wire('mobs', 'mobAdd', 'mobChange', 'mobRemove');+ wire('tombstones', 'tombAdd', 'tombChange', 'tombRemove');this.room.onLeave((code) => {this._setStatus('offline');@@ -151,13 +176,28 @@ export class GameNet {step(tx, ty, yaw) { this.room?.send('step', { tx, ty, yaw }); }setAvatar(url) { this.avatar = url; this.room?.send('setAvatar', { avatar: url }); }+ chat(text) { this.room?.send('chat', { text }); }gather(id) { this.room?.send('gather', { id }); }attack(id) { this.room?.send('attack', { id }); }+ fish() { this.room?.send('fish'); }+ tombLoot(id) { this.room?.send('tombLoot', { id }); }+ cook(qty = 1) { this.room?.send('cook', { qty }); }+ consume(ref) { this.room?.send('consume', { slot: ref }); }invMove(from, to) { this.room?.send('invMove', { from, to }); }equip(slot) { this.room?.send('equip', { slot }); }bankOpen() { this.room?.send('bankOpen'); }+ skills() { this.room?.send('skills'); }bankDeposit(i, qty) { this.room?.send('bankDeposit', { i, qty }); }bankWithdraw(i, qty) { this.room?.send('bankWithdraw', { i, qty }); }+ // Quests: request a fresh snapshot, talk to an NPC, claim a finished daily.+ questOpen() { this.room?.send('questOpen'); }+ npcTalk(id) { this.room?.send('npcTalk', { id }); }+ questTurnIn(id) { this.room?.send('questTurnIn', { id }); }+ // Mounts (Task 09): ride the active hotbar item if it's a mount, leave the+ // saddle, and a generic slash-command channel (Task 13 chat forwards here).+ use(slot) { this.room?.send('use', slot == null ? {} : { slot }); }+ dismount() { this.room?.send('dismount'); }+ command(text) { this.room?.send('command', { text }); }get state() { return this.room?.state ?? null; }diff --git a/src/game/iso-controls.js b/src/game/iso-controls.jsnew file mode 100644index 000000000..ea01b24b8--- /dev/null+++ b/src/game/iso-controls.js@@ -0,0 +1,817 @@+// Controls layer for the isometric MMO (/game) — the hotbar, the panel toggles+// (inventory · map · build · friends), and the rebindable Controls settings UI.+//+// This module is the single home for discrete keyboard input. It owns one+// capture-phase keydown listener that routes every game action through the+// central keybinding map (keybindings.js) instead of scattered key literals, so+// any action can be rebound and the binding persists per account. Movement+// (WASD / arrows) stays a held-key set inside iso-game.js; this layer never+// touches it — when a pressed key isn't a bound action it lets the event flow+// through to the renderer untouched.+//+// It attaches to the live IsoGame instance (window.__ISO__) and subscribes to the+// network bus directly (game.net.on('playerChange', …)) for the local player's+// hotbar / inventory / active slot. That keeps the renderer (which is large and+// evolving) free of UI-coupling: this file is self-contained and self-mounting.++import { Keybindings, ACTIONS, normalizeKey, keyLabel } from './keybindings.js';+import { itemDisplay } from './items.js';++const HOTBAR = 6;+const INV = 24;++// Designed placeholders for panels whose owning task hasn't landed yet. The key+// is never dead: it opens this surface, and the owning task fills the body.+const PLACEHOLDERS = {+ build: {+ title: 'Build',+ glyph: '🛠️',+ blurb: 'Place a firepit and raise a shack to claim a corner of the world.',+ note: 'Building arrives with Task 07.',+ },+ friends: {+ title: 'Friends',+ glyph: '👥',+ blurb: 'Send requests, see who’s online, and message friends directly.',+ note: 'Friends arrive with Task 15.',+ },+};++// Tiny DOM helper (mirrors the el() convention used elsewhere in src/game).+function el(tag, attrs = {}, kids = []) {+ const n = document.createElement(tag);+ for (const [k, v] of Object.entries(attrs)) {+ if (v == null || v === false) continue;+ if (k === 'class') n.className = v;+ else if (k === 'text') n.textContent = v;+ else if (k === 'html') n.innerHTML = v;+ else if (k === 'dataset') Object.assign(n.dataset, v);+ else if (k.startsWith('on') && typeof v === 'function')+ n.addEventListener(k.slice(2).toLowerCase(), v);+ else if (v === true) n.setAttribute(k, '');+ else n.setAttribute(k, v);+ }+ for (const c of [].concat(kids)) {+ if (c == null || c === false) continue;+ n.append(c.nodeType ? c : document.createTextNode(String(c)));+ }+ return n;+}++export class IsoControls {+ constructor(game) {+ this.game = game;+ this.kb = new Keybindings(localStorage.getItem('cc-name') || '');++ // Local-player mirror, fed by the network bus.+ this._hotbar = Array.from({ length: HOTBAR }, () => ({ item: '', qty: 0 }));+ this._inv = Array.from({ length: INV }, () => ({ item: '', qty: 0 }));+ this._activeSlot = -1;+ this._gold = 0;+ this._me = null;++ this._open = []; // stack of open surface keys (top = last)+ this._surfaces = {}; // key -> { overlay, card, body }+ this._capture = null; // { id, chip } while rebinding+ this._lastFocus = null; // restore target when a surface closes+ this._mapTimer = null;+ this._netBound = false;++ this._onKeyDown = this._onKeyDown.bind(this);+ this._sync = this._sync.bind(this);+ }++ // -------------------------------------------------------------- mount+ mount() {+ if (this._mounted) return;+ this._mounted = true;++ this._buildHotbar();+ this._buildGear();++ window.addEventListener('keydown', this._onKeyDown, true);+ this._unsub = this.kb.subscribe(() => this._onBindingsChanged());++ // Poll for the network connection + phase changes. Cheap (5Hz) and only+ // needs to wire the net bus once; visibility follows game.phase.+ this._syncTimer = setInterval(this._sync, 200);+ this._sync();+ }++ _sync() {+ const game = this.game;+ if (game.net && !this._netBound) {+ this._netBound = true;+ this.kb.setAccount(localStorage.getItem('cc-name') || '');+ game.net.on('playerAdd', (p, id) => this._onPlayer(p, id));+ game.net.on('playerChange', (p, id) => this._onPlayer(p, id));+ }+ // A reconnect builds a fresh GameNet; rebind against the new bus.+ if (game.net && this._boundNet && this._boundNet !== game.net) {+ this._netBound = false;+ }+ this._boundNet = game.net || this._boundNet;+ this._applyPhase(game.phase);+ }++ _applyPhase(phase) {+ const world = phase === 'world';+ if (this._hotbarEl) this._hotbarEl.hidden = !world;+ if (this._gearEl) this._gearEl.hidden = !world;+ if (world && !this._hintDone) {+ this._updateHint();+ this._hintDone = true;+ }+ if (!world && this._open.length) this._closeAll();+ }++ // -------------------------------------------------------------- network+ _onPlayer(p, id) {+ const myId = this.game.myId || this.game.net?.sessionId;+ if (!myId || id !== myId) return;+ const read = (arr, n) =>+ Array.from({ length: n }, (_, i) => ({+ item: arr?.[i]?.item || '',+ qty: arr?.[i]?.qty | 0,+ }));+ this._hotbar = read(p.hotbar, HOTBAR);+ this._inv = read(p.inv, INV);+ if (typeof p.activeSlot === 'number') this._activeSlot = p.activeSlot;+ this._gold = p.gold | 0;+ this._me = { tx: p.tx | 0, ty: p.ty | 0 };+ this._renderHotbar();+ if (this._isOpen('inv')) this._renderInv();+ }++ // -------------------------------------------------------------- hotbar+ _buildHotbar() {+ const slots = [];+ for (let i = 0; i < HOTBAR; i++) {+ const slot = el(+ 'button',+ {+ class: 'kg-hb-slot',+ type: 'button',+ dataset: { slot: String(i) },+ onclick: () => this._select(i),+ },+ [+ el('span', { class: 'kg-hb-key', 'aria-hidden': 'true' }),+ el('span', { class: 'kg-hb-glyph', 'aria-hidden': 'true' }),+ el('span', { class: 'kg-hb-qty', 'aria-hidden': 'true' }),+ ],+ );+ slots.push(slot);+ }+ this._hbSlots = slots;+ this._hotbarEl = el(+ 'div',+ {+ id: 'kg-hotbar',+ class: 'kg-hotbar',+ role: 'toolbar',+ 'aria-label': 'Hotbar',+ hidden: true,+ },+ slots,+ );+ document.body.appendChild(this._hotbarEl);+ this._renderHotbar();+ }++ _renderHotbar() {+ if (!this._hbSlots) return;+ for (let i = 0; i < HOTBAR; i++) {+ const btn = this._hbSlots[i];+ const cell = this._hotbar[i] || { item: '', qty: 0 };+ const disp = itemDisplay(cell.item);+ const active = i === this._activeSlot;+ const keyTxt = keyLabel(this.kb.get('hotbar' + (i + 1)));+ btn.querySelector('.kg-hb-key').textContent = keyTxt;+ btn.querySelector('.kg-hb-glyph').textContent = disp ? disp.glyph : '';+ btn.querySelector('.kg-hb-qty').textContent = cell.qty > 1 ? String(cell.qty) : '';+ btn.classList.toggle('kg-hb--active', active);+ btn.classList.toggle('kg-hb--empty', !cell.item);+ btn.setAttribute('aria-pressed', String(active));+ const name = disp ? disp.name : 'empty';+ btn.setAttribute(+ 'aria-label',+ `Hotbar ${i + 1} (${keyTxt}): ${name}${active ? ', selected' : ''}`,+ );+ btn.title = `${name} — press ${keyTxt}`;+ }+ }++ // Select hotbar slot `i` (0-5); pass -1 to clear. Selecting is idempotent so+ // 1–6 always *set* the active slot per the world-guide spec; 0 clears.+ _select(i) {+ const net = this.game.net;+ if (!net) return;+ this._activeSlot = i;+ net.equip(i);+ this._renderHotbar();+ }++ // -------------------------------------------------------------- gear button+ _buildGear() {+ this._gearEl = el(+ 'button',+ {+ id: 'kg-controls-btn',+ class: 'kg-iconbtn',+ type: 'button',+ hidden: true,+ 'aria-haspopup': 'dialog',+ 'aria-controls': 'kg-ov-settings',+ 'aria-label': 'Controls and settings',+ title: 'Controls',+ onclick: () => this._toggle('settings'),+ },+ '⚙',+ );+ const bar = document.getElementById('kg-topbar');+ const status = document.getElementById('kg-status');+ if (bar && status) bar.insertBefore(this._gearEl, status);+ else if (bar) bar.appendChild(this._gearEl);+ else document.body.appendChild(this._gearEl);+ }++ // -------------------------------------------------------------- keyboard+ _onKeyDown(e) {+ if (this._capture) {+ e.preventDefault();+ e.stopImmediatePropagation();+ this._applyCapture(e);+ return;+ }++ const key = normalizeKey(e.key);+ const a = document.activeElement;+ const onButton = a && a.tagName === 'BUTTON' && a.closest && a.closest('.kg-ov');++ // While a controls surface is open, the modal owns the keyboard: Esc closes,+ // Enter confirms (unless a control is focused, then it activates it), Tab+ // navigates, and every other key is swallowed so the avatar can't walk or+ // switch slots beneath the dialog.+ if (this._open.length) {+ if (key === this.kb.get('closeModal')) {+ e.preventDefault();+ e.stopImmediatePropagation();+ this._closeTop();+ return;+ }+ if (key === this.kb.get('confirm')) {+ if (onButton) {+ e.stopImmediatePropagation();+ return;+ }+ e.preventDefault();+ e.stopImmediatePropagation();+ this._confirmTop();+ return;+ }+ if (key === 'tab') {+ e.stopImmediatePropagation();+ return;+ }+ if (onButton && key === 'space') {+ e.stopImmediatePropagation();+ return;+ }+ e.preventDefault();+ e.stopImmediatePropagation();+ return;+ }++ if (this._isTyping()) return; // chat / name inputs own their keys+ if (this.game.phase !== 'world') return;++ const action = this.kb.actionFor(key);+ if (!action || action === 'closeModal' || action === 'confirm') return;++ e.preventDefault();+ e.stopImmediatePropagation();+ this._dispatch(action);+ }++ _dispatch(action) {+ if (action.startsWith('hotbar') && action !== 'hotbarClear') {+ this._select(Number(action.slice(6)) - 1);+ return;+ }+ switch (action) {+ case 'hotbarClear':+ this._select(-1);+ break;+ case 'inventory':+ this._toggle('inv');+ break;+ case 'map':+ this._toggle('map');+ break;+ case 'build':+ this._toggle('build');+ break;+ case 'friends':+ this._toggle('friends');+ break;+ case 'chat':+ this.game._openChat?.();+ break;+ case 'skills':+ this.game._toggleSkills?.();+ break;+ case 'rotateCam':+ this._rotateCamera();+ break;+ default:+ break;+ }+ }++ // Snap the follow camera 45° (matches the fixed three-quarter read). camYaw is+ // the renderer's public orbit angle, consumed every frame by _placeCamera.+ _rotateCamera() {+ this.game.camYaw = (this.game.camYaw || 0) - Math.PI / 4;+ }++ _isTyping() {+ const a = document.activeElement;+ return !!(a && (a.tagName === 'INPUT' || a.tagName === 'TEXTAREA' || a.isContentEditable));+ }++ // -------------------------------------------------------------- surfaces+ _isOpen(key) {+ return this._open.includes(key);+ }++ _toggle(key) {+ this._isOpen(key) ? this._close(key) : this._openSurface(key);+ }++ _openSurface(key) {+ // Single-panel policy: opening one closes the others (and the skills drawer)+ // so the screen never stacks competing dialogs.+ for (const k of [...this._open]) if (k !== key) this._close(k);+ this.game._toggleSkills?.(false);++ const surf = this._ensureSurface(key);+ if (!surf) return;+ this._lastFocus = document.activeElement;+ surf.overlay.hidden = false;+ // reflow so the fade/scale transition runs+ void surf.overlay.offsetWidth;+ surf.overlay.classList.add('kg-ov--in');+ this._open.push(key);+ this._renderSurface(key);+ if (key === 'map') this._mapTimer = setInterval(() => this._renderMap(), 700);+ (surf.card.querySelector('button, [tabindex]') || surf.card).focus();+ }++ _close(key) {+ const surf = this._surfaces[key];+ if (!surf) return;+ surf.overlay.classList.remove('kg-ov--in');+ surf.overlay.hidden = true;+ this._open = this._open.filter((k) => k !== key);+ if (key === 'map' && this._mapTimer) {+ clearInterval(this._mapTimer);+ this._mapTimer = null;+ }+ if (this._capture && key === 'settings') this._capture = null;+ const back = this._lastFocus;+ if (back && document.contains(back)) back.focus();+ else this._gearEl?.focus();+ }++ _closeTop() {+ if (this._open.length) this._close(this._open[this._open.length - 1]);+ }+ _closeAll() {+ for (const k of [...this._open]) this._close(k);+ }++ _confirmTop() {+ const key = this._open[this._open.length - 1];+ const surf = this._surfaces[key];+ surf?.card.querySelector('.kg-ov-primary')?.click();+ }++ _ensureSurface(key) {+ if (this._surfaces[key]) return this._surfaces[key];+ const titles = { inv: 'Inventory', map: 'Map', settings: 'Controls' };+ const title = titles[key] || PLACEHOLDERS[key]?.title || key;+ const closeBtn = el(+ 'button',+ {+ class: 'kg-ov-x',+ type: 'button',+ 'aria-label': 'Close',+ onclick: () => this._close(key),+ },+ '✕',+ );+ const head = el('div', { class: 'kg-ov-head' }, [+ el('h2', { class: 'kg-ov-title', id: `kg-ov-title-${key}` }, title),+ closeBtn,+ ]);+ const body = el('div', { class: 'kg-ov-body' });+ const card = el(+ 'div',+ {+ class: 'kg-ov-card',+ role: 'dialog',+ 'aria-modal': 'true',+ 'aria-labelledby': `kg-ov-title-${key}`,+ tabindex: '-1',+ },+ [head, body],+ );+ const overlay = el(+ 'div',+ {+ id: `kg-ov-${key}`,+ class: 'kg-ov',+ hidden: true,+ onclick: (e) => {+ if (e.target === overlay) this._close(key);+ },+ },+ [card],+ );+ document.body.appendChild(overlay);+ this._surfaces[key] = { overlay, card, body };+ return this._surfaces[key];+ }++ _renderSurface(key) {+ if (key === 'inv') this._renderInv();+ else if (key === 'map') this._renderMap();+ else if (key === 'settings') this._renderControls();+ else this._renderPlaceholder(key);+ }++ // -------------------------------------------------------------- inventory+ _renderInv() {+ const body = this._surfaces.inv?.body;+ if (!body) return;+ body.innerHTML = '';+ body.append(+ el('div', { class: 'kg-inv-meta' }, [+ el('span', {}, [el('b', {}, String(this._gold)), ' gold']),+ el('span', { class: 'kg-inv-hint' }, 'Slots 1–6 are your hotbar.'),+ ]),+ );+ const grid = el('div', { class: 'kg-inv-grid' });+ const filled = this._inv.some((s) => s.item);+ for (let i = 0; i < INV; i++) {+ const cell = this._inv[i] || { item: '', qty: 0 };+ const disp = itemDisplay(cell.item);+ const node = el(+ 'div',+ {+ class:+ 'kg-inv-cell' ++ (i < HOTBAR ? ' kg-inv-cell--hb' : '') ++ (cell.item ? '' : ' kg-inv-cell--empty'),+ title: disp ? disp.name : '',+ 'aria-label': disp+ ? `${disp.name}${cell.qty > 1 ? ` ×${cell.qty}` : ''}`+ : 'Empty slot',+ },+ [+ el(+ 'span',+ { class: 'kg-inv-glyph', 'aria-hidden': 'true' },+ disp ? disp.glyph : '',+ ),+ cell.qty > 1 ? el('span', { class: 'kg-inv-qty' }, String(cell.qty)) : null,+ ],+ );+ grid.append(node);+ }+ body.append(grid);+ if (!filled) {+ body.append(+ el(+ 'p',+ { class: 'kg-ov-empty' },+ 'Your backpack is empty. Gather wood and stone, or defeat mobs to fill it.',+ ),+ );+ }+ }++ // -------------------------------------------------------------- map+ _renderMap() {+ let surf = this._surfaces.map;+ if (!surf) return;+ if (!surf._canvas) {+ const cv = el('canvas', {+ class: 'kg-map-canvas',+ width: '260',+ height: '260',+ role: 'img',+ 'aria-label': 'Realm map',+ });+ const legend = el('div', { class: 'kg-map-legend' }, [+ el('span', {}, [el('i', { class: 'kg-map-dot kg-map-dot--me' }), 'You']),+ el('span', {}, [el('i', { class: 'kg-map-dot kg-map-dot--peer' }), 'Players']),+ el('span', {}, [el('i', { class: 'kg-map-sw kg-map-sw--bank' }), 'Bank']),+ el('span', {}, [el('i', { class: 'kg-map-sw kg-map-sw--block' }), 'Blocked']),+ ]);+ surf.body.append(cv, legend);+ surf._canvas = cv;+ }+ const cv = surf._canvas;+ const realm = this.game.realm;+ const ctx = cv.getContext('2d');+ const SZ = cv.width;+ ctx.clearRect(0, 0, SZ, SZ);+ if (!realm) {+ ctx.fillStyle = '#95a1b6';+ ctx.font = '13px system-ui';+ ctx.textAlign = 'center';+ ctx.fillText('Map loads when you enter the world.', SZ / 2, SZ / 2);+ return;+ }+ const grid = realm.grid || 48;+ const s = SZ / grid;+ ctx.fillStyle = '#33492b';+ ctx.fillRect(0, 0, SZ, SZ);+ ctx.fillStyle = 'rgba(8,11,16,0.55)';+ for (const b of realm.blocked || [])+ ctx.fillRect(b.x0 * s, b.y0 * s, (b.x1 - b.x0 + 1) * s, (b.y1 - b.y0 + 1) * s);+ ctx.fillStyle = 'rgba(255,206,92,0.6)';+ for (const t of realm.bankZone || []) ctx.fillRect(t.tx * s, t.ty * s, s, s);+ if (realm.fountain) {+ ctx.fillStyle = '#3aa0d0';+ ctx.beginPath();+ ctx.arc(+ (realm.fountain.tx + 0.5) * s,+ (realm.fountain.ty + 0.5) * s,+ Math.max(2.5, s * 0.7),+ 0,+ Math.PI * 2,+ );+ ctx.fill();+ }+ for (const [, pv] of this.game.players || []) {+ if (pv.dead) continue;+ const me = pv.isLocal;+ ctx.fillStyle = me ? '#ffffff' : '#8fd3ff';+ const r = Math.max(me ? 2.6 : 1.9, s * (me ? 0.75 : 0.55));+ ctx.beginPath();+ ctx.arc((pv.tx + 0.5) * s, (pv.ty + 0.5) * s, r, 0, Math.PI * 2);+ ctx.fill();+ if (me) {+ ctx.strokeStyle = '#0d1420';+ ctx.lineWidth = 1.5;+ ctx.stroke();+ }+ }+ }++ // -------------------------------------------------------------- placeholder+ _renderPlaceholder(key) {+ const meta = PLACEHOLDERS[key];+ const body = this._surfaces[key]?.body;+ if (!meta || !body) return;+ body.innerHTML = '';+ body.append(+ el('div', { class: 'kg-ph' }, [+ el('div', { class: 'kg-ph-glyph', 'aria-hidden': 'true' }, meta.glyph),+ el('p', { class: 'kg-ph-blurb' }, meta.blurb),+ el('p', { class: 'kg-ph-note' }, meta.note),+ ]),+ );+ body.append(+ el('div', { class: 'kg-ov-foot' }, [+ el(+ 'button',+ {+ class: 'kg-ov-btn kg-ov-primary',+ type: 'button',+ onclick: () => this._close(key),+ },+ 'Got it',+ ),+ ]),+ );+ }++ // -------------------------------------------------------------- controls UI+ _renderControls() {+ const body = this._surfaces.settings?.body;+ if (!body) return;+ body.innerHTML = '';+ body.append(+ el(+ 'p',+ { class: 'kg-ov-sub' },+ 'Click a key to rebind it, then press the new key. Esc cancels. Esc and Enter are reserved.',+ ),+ );++ const conflicts = new Map();+ for (const { key, ids } of this.kb.allConflicts()) conflicts.set(key, ids);++ const groups = [];+ for (const a of ACTIONS) {+ let g = groups.find((x) => x.name === a.group);+ if (!g) {+ g = { name: a.group, items: [] };+ groups.push(g);+ }+ g.items.push(a);+ }++ for (const g of groups) {+ const rows = [];+ for (const action of g.items) {+ const cur = this.kb.get(action.id);+ const sharedIds = (conflicts.get(cur) || []).filter((id) => id !== action.id);+ const chip = action.fixed+ ? el(+ 'span',+ {+ class: 'kg-bind-chip kg-bind-chip--fixed',+ title: 'System key (cannot be rebound)',+ },+ keyLabel(cur),+ )+ : el(+ 'button',+ {+ class: 'kg-bind-chip',+ type: 'button',+ dataset: { action: action.id },+ 'aria-label': `Rebind ${action.label}, currently ${keyLabel(cur)}`,+ onclick: (e) => this._beginCapture(action.id, e.currentTarget),+ },+ keyLabel(cur),+ );+ const row = el(+ 'div',+ { class: 'kg-bind-row' + (sharedIds.length ? ' kg-bind-row--conflict' : '') },+ [el('span', { class: 'kg-bind-label' }, action.label), chip],+ );+ if (sharedIds.length) {+ const names = sharedIds+ .map((id) => ACTIONS.find((x) => x.id === id)?.label || id)+ .join(', ');+ row.append(+ el(+ 'span',+ { class: 'kg-bind-warn', role: 'note' },+ `⚠ shared with ${names}`,+ ),+ );+ }+ rows.push(row);+ }+ body.append(+ el('section', { class: 'kg-bind-group' }, [+ el('h3', { class: 'kg-bind-h' }, g.name),+ ...rows,+ ]),+ );+ }++ this._msgEl = el(+ 'p',+ { class: 'kg-bind-msg', role: 'status', 'aria-live': 'polite' },+ this._pendingMsg || '',+ );+ this._pendingMsg = '';+ body.append(this._msgEl);+ body.append(+ el('div', { class: 'kg-ov-foot' }, [+ el(+ 'button',+ {+ class: 'kg-ov-btn kg-ov-ghost',+ type: 'button',+ onclick: () => this._resetBindings(),+ },+ 'Reset to defaults',+ ),+ el(+ 'button',+ {+ class: 'kg-ov-btn kg-ov-primary',+ type: 'button',+ onclick: () => this._close('settings'),+ },+ 'Done',+ ),+ ]),+ );+ }++ _beginCapture(id, chip) {+ this._capture = { id, chip };+ chip.classList.add('kg-bind-chip--capturing');+ chip.textContent = 'Press a key…';+ this._setMsg(`Press a key for “${ACTIONS.find((a) => a.id === id)?.label}”. Esc cancels.`);+ }++ _applyCapture(e) {+ const { id } = this._capture;+ const key = normalizeKey(e.key);+ this._capture = null;+ if (key === 'escape' || key === 'tab') {+ this._setMsg('Rebind cancelled.');+ this._renderControls();+ this._focusChip(id);+ return;+ }+ const res = this.kb.set(id, key);+ if (!res.ok) {+ const reasons = {+ fixed: 'That action can’t be rebound.',+ reserved: 'Esc and Enter are reserved.',+ empty: 'Unrecognized key.',+ unknown: 'Unknown action.',+ };+ this._setMsg(reasons[res.reason] || 'Could not bind that key.');+ } else if (res.conflicts.length) {+ const names = res.conflicts+ .map((c) => ACTIONS.find((a) => a.id === c)?.label || c)+ .join(', ');+ this._setMsg(`Bound to ${keyLabel(key)} — also used by ${names}.`);+ } else {+ this._setMsg(`Bound to ${keyLabel(key)}.`);+ }+ this._renderControls();+ this._focusChip(id);+ }++ _focusChip(id) {+ this._surfaces.settings?.body.querySelector(`.kg-bind-chip[data-action="${id}"]`)?.focus();+ }++ _setMsg(text) {+ this._pendingMsg = text;+ if (this._msgEl) this._msgEl.textContent = text;+ }++ _resetBindings() {+ this.kb.reset();+ this._setMsg('Restored default controls.');+ this._renderControls();+ }++ _onBindingsChanged() {+ this._renderHotbar();+ this._updateHint();+ if (this._isOpen('settings')) {+ const msg = this._pendingMsg;+ this._renderControls();+ if (msg) this._setMsg(msg);+ }+ }++ _updateHint() {+ const hint = document.getElementById('kg-hint');+ if (!hint) return;+ const kl = (id) => keyLabel(this.kb.get(id));+ hint.innerHTML =+ `<kbd>WASD</kbd> move · <kbd>${kl('hotbar1')}</kbd>–<kbd>${kl('hotbar6')}</kbd> hotbar · ` ++ `<kbd>${kl('inventory')}</kbd> bag · <kbd>${kl('map')}</kbd> map · ` ++ `<kbd>${kl('skills')}</kbd> skills · <kbd>${kl('chat')}</kbd> chat · <kbd>⚙</kbd> controls`;+ }++ // -------------------------------------------------------------- teardown+ destroy() {+ window.removeEventListener('keydown', this._onKeyDown, true);+ clearInterval(this._syncTimer);+ if (this._mapTimer) clearInterval(this._mapTimer);+ this._unsub?.();+ this._hotbarEl?.remove();+ this._gearEl?.remove();+ for (const k of Object.keys(this._surfaces)) this._surfaces[k].overlay.remove();+ this._surfaces = {};+ this._mounted = false;+ }+}++// Self-mount onto the live game instance. iso-game.js creates window.__ISO__ at+// module load; we poll briefly to cover either load order, then attach once.+function boot() {+ const attach = () => {+ const game = window.__ISO__;+ if (!game) return false;+ if (game.__controls) return true;+ game.__controls = new IsoControls(game);+ game.__controls.mount();+ return true;+ };+ if (attach()) return;+ const t = setInterval(() => {+ if (attach()) clearInterval(t);+ }, 120);+ setTimeout(() => clearInterval(t), 30000);+}++if (typeof window !== 'undefined') boot();diff --git a/src/game/iso-game.css b/src/game/iso-game.cssindex 03fe5b56e..c13b97392 100644--- a/src/game/iso-game.css+++ b/src/game/iso-game.css@@ -11,128 +11,2203 @@--kg-accent: #cdd6e6;}-* { box-sizing: border-box; }-html, body {- margin: 0; height: 100%; overflow: hidden;- background: var(--kg-bg); color: var(--kg-text);- font-family: system-ui, -apple-system, "Segoe UI", sans-serif;- -webkit-font-smoothing: antialiased; overscroll-behavior: none;+* {+ box-sizing: border-box;+}+html,+body {+ margin: 0;+ height: 100%;+ overflow: hidden;+ background: var(--kg-bg);+ color: var(--kg-text);+ font-family:+ system-ui,+ -apple-system,+ 'Segoe UI',+ sans-serif;+ -webkit-font-smoothing: antialiased;+ overscroll-behavior: none;+}+#kg-canvas {+ position: fixed;+ inset: 0;+ width: 100%;+ height: 100%;+ display: block;+ touch-action: none;+}+body.kg-loading-cursor {+ cursor: progress;}-#kg-canvas { position: fixed; inset: 0; width: 100%; height: 100%; display: block; touch-action: none; }-body.kg-loading-cursor { cursor: progress; }/* DOM layer for projected nameplates (pointer-transparent). */-#kg-labels { position: fixed; inset: 0; pointer-events: none; overflow: hidden; z-index: 5; }+#kg-labels {+ position: fixed;+ inset: 0;+ pointer-events: none;+ overflow: hidden;+ z-index: 5;+}.kg-label {- position: absolute; top: 0; left: 0; will-change: transform;- display: flex; flex-direction: column; align-items: center; gap: 3px;- font-size: 12px; font-weight: 600; letter-spacing: 0.01em;+ position: absolute;+ top: 0;+ left: 0;+ will-change: transform;+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 3px;+ font-size: 12px;+ font-weight: 600;+ letter-spacing: 0.01em;text-shadow: 0 1px 3px rgba(0, 0, 0, 0.8);}.kg-label-name {- padding: 1px 7px; border-radius: 6px;- background: rgba(13, 20, 32, 0.66); border: 1px solid var(--kg-line);- white-space: nowrap; max-width: 160px; overflow: hidden; text-overflow: ellipsis;+ padding: 1px 7px;+ border-radius: 6px;+ background: rgba(13, 20, 32, 0.66);+ border: 1px solid var(--kg-line);+ white-space: nowrap;+ max-width: 160px;+ overflow: hidden;+ text-overflow: ellipsis;+}+.kg-label--me .kg-label-name {+ background: rgba(40, 52, 74, 0.82);+ border-color: rgba(255, 255, 255, 0.28);}-.kg-label--me .kg-label-name { background: rgba(40, 52, 74, 0.82); border-color: rgba(255, 255, 255, 0.28); }.kg-hp {- width: 46px; height: 4px; border-radius: 3px; overflow: hidden;- background: rgba(0, 0, 0, 0.55); border: 1px solid rgba(0, 0, 0, 0.4);- opacity: 0; transition: opacity 0.2s;+ width: 46px;+ height: 4px;+ border-radius: 3px;+ overflow: hidden;+ background: rgba(0, 0, 0, 0.55);+ border: 1px solid rgba(0, 0, 0, 0.4);+ opacity: 0;+ transition: opacity 0.2s;+}+.kg-label.kg-hurt .kg-hp {+ opacity: 1;+}+.kg-hp i {+ display: block;+ height: 100%;+ width: 100%;+ background: linear-gradient(90deg, #6ee787, #d7ff7a);+ transition: width 0.2s ease;}-.kg-label.kg-hurt .kg-hp { opacity: 1; }-.kg-hp i { display: block; height: 100%; width: 100%; background: linear-gradient(90deg, #6ee787, #d7ff7a); transition: width 0.2s ease; }/* Top bar: realm + online + connection status. */#kg-topbar {- position: fixed; top: 0; left: 0; right: 0; z-index: 8;- display: flex; align-items: center; gap: 14px;- padding: 10px 16px; pointer-events: none;+ position: fixed;+ top: 0;+ left: 0;+ right: 0;+ z-index: 8;+ display: flex;+ align-items: center;+ gap: 14px;+ padding: 10px 16px;+ pointer-events: none;background: linear-gradient(180deg, rgba(8, 12, 20, 0.7), transparent);}-#kg-realm { font-weight: 700; font-size: 15px; letter-spacing: 0.02em; }-.kg-stat { font-size: 12px; color: var(--kg-dim); display: inline-flex; align-items: center; gap: 5px; }-.kg-stat b { color: var(--kg-text); font-weight: 700; }+#kg-realm {+ font-weight: 700;+ font-size: 15px;+ letter-spacing: 0.02em;+}+.kg-stat {+ font-size: 12px;+ color: var(--kg-dim);+ display: inline-flex;+ align-items: center;+ gap: 5px;+}+.kg-stat b {+ color: var(--kg-text);+ font-weight: 700;+}#kg-status {- margin-left: auto; pointer-events: auto;- font-size: 11px; text-transform: uppercase; letter-spacing: 0.08em;- padding: 4px 10px; border-radius: 999px;- background: rgba(255, 255, 255, 0.06); border: 1px solid var(--kg-line); color: var(--kg-dim);+ margin-left: auto;+ pointer-events: auto;+ font-size: 11px;+ text-transform: uppercase;+ letter-spacing: 0.08em;+ padding: 4px 10px;+ border-radius: 999px;+ background: rgba(255, 255, 255, 0.06);+ border: 1px solid var(--kg-line);+ color: var(--kg-dim);+}+#kg-status[data-status='online'] {+ color: #6ee787;+ border-color: rgba(110, 231, 135, 0.4);+}+#kg-status[data-status='connecting'] {+ color: #ffce5c;+ border-color: rgba(255, 206, 92, 0.4);+}+#kg-status[data-status='offline'],+#kg-status[data-status='failed'] {+ color: #ff8a8a;+ border-color: rgba(255, 138, 138, 0.4);}-#kg-status[data-status="online"] { color: #6ee787; border-color: rgba(110, 231, 135, 0.4); }-#kg-status[data-status="connecting"] { color: #ffce5c; border-color: rgba(255, 206, 92, 0.4); }-#kg-status[data-status="offline"], #kg-status[data-status="failed"] { color: #ff8a8a; border-color: rgba(255, 138, 138, 0.4); }/* Controls hint (bottom). */#kg-hint {- position: fixed; bottom: 14px; left: 50%; transform: translateX(-50%); z-index: 7;- font-size: 12px; color: var(--kg-dim); pointer-events: none; text-align: center;- background: rgba(13, 20, 32, 0.5); padding: 6px 12px; border-radius: 8px; border: 1px solid var(--kg-line);+ position: fixed;+ bottom: 14px;+ left: 50%;+ transform: translateX(-50%);+ z-index: 7;+ font-size: 12px;+ color: var(--kg-dim);+ pointer-events: none;+ text-align: center;+ background: rgba(13, 20, 32, 0.5);+ padding: 6px 12px;+ border-radius: 8px;+ border: 1px solid var(--kg-line);}#kg-hint kbd {- font: inherit; font-weight: 700; color: var(--kg-text);- background: rgba(255, 255, 255, 0.08); border: 1px solid var(--kg-line);- border-radius: 4px; padding: 0 5px;+ font: inherit;+ font-weight: 700;+ color: var(--kg-text);+ background: rgba(255, 255, 255, 0.08);+ border: 1px solid var(--kg-line);+ border-radius: 4px;+ padding: 0 5px;}/* Toasts (server notices: gathered, killed, inventory full, …). */-#kg-toasts { position: fixed; top: 56px; left: 50%; transform: translateX(-50%); z-index: 9; display: flex; flex-direction: column; gap: 8px; align-items: center; pointer-events: none; }+#kg-toasts {+ position: fixed;+ top: 56px;+ left: 50%;+ transform: translateX(-50%);+ z-index: 9;+ display: flex;+ flex-direction: column;+ gap: 8px;+ align-items: center;+ pointer-events: none;+}.kg-toast {- padding: 8px 16px; border-radius: 10px; font-size: 13px; font-weight: 600;- background: var(--kg-panel); border: 1px solid var(--kg-line); color: var(--kg-text);- opacity: 0; transform: translateY(-8px); transition: opacity 0.3s, transform 0.3s;+ padding: 8px 16px;+ border-radius: 10px;+ font-size: 13px;+ font-weight: 600;+ background: var(--kg-panel);+ border: 1px solid var(--kg-line);+ color: var(--kg-text);+ opacity: 0;+ transform: translateY(-8px);+ transition:+ opacity 0.3s,+ transform 0.3s;box-shadow: 0 8px 28px rgba(0, 0, 0, 0.45);}-.kg-toast--in { opacity: 1; transform: translateY(0); }-.kg-toast--kill { border-color: rgba(110, 231, 135, 0.45); }-.kg-toast--full, .kg-toast--tool, .kg-toast--bank { border-color: rgba(255, 206, 92, 0.45); }+.kg-toast--in {+ opacity: 1;+ transform: translateY(0);+}+.kg-toast--kill {+ border-color: rgba(110, 231, 135, 0.45);+}+.kg-toast--full,+.kg-toast--tool,+.kg-toast--bank {+ border-color: rgba(255, 206, 92, 0.45);+}+.kg-toast--cook,+.kg-toast--eat {+ border-color: rgba(110, 231, 135, 0.45);+}+.kg-toast--burn {+ border-color: rgba(255, 122, 58, 0.5);+}+.kg-toast--fish {+ border-color: rgba(92, 182, 230, 0.5);+}++/* Contextual action bar (cook at a Roast Pit, eat to heal). Buttons reveal only+ when the action is actually possible; see _updateActions in iso-game.js. */+#kg-actions {+ position: fixed;+ left: 50%;+ bottom: 96px;+ transform: translateX(-50%);+ z-index: 8;+ display: flex;+ gap: 10px;+ align-items: center;+}+#kg-actions[hidden] {+ display: none;+}+.kg-action {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ cursor: pointer;+ padding: 10px 16px;+ font-size: 14px;+ font-weight: 700;+ color: var(--kg-text);+ background: var(--kg-panel);+ border: 1px solid var(--kg-line);+ border-radius: 12px;+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.45);+ backdrop-filter: blur(4px);+ transition:+ transform 0.08s ease,+ border-color 0.15s,+ opacity 0.15s;+}+.kg-action[hidden] {+ display: none;+}+.kg-action:hover {+ border-color: var(--kg-accent);+ transform: translateY(-1px);+}+.kg-action:active {+ transform: translateY(1px);+}+.kg-action:focus-visible {+ outline: 2px solid var(--kg-accent);+ outline-offset: 2px;+}+.kg-action-dot {+ width: 9px;+ height: 9px;+ border-radius: 50%;+ background: var(--kg-dim);+ box-shadow: 0 0 8px currentColor;+}+#kg-cook .kg-action-dot {+ background: #ff7a3a;+ color: #ff7a3a;+}+#kg-eat .kg-action-dot {+ background: #6ee787;+ color: #6ee787;+}+#kg-cast .kg-action-dot {+ background: #5cb6e6;+ color: #5cb6e6;+}+/* Cast is shown beside water even without a rod, so the player learns where to+ fish — muted + a help cursor signal it's gated until they hold a rod. */+.kg-action--muted {+ opacity: 0.6;+}+.kg-action--muted .kg-action-dot {+ background: var(--kg-dim);+ color: var(--kg-dim);+ box-shadow: none;+}+.kg-action--muted:hover {+ border-color: var(--kg-line);+ transform: none;+}+.kg-action--pulse {+ animation: kg-cook-pulse 0.7s ease;+}+@keyframes kg-cook-pulse {+ 0% {+ box-shadow:+ 0 10px 30px rgba(0, 0, 0, 0.45),+ 0 0 0 0 rgba(255, 122, 58, 0.55);+ }+ 60% {+ box-shadow:+ 0 10px 30px rgba(0, 0, 0, 0.45),+ 0 0 0 14px rgba(255, 122, 58, 0);+ }+ 100% {+ box-shadow:+ 0 10px 30px rgba(0, 0, 0, 0.45),+ 0 0 0 0 rgba(255, 122, 58, 0);+ }+}+/* Green heal flash on the local nameplate when eating. */+.kg-label.kg-heal {+ animation: kg-heal-flash 0.7s ease;+}+@keyframes kg-heal-flash {+ 0% {+ box-shadow: 0 0 0 0 rgba(110, 231, 135, 0);+ }+ 30% {+ box-shadow: 0 0 14px 4px rgba(110, 231, 135, 0.6);+ }+ 100% {+ box-shadow: 0 0 0 0 rgba(110, 231, 135, 0);+ }+}+@media (max-width: 480px) {+ #kg-actions {+ bottom: 128px;+ }+}/* Joystick zone (touch only). */-#kg-joystick { position: fixed; left: 0; bottom: 0; width: 180px; height: 200px; z-index: 6; }+#kg-joystick {+ position: fixed;+ left: 0;+ bottom: 0;+ width: 180px;+ height: 200px;+ z-index: 6;+}/* Start + offline overlays. */.kg-overlay {- position: fixed; inset: 0; z-index: 20;- display: flex; align-items: center; justify-content: center; padding: 24px;+ position: fixed;+ inset: 0;+ z-index: 20;+ display: flex;+ align-items: center;+ justify-content: center;+ padding: 24px;background: radial-gradient(120% 120% at 50% 30%, rgba(20, 28, 44, 0.55), rgba(8, 12, 20, 0.9));backdrop-filter: blur(2px);}-.kg-overlay[hidden] { display: none; }+.kg-overlay[hidden] {+ display: none;+}.kg-card {- width: 100%; max-width: 380px; text-align: center;- background: var(--kg-panel); border: 1px solid var(--kg-line); border-radius: 18px;- padding: 30px 26px; box-shadow: 0 24px 70px rgba(0, 0, 0, 0.55);+ width: 100%;+ max-width: 380px;+ text-align: center;+ background: var(--kg-panel);+ border: 1px solid var(--kg-line);+ border-radius: 18px;+ padding: 30px 26px;+ box-shadow: 0 24px 70px rgba(0, 0, 0, 0.55);+}+.kg-eyebrow {+ font-size: 11px;+ letter-spacing: 0.22em;+ text-transform: uppercase;+ color: var(--kg-dim);+}+.kg-title {+ font-size: 26px;+ font-weight: 800;+ margin: 8px 0 4px;+ letter-spacing: -0.01em;+}+.kg-sub {+ font-size: 14px;+ color: var(--kg-dim);+ line-height: 1.5;+ margin: 0 0 22px;+}+.kg-field {+ display: block;+ width: 100%;+ margin-bottom: 14px;}-.kg-eyebrow { font-size: 11px; letter-spacing: 0.22em; text-transform: uppercase; color: var(--kg-dim); }-.kg-title { font-size: 26px; font-weight: 800; margin: 8px 0 4px; letter-spacing: -0.01em; }-.kg-sub { font-size: 14px; color: var(--kg-dim); line-height: 1.5; margin: 0 0 22px; }-.kg-field { display: block; width: 100%; margin-bottom: 14px; }.kg-field input {- width: 100%; padding: 12px 14px; font-size: 15px;- background: rgba(0, 0, 0, 0.3); color: var(--kg-text);- border: 1px solid var(--kg-line); border-radius: 10px; outline: none; transition: border-color 0.15s;+ width: 100%;+ padding: 12px 14px;+ font-size: 15px;+ background: rgba(0, 0, 0, 0.3);+ color: var(--kg-text);+ border: 1px solid var(--kg-line);+ border-radius: 10px;+ outline: none;+ transition: border-color 0.15s;+}+.kg-field input:focus {+ border-color: var(--kg-accent);}-.kg-field input:focus { border-color: var(--kg-accent); }.kg-btn {- width: 100%; padding: 13px 18px; font-size: 15px; font-weight: 700; cursor: pointer;- background: var(--kg-text); color: #0d1420; border: 0; border-radius: 10px;- transition: transform 0.08s ease, opacity 0.15s;+ width: 100%;+ padding: 13px 18px;+ font-size: 15px;+ font-weight: 700;+ cursor: pointer;+ background: var(--kg-text);+ color: #0d1420;+ border: 0;+ border-radius: 10px;+ transition:+ transform 0.08s ease,+ opacity 0.15s;+}+.kg-btn:hover {+ opacity: 0.92;+}+.kg-btn:active {+ transform: translateY(1px);+}+.kg-btn:focus-visible {+ outline: 2px solid var(--kg-accent);+ outline-offset: 2px;+}+.kg-feats {+ display: flex;+ gap: 8px;+ justify-content: center;+ margin-top: 18px;+ flex-wrap: wrap;+}+.kg-feat {+ font-size: 11px;+ color: var(--kg-dim);+ border: 1px solid var(--kg-line);+ border-radius: 999px;+ padding: 4px 10px;}-.kg-btn:hover { opacity: 0.92; }-.kg-btn:active { transform: translateY(1px); }-.kg-btn:focus-visible { outline: 2px solid var(--kg-accent); outline-offset: 2px; }-.kg-feats { display: flex; gap: 8px; justify-content: center; margin-top: 18px; flex-wrap: wrap; }-.kg-feat { font-size: 11px; color: var(--kg-dim); border: 1px solid var(--kg-line); border-radius: 999px; padding: 4px 10px; }.kg-spinner {- width: 34px; height: 34px; margin: 4px auto 18px; border-radius: 50%;- border: 3px solid rgba(255, 255, 255, 0.15); border-top-color: var(--kg-text);+ width: 34px;+ height: 34px;+ margin: 4px auto 18px;+ border-radius: 50%;+ border: 3px solid rgba(255, 255, 255, 0.15);+ border-top-color: var(--kg-text);animation: kg-spin 0.8s linear infinite;}-@keyframes kg-spin { to { transform: rotate(360deg); } }+@keyframes kg-spin {+ to {+ transform: rotate(360deg);+ }+}++@media (max-width: 480px) {+ .kg-card {+ padding: 24px 20px;+ }+ .kg-title {+ font-size: 22px;+ }+}++/* ---------------------------------------------------------------- world chat+ Bottom-left panel. Collapsed by default (click-through, masked scrollback);+ focusing the input or pressing C/Enter opens it (full scrollback, mute UI). */+#kg-chat {+ position: fixed;+ left: 14px;+ bottom: 14px;+ z-index: 7;+ width: min(340px, calc(100vw - 28px));+ display: flex;+ flex-direction: column;+ gap: 6px;+ pointer-events: none; /* world stays clickable through the gaps; children opt back in */+ font-size: 13px;+}+#kg-chat[hidden] {+ display: none;+}++.kg-chat-head {+ display: none;+ align-items: center;+ justify-content: space-between;+ padding: 0 2px;+}+.kg-chat--open .kg-chat-head {+ display: flex;+}+.kg-chat-title {+ font-size: 11px;+ text-transform: uppercase;+ letter-spacing: 0.12em;+ color: var(--kg-dim);+ font-weight: 700;+}+.kg-chat-muted-btn {+ pointer-events: auto;+ cursor: pointer;+ font: inherit;+ font-size: 11px;+ color: var(--kg-dim);+ background: rgba(255, 255, 255, 0.05);+ border: 1px solid var(--kg-line);+ border-radius: 999px;+ padding: 2px 9px;+ transition:+ color 0.15s,+ border-color 0.15s;+}+.kg-chat-muted-btn:hover {+ color: var(--kg-text);+ border-color: var(--kg-accent);+}+.kg-chat-muted-btn b {+ color: var(--kg-text);+}+.kg-chat-muted-btn:focus-visible {+ outline: 2px solid var(--kg-accent);+ outline-offset: 2px;+}++.kg-chat-log {+ display: flex;+ flex-direction: column;+ gap: 3px;+ max-height: 132px;+ overflow-y: auto;+ overflow-x: hidden;+ padding: 2px 4px;+ pointer-events: none; /* collapsed: clicks fall through to the world */+ -webkit-mask-image: linear-gradient(180deg, transparent 0, #000 20px);+ mask-image: linear-gradient(180deg, transparent 0, #000 20px);+ scrollbar-width: thin;+ scrollbar-color: rgba(255, 255, 255, 0.2) transparent;+ transition: max-height 0.18s ease;+}+.kg-chat--open .kg-chat-log {+ max-height: 230px;+ pointer-events: auto;+ -webkit-mask-image: none;+ mask-image: none;+}+.kg-chat-log::-webkit-scrollbar {+ width: 7px;+}+.kg-chat-log::-webkit-scrollbar-thumb {+ background: rgba(255, 255, 255, 0.18);+ border-radius: 4px;+}++.kg-chat-line {+ line-height: 1.4;+ overflow-wrap: anywhere;+ text-shadow: 0 1px 3px rgba(0, 0, 0, 0.85);+ background: rgba(13, 20, 32, 0.42);+ border-radius: 7px;+ padding: 2px 8px;+ animation: kg-chat-in 0.18s ease;+}+.kg-chat--open .kg-chat-line {+ background: rgba(13, 20, 32, 0.66);+}+.kg-chat-line--muted {+ display: none;+}+@keyframes kg-chat-in {+ from {+ opacity: 0;+ transform: translateY(4px);+ }+}++.kg-chat-name {+ pointer-events: auto;+ cursor: pointer;+ font: inherit;+ font-weight: 700;+ color: var(--kg-accent);+ background: none;+ border: 0;+ padding: 0;+ margin-right: 5px;+ border-radius: 4px;+}+.kg-chat-name:hover {+ text-decoration: underline;+}+.kg-chat-name:focus-visible {+ outline: 2px solid var(--kg-accent);+ outline-offset: 1px;+}+.kg-chat-name--me {+ color: #d7ff7a;+ cursor: default;+}+.kg-chat-name--me:hover {+ text-decoration: none;+}+.kg-chat-text {+ color: var(--kg-text);+}++.kg-chat-line--system {+ background: rgba(40, 52, 74, 0.5);+}+.kg-chat-line--system .kg-chat-text {+ color: var(--kg-dim);+ white-space: pre-wrap;+ font-style: italic;+}+.kg-chat-line--error {+ background: rgba(120, 40, 40, 0.42);+}+.kg-chat-line--error .kg-chat-text {+ color: #ff9c9c;+ font-style: normal;+}++.kg-chat-form {+ display: flex;+}+.kg-chat-input {+ pointer-events: auto;+ width: 100%;+ padding: 8px 12px;+ font: inherit;+ font-size: 13px;+ color: var(--kg-text);+ background: rgba(13, 20, 32, 0.5);+ border: 1px solid var(--kg-line);+ border-radius: 9px;+ outline: none;+ opacity: 0.55;+ transition:+ opacity 0.15s,+ border-color 0.15s,+ background 0.15s;+}+.kg-chat-input::placeholder {+ color: var(--kg-dim);+}+.kg-chat--open .kg-chat-input,+.kg-chat-input:focus {+ opacity: 1;+ background: rgba(0, 0, 0, 0.45);+ border-color: var(--kg-accent);+}++/* Mute menu popover (click a sender's name). */+.kg-chat-menu {+ position: absolute;+ z-index: 9;+ pointer-events: auto;+ min-width: 140px;+ background: var(--kg-panel);+ border: 1px solid var(--kg-line);+ border-radius: 9px;+ padding: 4px;+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);+ animation: kg-chat-in 0.12s ease;+}+.kg-chat-menu-btn {+ display: block;+ width: 100%;+ text-align: left;+ cursor: pointer;+ font: inherit;+ font-size: 12px;+ color: var(--kg-text);+ background: none;+ border: 0;+ border-radius: 6px;+ padding: 7px 9px;+}+.kg-chat-menu-btn:hover {+ background: rgba(255, 255, 255, 0.08);+}+.kg-chat-menu-btn:focus-visible {+ outline: 2px solid var(--kg-accent);+ outline-offset: -2px;+}++/* Muted-players list (floats above the panel). */+.kg-chat-muted {+ position: absolute;+ left: 0;+ right: 0;+ bottom: calc(100% + 6px);+ z-index: 9;+ pointer-events: auto;+ background: var(--kg-panel);+ border: 1px solid var(--kg-line);+ border-radius: 10px;+ padding: 8px;+ box-shadow: 0 12px 34px rgba(0, 0, 0, 0.5);+ max-height: 220px;+ overflow-y: auto;+ animation: kg-chat-in 0.14s ease;+}+.kg-chat-muted[hidden] {+ display: none;+}+.kg-chat-muted-row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 10px;+ padding: 5px 4px;+}+.kg-chat-muted-name {+ color: var(--kg-text);+ font-weight: 600;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.kg-chat-unmute {+ cursor: pointer;+ font: inherit;+ font-size: 11px;+ font-weight: 700;+ color: #0d1420;+ background: var(--kg-text);+ border: 0;+ border-radius: 6px;+ padding: 4px 10px;+ transition: opacity 0.15s;+}+.kg-chat-unmute:hover {+ opacity: 0.88;+}+.kg-chat-unmute:focus-visible {+ outline: 2px solid var(--kg-accent);+ outline-offset: 2px;+}+.kg-chat-muted-empty {+ color: var(--kg-dim);+ font-size: 12px;+ text-align: center;+ padding: 10px 4px;+}++/* On touch the joystick owns the bottom-left corner — float chat above it. */+@media (pointer: coarse) {+ #kg-chat {+ bottom: 216px;+ width: min(300px, calc(100vw - 28px));+ }+ .kg-chat-log {+ max-height: 110px;+ }+}++/* ===========================================================================+ Skills — topbar toggle, slide-in panel, per-skill progress, level-up toast.+ =========================================================================== */++/* Topbar "Skills" toggle. Sits to the right; the status pill follows it. */+.kg-hud-btn {+ margin-left: auto;+ pointer-events: auto;+ cursor: pointer;+ display: inline-flex;+ align-items: center;+ gap: 6px;+ font-size: 12px;+ font-weight: 700;+ letter-spacing: 0.02em;+ padding: 5px 11px;+ border-radius: 999px;+ background: rgba(255, 255, 255, 0.06);+ border: 1px solid var(--kg-line);+ color: var(--kg-text);+ transition:+ background 0.15s,+ border-color 0.15s,+ transform 0.08s;+}+.kg-hud-btn:hover {+ background: rgba(255, 255, 255, 0.12);+ border-color: rgba(255, 255, 255, 0.28);+}+.kg-hud-btn:active {+ transform: translateY(1px);+}+.kg-hud-btn:focus-visible {+ outline: 2px solid var(--kg-accent);+ outline-offset: 2px;+}+.kg-hud-btn[aria-expanded='true'] {+ background: rgba(120, 150, 220, 0.22);+ border-color: rgba(150, 180, 255, 0.45);+}+.kg-hud-ico {+ width: 15px;+ height: 15px;+ fill: none;+ stroke: currentColor;+ stroke-width: 2;+ stroke-linecap: round;+ stroke-linejoin: round;+}+/* Keep the status pill grouped with the toggle (override its margin-left:auto). */+#kg-status {+ margin-left: 12px;+}++/* Slide-in panel, right edge. */+.kg-skills {+ position: fixed;+ top: 0;+ right: 0;+ bottom: 0;+ z-index: 12;+ width: min(340px, 88vw);+ display: flex;+ flex-direction: column;+ background: var(--kg-panel);+ border-left: 1px solid var(--kg-line);+ box-shadow: -18px 0 50px rgba(0, 0, 0, 0.5);+ backdrop-filter: blur(6px);+ transform: translateX(100%);+ transition: transform 0.22s cubic-bezier(0.22, 1, 0.36, 1);+ will-change: transform;+}+.kg-skills.kg-skills--open {+ transform: translateX(0);+}+.kg-skills[hidden] {+ display: none;+}++.kg-skills-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 16px 18px 12px;+ border-bottom: 1px solid var(--kg-line);+}+.kg-skills-title {+ margin: 0;+ font-size: 16px;+ font-weight: 800;+ letter-spacing: 0.01em;+}+.kg-skills-close {+ display: inline-flex;+ padding: 6px;+ border-radius: 8px;+ cursor: pointer;+ background: transparent;+ border: 1px solid transparent;+ color: var(--kg-dim);+ transition:+ color 0.15s,+ background 0.15s,+ border-color 0.15s;+}+.kg-skills-close svg {+ width: 18px;+ height: 18px;+ fill: none;+ stroke: currentColor;+ stroke-width: 2;+ stroke-linecap: round;+}+.kg-skills-close:hover {+ color: var(--kg-text);+ background: rgba(255, 255, 255, 0.07);+ border-color: var(--kg-line);+}+.kg-skills-close:focus-visible {+ outline: 2px solid var(--kg-accent);+ outline-offset: 2px;+}++.kg-skills-summary {+ display: flex;+ gap: 10px;+ padding: 14px 18px 4px;+}+.kg-skills-sum {+ flex: 1;+ display: flex;+ flex-direction: column;+ gap: 2px;+ align-items: center;+ padding: 10px 8px;+ border-radius: 12px;+ background: rgba(255, 255, 255, 0.04);+ border: 1px solid var(--kg-line);+}+.kg-skills-sum-val {+ font-size: 22px;+ font-weight: 800;+ line-height: 1;+ font-variant-numeric: tabular-nums;+}+.kg-skills-sum-lbl {+ font-size: 10px;+ text-transform: uppercase;+ letter-spacing: 0.1em;+ color: var(--kg-dim);+}++.kg-skills-list {+ list-style: none;+ margin: 0;+ padding: 12px 14px;+ display: flex;+ flex-direction: column;+ gap: 8px;+ overflow-y: auto;+ flex: 1;+ scrollbar-width: thin;+ scrollbar-color: rgba(255, 255, 255, 0.2) transparent;+}+.kg-skills-loading {+ color: var(--kg-dim);+ font-size: 13px;+ text-align: center;+ padding: 28px 12px;+}++.kg-skill {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 11px 12px;+ border-radius: 12px;+ background: rgba(255, 255, 255, 0.03);+ border: 1px solid var(--kg-line);+ transition:+ border-color 0.15s,+ background 0.15s;+ animation: kg-skill-in 0.28s ease both;+}+.kg-skill:hover {+ background: rgba(255, 255, 255, 0.06);+ border-color: rgba(255, 255, 255, 0.2);+}+@keyframes kg-skill-in {+ from {+ opacity: 0;+ transform: translateY(6px);+ }+ to {+ opacity: 1;+ transform: none;+ }+}++.kg-skill-ico {+ flex: 0 0 36px;+ width: 36px;+ height: 36px;+ display: grid;+ place-items: center;+ border-radius: 10px;+ background: color-mix(in srgb, var(--kg-hue) 16%, transparent);+ border: 1px solid color-mix(in srgb, var(--kg-hue) 38%, transparent);+}+.kg-skill-ico svg {+ width: 20px;+ height: 20px;+ fill: none;+ stroke: var(--kg-hue);+ stroke-width: 1.9;+ stroke-linecap: round;+ stroke-linejoin: round;+}++.kg-skill-main {+ flex: 1;+ min-width: 0;+ display: flex;+ flex-direction: column;+ gap: 5px;+}+.kg-skill-top {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ gap: 8px;+}+.kg-skill-name {+ font-size: 13px;+ font-weight: 700;+ letter-spacing: 0.01em;+}+.kg-skill-lvl {+ font-size: 12px;+ color: var(--kg-dim);+ font-variant-numeric: tabular-nums;+ white-space: nowrap;+}+.kg-skill-lvl b {+ color: var(--kg-text);+ font-size: 15px;+ font-weight: 800;+}+.kg-skill-lvl i {+ font-style: normal;+ opacity: 0.6;+}+.kg-skill-lvl em {+ font-style: normal;+ font-size: 9px;+ font-weight: 800;+ letter-spacing: 0.08em;+ color: #0d1420;+ background: var(--kg-hue);+ border-radius: 4px;+ padding: 1px 4px;+ margin-right: 6px;+ vertical-align: 1px;+}++.kg-skill-bar {+ height: 7px;+ border-radius: 5px;+ overflow: hidden;+ background: rgba(0, 0, 0, 0.4);+ border: 1px solid rgba(0, 0, 0, 0.3);+}+.kg-skill-bar i {+ display: block;+ height: 100%;+ min-width: 0;+ border-radius: 5px;+ background: linear-gradient(90deg, color-mix(in srgb, var(--kg-hue) 65%, #fff), var(--kg-hue));+ box-shadow: 0 0 8px color-mix(in srgb, var(--kg-hue) 60%, transparent);+ transition: width 0.45s cubic-bezier(0.22, 1, 0.36, 1);+}+.kg-skill-xp {+ font-size: 11px;+ color: var(--kg-dim);+ font-variant-numeric: tabular-nums;+}++/* Maxed skill: hue-tinted rim + a steady full bar. */+.kg-skill--max {+ border-color: color-mix(in srgb, var(--kg-hue) 45%, transparent);+ background: color-mix(in srgb, var(--kg-hue) 8%, transparent);+}+.kg-skill--max .kg-skill-xp {+ color: var(--kg-hue);+ font-weight: 700;+}+/* Fresh skill (level 1, no XP yet): the empty bar reads as a starting line. */+.kg-skill--fresh .kg-skill-xp {+ opacity: 0.8;+}++.kg-skills-foot {+ margin: 0;+ padding: 12px 18px 16px;+ font-size: 11px;+ color: var(--kg-dim);+ border-top: 1px solid var(--kg-line);+ text-align: center;+}+.kg-skills-foot b {+ color: var(--kg-text);+ font-weight: 700;+}++/* Level-up celebration toasts — driven by real server 'levelup' events. */+#kg-levelups {+ position: fixed;+ top: 22%;+ left: 50%;+ transform: translateX(-50%);+ z-index: 11;+ display: flex;+ flex-direction: column;+ gap: 10px;+ align-items: center;+ pointer-events: none;+}+.kg-levelup {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 12px 20px 12px 14px;+ border-radius: 14px;+ background: var(--kg-panel);+ border: 1px solid color-mix(in srgb, var(--kg-hue) 55%, var(--kg-line));+ box-shadow:+ 0 12px 40px rgba(0, 0, 0, 0.5),+ 0 0 26px color-mix(in srgb, var(--kg-hue) 35%, transparent);+ opacity: 0;+ transform: translateY(-10px) scale(0.92);+ transition:+ opacity 0.3s ease,+ transform 0.35s cubic-bezier(0.18, 1.4, 0.4, 1);+}+.kg-levelup--in {+ opacity: 1;+ transform: translateY(0) scale(1);+}+.kg-levelup-ico {+ flex: 0 0 40px;+ width: 40px;+ height: 40px;+ display: grid;+ place-items: center;+ border-radius: 11px;+ background: color-mix(in srgb, var(--kg-hue) 18%, transparent);+ border: 1px solid color-mix(in srgb, var(--kg-hue) 42%, transparent);+ animation: kg-levelup-pop 0.5s ease both;+}+.kg-levelup-ico svg {+ width: 22px;+ height: 22px;+ fill: none;+ stroke: var(--kg-hue);+ stroke-width: 1.9;+ stroke-linecap: round;+ stroke-linejoin: round;+}+@keyframes kg-levelup-pop {+ 0% {+ transform: scale(0.5) rotate(-12deg);+ }+ 60% {+ transform: scale(1.15) rotate(4deg);+ }+ 100% {+ transform: scale(1);+ }+}+.kg-levelup-txt {+ display: flex;+ flex-direction: column;+ gap: 1px;+}+.kg-levelup-kicker {+ font-size: 10px;+ font-weight: 800;+ letter-spacing: 0.14em;+ text-transform: uppercase;+ color: var(--kg-hue);+}+.kg-levelup-main {+ font-size: 15px;+ font-weight: 700;+}+.kg-levelup-main b {+ font-size: 18px;+ font-weight: 800;+}++@media (prefers-reduced-motion: reduce) {+ .kg-skills,+ .kg-skill,+ .kg-skill-bar i,+ .kg-levelup,+ .kg-levelup-ico {+ transition: none;+ animation: none;+ }+}++@media (max-width: 480px) {+ .kg-hud-btn span:not(.kg-hud-ico) {+ display: none;+ } /* icon-only on small screens */+ .kg-skills {+ width: min(360px, 94vw);+ }+ #kg-levelups {+ top: auto;+ bottom: 96px;+ }+}++/* --------------------------------------------------------------------------+ Death-bags (tombstones), the recovery panel, and the respawn overlay.+ Violet keys the "lootable death-bag" colour used by the tombstone mesh.+ -------------------------------------------------------------------------- */+:root {+ --kg-tomb: #ae7bff;+}++/* Floating tombstone label (owner + expiry countdown), projected each frame. */+.kg-tomblabel {+ position: absolute;+ top: 0;+ left: 0;+ will-change: transform;+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 2px;+ font-size: 11px;+ font-weight: 700;+ letter-spacing: 0.01em;+ text-shadow: 0 1px 3px rgba(0, 0, 0, 0.85);+ pointer-events: none;+}+.kg-tomb-name {+ padding: 1px 7px;+ border-radius: 6px;+ white-space: nowrap;+ background: rgba(26, 18, 40, 0.74);+ border: 1px solid rgba(174, 123, 255, 0.5);+ color: #e7ddff;+}+.kg-tomb-ttl {+ font-size: 10px;+ font-weight: 600;+ color: var(--kg-dim);+ background: rgba(13, 20, 32, 0.6);+ border-radius: 5px;+ padding: 0 5px;+}+.kg-tomblabel.kg-tomb-soon .kg-tomb-ttl {+ color: #ffce5c;+} /* grace window is open */++/* Recovery panel — bottom-centre, above the hint line. */+.kg-tomb-panel {+ position: fixed;+ left: 50%;+ bottom: 64px;+ transform: translateX(-50%) translateY(8px);+ z-index: 12;+ width: min(320px, 92vw);+ background: var(--kg-panel);+ border: 1px solid rgba(174, 123, 255, 0.35);+ border-radius: 14px;+ box-shadow: 0 18px 50px rgba(0, 0, 0, 0.55);+ padding: 12px 14px 14px;+ opacity: 0;+ transition:+ opacity 0.2s ease,+ transform 0.2s ease;+}+.kg-tomb-panel[hidden] {+ display: none;+}+.kg-tomb-panel--in {+ opacity: 1;+ transform: translateX(-50%) translateY(0);+}+.kg-tomb-head {+ display: flex;+ align-items: center;+ gap: 8px;+ margin-bottom: 10px;+}+.kg-tomb-owner {+ font-weight: 700;+ font-size: 14px;+ color: #e7ddff;+ flex: 1;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.kg-tomb-head .kg-tomb-ttl {+ background: none;+ padding: 0;+ font-size: 11px;+}+.kg-tomb-close {+ display: grid;+ place-items: center;+ width: 26px;+ height: 26px;+ flex: none;+ background: rgba(255, 255, 255, 0.06);+ border: 1px solid var(--kg-line);+ border-radius: 7px;+ color: var(--kg-dim);+ cursor: pointer;+ transition:+ color 0.15s,+ border-color 0.15s;+}+.kg-tomb-close:hover {+ color: var(--kg-text);+ border-color: var(--kg-accent);+}+.kg-tomb-close svg {+ width: 14px;+ height: 14px;+ fill: none;+ stroke: currentColor;+ stroke-width: 2;+ stroke-linecap: round;+}+.kg-tomb-close:focus-visible {+ outline: 2px solid var(--kg-accent);+ outline-offset: 2px;+}++.kg-tomb-items {+ display: flex;+ flex-direction: column;+ gap: 6px;+ max-height: 220px;+ overflow-y: auto;+ margin-bottom: 12px;+}+.kg-tomb-item {+ display: flex;+ align-items: center;+ gap: 9px;+ font-size: 13px;+ padding: 4px 2px;+}+.kg-tomb-chip {+ width: 14px;+ height: 14px;+ border-radius: 4px;+ background: var(--chip);+ border: 1px solid rgba(0, 0, 0, 0.35);+ flex: none;+}+.kg-tomb-iname {+ flex: 1;+ color: var(--kg-text);+}+.kg-tomb-iqty {+ color: var(--kg-dim);+ font-variant-numeric: tabular-nums;+ font-weight: 600;+}+.kg-tomb-empty {+ font-size: 13px;+ color: var(--kg-dim);+ text-align: center;+ padding: 14px 0;+}++.kg-tomb-take {+ width: 100%;+ padding: 10px 14px;+ font-size: 14px;+ font-weight: 700;+ cursor: pointer;+ background: var(--kg-tomb);+ color: #160c2a;+ border: 0;+ border-radius: 9px;+ transition:+ transform 0.08s ease,+ opacity 0.15s;+}+.kg-tomb-take:hover {+ opacity: 0.92;+}+.kg-tomb-take:active {+ transform: translateY(1px);+}+.kg-tomb-take:disabled {+ opacity: 0.4;+ cursor: not-allowed;+}+.kg-tomb-take:focus-visible {+ outline: 2px solid var(--kg-accent);+ outline-offset: 2px;+}++/* Respawn overlay — pointer-transparent vignette + centred status. */+.kg-death {+ position: fixed;+ inset: 0;+ z-index: 18;+ pointer-events: none;+ display: flex;+ align-items: center;+ justify-content: center;+ background: radial-gradient(120% 120% at 50% 45%, rgba(60, 8, 8, 0.32), rgba(8, 6, 10, 0.74));+ animation: kg-death-in 0.35s ease both;+}+.kg-death[hidden] {+ display: none;+}+@keyframes kg-death-in {+ from {+ opacity: 0;+ }+ to {+ opacity: 1;+ }+}+.kg-death-card {+ text-align: center;+ max-width: 360px;+ padding: 0 24px;+}+.kg-death-eyebrow {+ font-size: 12px;+ letter-spacing: 0.28em;+ text-transform: uppercase;+ color: #ff8a8a;+ font-weight: 700;+}+.kg-death-msg {+ font-size: 16px;+ color: var(--kg-text);+ line-height: 1.5;+ margin: 10px 0 16px;+ text-shadow: 0 2px 8px rgba(0, 0, 0, 0.7);+}+.kg-death-count {+ display: inline-block;+ font-size: 13px;+ font-weight: 700;+ letter-spacing: 0.04em;+ color: var(--kg-text);+ background: rgba(13, 20, 32, 0.7);+ border: 1px solid var(--kg-line);+ border-radius: 999px;+ padding: 7px 16px;+ font-variant-numeric: tabular-nums;+}++.kg-toast--tomb {+ border-color: rgba(174, 123, 255, 0.5);+}++@media (prefers-reduced-motion: reduce) {+ .kg-tomb-panel,+ .kg-tomb-take {+ transition: none;+ }+ .kg-death {+ animation: none;+ }+}++/* ===========================================================================+ Task 12 — Controls: topbar buttons, hotbar, panels (inventory / map /+ placeholders) and the rebindable Controls settings dialog. Uses the same+ token set as the rest of this file (--kg-panel / --kg-line / --kg-text / …).+ =========================================================================== */++/* Topbar icon buttons (skills, controls/gear). */+.kg-iconbtn {+ pointer-events: auto;+ cursor: pointer;+ font: inherit;+ font-size: 12px;+ font-weight: 700;+ line-height: 1;+ color: var(--kg-text);+ background: rgba(255, 255, 255, 0.06);+ border: 1px solid var(--kg-line);+ border-radius: 8px;+ padding: 6px 10px;+ transition:+ background 0.15s,+ border-color 0.15s,+ transform 0.08s;+}+.kg-iconbtn:hover {+ background: rgba(255, 255, 255, 0.12);+ border-color: var(--kg-accent);+}+.kg-iconbtn:active {+ transform: translateY(1px);+}+.kg-iconbtn:focus-visible {+ outline: 2px solid var(--kg-accent);+ outline-offset: 2px;+}+#kg-controls-btn {+ font-size: 15px;+ padding: 5px 9px;+}++/* Keep the bottom hint clear of the hotbar. */+#kg-hint {+ bottom: 96px;+}++/* --------------------------------------------------------------- hotbar --- */+.kg-hotbar {+ position: fixed;+ left: 50%;+ bottom: 16px;+ transform: translateX(-50%);+ z-index: 7;+ display: flex;+ gap: 8px;+ padding: 8px;+ background: rgba(13, 20, 32, 0.55);+ border: 1px solid var(--kg-line);+ border-radius: 14px;+ backdrop-filter: blur(6px);+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.4);+}+.kg-hotbar[hidden] {+ display: none;+}+.kg-hb-slot {+ position: relative;+ width: 56px;+ height: 56px;+ cursor: pointer;+ display: flex;+ align-items: center;+ justify-content: center;+ background: rgba(255, 255, 255, 0.05);+ border: 1px solid var(--kg-line);+ border-radius: 10px;+ color: var(--kg-text);+ transition:+ border-color 0.15s,+ background 0.15s,+ transform 0.08s;+}+.kg-hb-slot:hover {+ background: rgba(255, 255, 255, 0.1);+ border-color: var(--kg-accent);+}+.kg-hb-slot:active {+ transform: translateY(1px);+}+.kg-hb-slot:focus-visible {+ outline: 2px solid var(--kg-accent);+ outline-offset: 2px;+}+.kg-hb--active {+ border-color: #ffce5c;+ background: rgba(255, 206, 92, 0.16);+ box-shadow:+ 0 0 0 1px #ffce5c,+ 0 4px 16px rgba(255, 206, 92, 0.25);+}+.kg-hb--empty {+ color: var(--kg-dim);+ opacity: 0.8;+}+.kg-hb-key {+ position: absolute;+ top: 3px;+ left: 5px;+ font-size: 10px;+ font-weight: 700;+ color: var(--kg-dim);+ letter-spacing: 0.02em;+}+.kg-hb--active .kg-hb-key {+ color: #ffce5c;+}+.kg-hb-glyph {+ font-size: 26px;+ line-height: 1;+}+.kg-hb-qty {+ position: absolute;+ right: 4px;+ bottom: 3px;+ font-size: 11px;+ font-weight: 800;+ color: var(--kg-text);+ text-shadow: 0 1px 2px rgba(0, 0, 0, 0.8);+}++/* --------------------------------------------------------- modal overlays - */+.kg-ov {+ position: fixed;+ inset: 0;+ z-index: 24;+ display: flex;+ align-items: center;+ justify-content: center;+ padding: 24px;+ background: rgba(6, 10, 18, 0.62);+ backdrop-filter: blur(3px);+ opacity: 0;+ transition: opacity 0.18s;+}+.kg-ov[hidden] {+ display: none;+}+.kg-ov--in {+ opacity: 1;+}+.kg-ov-card {+ width: 100%;+ max-width: 460px;+ max-height: min(80vh, 640px);+ overflow: auto;+ background: var(--kg-panel);+ border: 1px solid var(--kg-line);+ border-radius: 16px;+ box-shadow: 0 24px 70px rgba(0, 0, 0, 0.6);+ transform: translateY(8px) scale(0.98);+ transition: transform 0.18s;+}+.kg-ov--in .kg-ov-card {+ transform: translateY(0) scale(1);+}+.kg-ov-card:focus {+ outline: none;+}+.kg-ov-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ padding: 16px 18px 12px;+ border-bottom: 1px solid var(--kg-line);+ position: sticky;+ top: 0;+ background: var(--kg-panel);+ z-index: 1;+}+.kg-ov-title {+ margin: 0;+ font-size: 17px;+ font-weight: 800;+ letter-spacing: -0.01em;+}+.kg-ov-x {+ cursor: pointer;+ font-size: 14px;+ line-height: 1;+ color: var(--kg-dim);+ background: transparent;+ border: 1px solid var(--kg-line);+ border-radius: 8px;+ padding: 6px 9px;+ transition:+ color 0.15s,+ border-color 0.15s;+}+.kg-ov-x:hover {+ color: var(--kg-text);+ border-color: var(--kg-accent);+}+.kg-ov-x:focus-visible {+ outline: 2px solid var(--kg-accent);+ outline-offset: 2px;+}+.kg-ov-body {+ padding: 16px 18px 18px;+}+.kg-ov-sub {+ margin: 0 0 14px;+ font-size: 12.5px;+ color: var(--kg-dim);+ line-height: 1.5;+}+.kg-ov-empty {+ margin: 14px 0 0;+ font-size: 13px;+ color: var(--kg-dim);+ line-height: 1.5;+ text-align: center;+}+.kg-ov-foot {+ display: flex;+ justify-content: flex-end;+ gap: 10px;+ margin-top: 18px;+}+.kg-ov-btn {+ cursor: pointer;+ font: inherit;+ font-size: 13px;+ font-weight: 700;+ padding: 9px 16px;+ border-radius: 9px;+ border: 1px solid var(--kg-line);+ background: rgba(255, 255, 255, 0.06);+ color: var(--kg-text);+ transition:+ background 0.15s,+ border-color 0.15s,+ transform 0.08s;+}+.kg-ov-btn:hover {+ background: rgba(255, 255, 255, 0.12);+ border-color: var(--kg-accent);+}+.kg-ov-btn:active {+ transform: translateY(1px);+}+.kg-ov-btn:focus-visible {+ outline: 2px solid var(--kg-accent);+ outline-offset: 2px;+}+.kg-ov-primary {+ background: var(--kg-text);+ color: #0d1420;+ border-color: var(--kg-text);+}+.kg-ov-primary:hover {+ opacity: 0.92;+ background: var(--kg-text);+}+.kg-ov-ghost {+ color: var(--kg-dim);+}++/* ----------------------------------------------------------- inventory --- */+.kg-inv-meta {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 10px;+ margin-bottom: 12px;+ font-size: 13px;+ color: var(--kg-dim);+}+.kg-inv-meta b {+ color: var(--kg-text);+}+.kg-inv-hint {+ font-size: 11px;+}+.kg-inv-grid {+ display: grid;+ grid-template-columns: repeat(6, 1fr);+ gap: 6px;+}+.kg-inv-cell {+ position: relative;+ aspect-ratio: 1;+ display: flex;+ align-items: center;+ justify-content: center;+ background: rgba(255, 255, 255, 0.05);+ border: 1px solid var(--kg-line);+ border-radius: 9px;+}+.kg-inv-cell--hb {+ border-color: rgba(255, 206, 92, 0.4);+}+.kg-inv-cell--empty {+ background: rgba(255, 255, 255, 0.02);+}+.kg-inv-glyph {+ font-size: 22px;+ line-height: 1;+}+.kg-inv-qty {+ position: absolute;+ right: 3px;+ bottom: 2px;+ font-size: 11px;+ font-weight: 800;+ text-shadow: 0 1px 2px rgba(0, 0, 0, 0.8);+}++/* ----------------------------------------------------------------- map --- */+.kg-map-canvas {+ display: block;+ width: 100%;+ max-width: 320px;+ height: auto;+ margin: 0 auto;+ border: 1px solid var(--kg-line);+ border-radius: 10px;+ image-rendering: pixelated;+ background: #1a2417;+}+.kg-map-legend {+ display: flex;+ flex-wrap: wrap;+ gap: 12px;+ justify-content: center;+ margin-top: 12px;+ font-size: 11px;+ color: var(--kg-dim);+}+.kg-map-legend span {+ display: inline-flex;+ align-items: center;+ gap: 5px;+}+.kg-map-dot {+ width: 9px;+ height: 9px;+ border-radius: 50%;+}+.kg-map-dot--me {+ background: #fff;+ border: 1.5px solid #0d1420;+}+.kg-map-dot--peer {+ background: #8fd3ff;+}+.kg-map-sw {+ width: 10px;+ height: 10px;+ border-radius: 2px;+}+.kg-map-sw--bank {+ background: rgba(255, 206, 92, 0.8);+}+.kg-map-sw--block {+ background: rgba(8, 11, 16, 0.7);+ border: 1px solid var(--kg-line);+}++/* --------------------------------------------------------- placeholders --- */+.kg-ph {+ text-align: center;+ padding: 14px 6px 6px;+}+.kg-ph-glyph {+ font-size: 44px;+ line-height: 1;+ margin-bottom: 12px;+}+.kg-ph-blurb {+ margin: 0 0 8px;+ font-size: 14px;+ color: var(--kg-text);+ line-height: 1.5;+}+.kg-ph-note {+ margin: 0;+ font-size: 12px;+ color: var(--kg-dim);+}++/* ----------------------------------------------------- controls (rebind) - */+.kg-bind-group {+ margin-bottom: 18px;+}+.kg-bind-h {+ margin: 0 0 8px;+ font-size: 11px;+ text-transform: uppercase;+ letter-spacing: 0.12em;+ color: var(--kg-dim);+}+.kg-bind-row {+ display: grid;+ grid-template-columns: 1fr auto;+ align-items: center;+ gap: 8px 12px;+ padding: 7px 0;+ border-bottom: 1px solid rgba(255, 255, 255, 0.05);+}+.kg-bind-row--conflict {+ /* warning lives on its own row span below */+}+.kg-bind-label {+ font-size: 13.5px;+ color: var(--kg-text);+}+.kg-bind-chip {+ min-width: 58px;+ cursor: pointer;+ font: inherit;+ font-size: 12px;+ font-weight: 700;+ padding: 6px 12px;+ border-radius: 7px;+ text-align: center;+ background: rgba(255, 255, 255, 0.06);+ border: 1px solid var(--kg-line);+ color: var(--kg-text);+ transition:+ background 0.15s,+ border-color 0.15s;+}+.kg-bind-chip:hover {+ background: rgba(255, 255, 255, 0.12);+ border-color: var(--kg-accent);+}+.kg-bind-chip:focus-visible {+ outline: 2px solid var(--kg-accent);+ outline-offset: 2px;+}+.kg-bind-chip--fixed {+ cursor: default;+ color: var(--kg-dim);+ opacity: 0.8;+}+.kg-bind-chip--fixed:hover {+ background: rgba(255, 255, 255, 0.06);+ border-color: var(--kg-line);+}+.kg-bind-chip--capturing {+ background: rgba(255, 206, 92, 0.18);+ border-color: #ffce5c;+ color: #ffce5c;+}+.kg-bind-warn {+ grid-column: 1 / -1;+ font-size: 11px;+ color: #ffce5c;+ margin-top: -2px;+}+.kg-bind-msg {+ min-height: 1.2em;+ margin: 6px 0 0;+ font-size: 12px;+ color: var(--kg-dim);+}@media (max-width: 480px) {- .kg-card { padding: 24px 20px; }- .kg-title { font-size: 22px; }+ .kg-hb-slot {+ width: 46px;+ height: 46px;+ }+ .kg-hb-glyph {+ font-size: 22px;+ }+ .kg-ov-card {+ max-width: 100%;+ }+ .kg-inv-grid {+ gap: 5px;+ }+}++/* ============================================================================+ Quests, hotbar, NPC dialog & bank (Task 10). Self-contained `kq-*` namespace+ layered over the base `kg-*` HUD; matches the dark, monochrome-leaning palette+ so quest reward colour and avatars carry the eye.+ ========================================================================== */++/* ----- nameplate badges + NPC plates -------------------------------------- */+.kg-label-row { display: inline-flex; align-items: center; gap: 4px; }+.kg-badges { display: inline-flex; gap: 2px; }+.kg-badge-glyph { font-size: 11px; line-height: 1; filter: drop-shadow(0 1px 2px rgba(0,0,0,0.7)); }++.kg-npc-label {+ position: absolute; top: 0; left: 0; will-change: transform; pointer-events: none;+ display: flex; flex-direction: column; align-items: center; gap: 2px;+ font-size: 12px; font-weight: 700; text-shadow: 0 1px 3px rgba(0,0,0,0.85);+}+.kg-npc-tag {+ padding: 1px 8px; border-radius: 6px; white-space: nowrap;+ background: rgba(59, 91, 140, 0.55); border: 1px solid rgba(170, 190, 230, 0.4); color: #eaf1ff;+}+.kg-npc-marker {+ font-size: 18px; font-weight: 900; line-height: 1;+ animation: kq-bob 1.4s ease-in-out infinite;+}+.kq-marker-new { color: #ffce5c; text-shadow: 0 0 8px rgba(255, 206, 92, 0.7); }+.kq-marker-turnin { color: #6ee787; text-shadow: 0 0 8px rgba(110, 231, 135, 0.7); }+@keyframes kq-bob { 0%,100% { transform: translateY(0); } 50% { transform: translateY(-4px); } }++/* ----- toolbar (Quests / Bank buttons) ------------------------------------ */+.kq-toolbar { position: fixed; top: 52px; right: 12px; z-index: 11; display: flex; gap: 8px; }+.kq-toolbar[hidden] { display: none; }+.kq-tool-btn {+ position: relative; display: inline-flex; align-items: center; gap: 7px; cursor: pointer;+ padding: 8px 13px; border-radius: 10px; font: inherit; font-size: 13px; font-weight: 700;+ color: var(--kg-text); background: var(--kg-panel); border: 1px solid var(--kg-line);+ box-shadow: 0 6px 20px rgba(0,0,0,0.35); transition: transform .08s, border-color .15s, background .15s;+}+.kq-tool-btn:hover { border-color: var(--kg-accent); background: rgba(40, 52, 74, 0.92); }+.kq-tool-btn:active { transform: translateY(1px); }+.kq-tool-btn:focus-visible { outline: 2px solid var(--kg-accent); outline-offset: 2px; }+.kq-tool-ic { font-size: 15px; }+.kq-dot {+ position: absolute; top: -4px; right: -4px; width: 11px; height: 11px; border-radius: 50%;+ background: #6ee787; border: 2px solid var(--kg-bg); box-shadow: 0 0 8px rgba(110,231,135,0.8);+ animation: kq-pulse 1.6s ease-in-out infinite;+}+.kq-dot[hidden] { display: none; }+@keyframes kq-pulse { 0%,100% { transform: scale(1); opacity: 1; } 50% { transform: scale(1.25); opacity: 0.7; } }++/* ----- hotbar ------------------------------------------------------------- */+.kq-hotbar {+ position: fixed; left: 50%; bottom: 44px; transform: translateX(-50%); z-index: 9;+ display: flex; gap: 8px; padding: 8px; border-radius: 14px;+ background: rgba(13, 20, 32, 0.6); border: 1px solid var(--kg-line); backdrop-filter: blur(4px);+}+.kq-hotbar[hidden] { display: none; }+.kq-slot {+ position: relative; width: 52px; height: 52px; cursor: pointer; padding: 0;+ display: flex; align-items: center; justify-content: center; font: inherit;+ background: rgba(255,255,255,0.05); border: 1px solid var(--kg-line); border-radius: 10px;+ transition: transform .08s, border-color .15s, background .15s;+}+.kq-slot:hover { border-color: var(--kg-accent); }+.kq-slot:active { transform: translateY(1px); }+.kq-slot:focus-visible { outline: 2px solid var(--kg-accent); outline-offset: 2px; }+.kq-slot--active { border-color: #ffce5c; background: rgba(255, 206, 92, 0.14); box-shadow: 0 0 0 1px rgba(255,206,92,0.5) inset; }+.kq-slot--empty { opacity: 0.55; }+.kq-slot .kq-key { position: absolute; top: 3px; left: 5px; font-size: 9px; font-weight: 700; color: var(--kg-dim); }+.kq-slot .kq-ic { font-size: 24px; line-height: 1; }+.kq-slot .kq-qty { position: absolute; bottom: 3px; right: 5px; font-size: 10px; font-weight: 700; color: var(--kg-text); text-shadow: 0 1px 2px #000; }+@media (max-width: 560px) {+ .kq-hotbar { bottom: 12px; gap: 6px; padding: 6px; }+ .kq-slot { width: 44px; height: 44px; }+ .kq-slot .kq-ic { font-size: 20px; }+}++/* ----- quest panel (left drawer) ------------------------------------------ */+.kq-panel {+ position: fixed; top: 0; left: 0; bottom: 0; z-index: 13; width: min(360px, 92vw);+ display: flex; flex-direction: column;+ background: var(--kg-panel); border-right: 1px solid var(--kg-line);+ box-shadow: 14px 0 50px rgba(0,0,0,0.5); backdrop-filter: blur(8px);+ transform: translateX(-105%); transition: transform .24s cubic-bezier(.2,.7,.2,1);+}+.kq-panel.kq-in { transform: translateX(0); }+.kq-panel[hidden] { display: none; }+.kq-panel-head { display: flex; align-items: center; justify-content: space-between; padding: 16px 18px 12px; border-bottom: 1px solid var(--kg-line); }+.kq-panel-head h2 { margin: 0; font-size: 17px; font-weight: 800; letter-spacing: .01em; }+.kq-x { width: 30px; height: 30px; cursor: pointer; border-radius: 8px; font-size: 14px; color: var(--kg-dim); background: rgba(255,255,255,0.05); border: 1px solid var(--kg-line); transition: color .15s, border-color .15s; }+.kq-x:hover { color: var(--kg-text); border-color: var(--kg-accent); }+.kq-panel-body { padding: 14px 16px 24px; overflow-y: auto; }+.kq-section { margin-bottom: 22px; }+.kq-h3 { margin: 0 0 10px; font-size: 11px; font-weight: 800; text-transform: uppercase; letter-spacing: .12em; color: var(--kg-dim); }+.kq-daily-head { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; }+.kq-reset, .kq-reset-inline { font-size: 11px; font-weight: 700; color: #ffce5c; font-variant-numeric: tabular-nums; }++.kq-card-q { padding: 12px 14px; margin-bottom: 10px; border-radius: 12px; background: rgba(255,255,255,0.035); border: 1px solid var(--kg-line); transition: border-color .2s, opacity .2s; }+.kq-card-tut { border-color: rgba(255, 206, 92, 0.4); background: rgba(255, 206, 92, 0.07); }+.kq-card-q.kq-ready { border-color: rgba(110, 231, 135, 0.5); background: rgba(110, 231, 135, 0.07); }+.kq-card-q.kq-claimed { opacity: 0.55; }+.kq-q-title { font-size: 14px; font-weight: 700; color: var(--kg-text); }+.kq-q-desc { font-size: 12px; color: var(--kg-dim); margin: 3px 0 9px; line-height: 1.4; }+.kq-progress { position: relative; height: 16px; border-radius: 8px; overflow: hidden; background: rgba(0,0,0,0.4); border: 1px solid rgba(0,0,0,0.3); }+.kq-progress i { display: block; height: 100%; background: linear-gradient(90deg, #6ee787, #d7ff7a); transition: width .35s ease; }+.kq-progress-txt { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; font-size: 10px; font-weight: 700; color: var(--kg-text); text-shadow: 0 1px 2px rgba(0,0,0,0.8); font-variant-numeric: tabular-nums; }+.kq-q-foot { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-top: 10px; }+.kq-rewards { display: flex; flex-wrap: wrap; gap: 5px; }+.kq-rw { font-size: 11px; font-weight: 700; color: var(--kg-text); background: rgba(255,255,255,0.06); border: 1px solid var(--kg-line); border-radius: 6px; padding: 2px 7px; white-space: nowrap; }+.kq-rw-badge { color: #ffce5c; border-color: rgba(255,206,92,0.4); }+.kq-claimed-tag { font-size: 12px; font-weight: 700; color: #6ee787; white-space: nowrap; }++.kq-btn {+ cursor: pointer; font: inherit; font-size: 12px; font-weight: 800; padding: 7px 14px;+ border: 0; border-radius: 8px; background: var(--kg-text); color: #0d1420;+ transition: transform .08s, opacity .15s;+}+.kq-btn:hover { opacity: 0.9; }+.kq-btn:active { transform: translateY(1px); }+.kq-btn:focus-visible { outline: 2px solid var(--kg-accent); outline-offset: 2px; }+.kq-turnin { background: #6ee787; }+.kq-btn-disabled, .kq-btn:disabled { background: rgba(255,255,255,0.08); color: var(--kg-dim); cursor: not-allowed; }+.kq-btn-ghost { background: transparent; color: var(--kg-text); border: 1px solid var(--kg-line); margin-top: 12px; width: 100%; padding: 9px; }+.kq-btn-ghost:hover { border-color: var(--kg-accent); opacity: 1; }++.kq-empty { font-size: 12px; color: var(--kg-dim); line-height: 1.5; padding: 8px 2px; }+.kq-empty-good { color: var(--kg-text); background: rgba(110, 231, 135, 0.08); border: 1px solid rgba(110,231,135,0.3); border-radius: 10px; padding: 12px 14px; text-align: center; }+.kq-tut-done { font-size: 13px; color: var(--kg-text); background: rgba(255,206,92,0.08); border: 1px solid rgba(255,206,92,0.3); border-radius: 10px; padding: 11px 14px; }+.kq-badges { display: flex; flex-wrap: wrap; gap: 7px; }+.kq-badge { display: inline-flex; align-items: center; gap: 5px; font-size: 12px; font-weight: 700; color: var(--kg-text); background: rgba(255,255,255,0.05); border: 1px solid var(--kg-line); border-radius: 999px; padding: 4px 11px; }+.kq-badge-ic { font-size: 14px; }++/* ----- modals (NPC dialog + bank) ----------------------------------------- */+.kq-modal {+ position: fixed; inset: 0; z-index: 16; display: flex; align-items: center; justify-content: center; padding: 24px;+ background: radial-gradient(120% 120% at 50% 35%, rgba(20,28,44,0.45), rgba(8,12,20,0.82)); backdrop-filter: blur(2px);+}+.kq-modal[hidden] { display: none; }+.kq-modal-card {+ position: relative; width: 100%; max-width: 440px; max-height: 86vh; overflow-y: auto;+ background: var(--kg-panel); border: 1px solid var(--kg-line); border-radius: 18px;+ padding: 22px 22px 20px; box-shadow: 0 24px 70px rgba(0,0,0,0.6);+ animation: kq-rise .22s cubic-bezier(.2,.7,.2,1);+}+@keyframes kq-rise { from { opacity: 0; transform: translateY(10px) scale(.98); } to { opacity: 1; transform: none; } }+.kq-modal-card .kq-x { position: absolute; top: 12px; right: 12px; }++/* NPC dialog */+.kq-npc-head { display: flex; align-items: center; gap: 12px; margin-bottom: 14px; }+.kq-npc-portrait { font-size: 34px; width: 54px; height: 54px; display: grid; place-items: center; border-radius: 12px; background: rgba(59,91,140,0.25); border: 1px solid rgba(170,190,230,0.35); }+.kq-npc-name { font-size: 17px; font-weight: 800; }+.kq-npc-role { font-size: 11px; text-transform: uppercase; letter-spacing: .1em; color: var(--kg-dim); }+.kq-npc-line { font-size: 14px; line-height: 1.55; color: var(--kg-text); margin: 0 0 14px; }+.kq-npc-objective { background: rgba(255,206,92,0.08); border: 1px solid rgba(255,206,92,0.3); border-radius: 12px; padding: 12px 14px; font-size: 14px; font-weight: 700; color: var(--kg-text); display: flex; flex-direction: column; gap: 4px; }+.kq-npc-obj-label { font-size: 10px; font-weight: 800; text-transform: uppercase; letter-spacing: .12em; color: #ffce5c; }+.kq-npc-obj-desc { font-size: 12px; font-weight: 500; color: var(--kg-dim); line-height: 1.4; }+.kq-npc-sub { font-size: 10px; font-weight: 800; text-transform: uppercase; letter-spacing: .12em; color: var(--kg-dim); margin: 16px 0 8px; }+.kq-npc-turnin { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 9px 12px; border-radius: 10px; background: rgba(110,231,135,0.08); border: 1px solid rgba(110,231,135,0.3); margin-bottom: 7px; }+.kq-npc-turnin-name { font-size: 13px; font-weight: 700; }++/* Bank */+.kq-bank-head { display: flex; align-items: center; gap: 10px; margin-bottom: 16px; }+.kq-bank-head h2 { margin: 0; font-size: 17px; font-weight: 800; }+.kq-bank-hint { margin-left: auto; font-size: 11px; color: var(--kg-dim); }+.kq-bank-cols { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }+.kq-bank-col h3 { margin: 0 0 8px; font-size: 11px; font-weight: 800; text-transform: uppercase; letter-spacing: .12em; color: var(--kg-dim); }+.kq-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px; min-height: 56px; align-content: start; }+.kq-cell {+ position: relative; aspect-ratio: 1; cursor: pointer; padding: 0;+ display: flex; align-items: center; justify-content: center;+ background: rgba(255,255,255,0.05); border: 1px solid var(--kg-line); border-radius: 9px;+ transition: transform .08s, border-color .15s, background .15s;+}+.kq-cell:hover { border-color: var(--kg-accent); background: rgba(40,52,74,0.9); }+.kq-cell:active { transform: translateY(1px); }+.kq-cell:focus-visible { outline: 2px solid var(--kg-accent); outline-offset: 2px; }+.kq-cell .kq-ic { font-size: 22px; }+.kq-cell .kq-qty { position: absolute; bottom: 2px; right: 4px; font-size: 10px; font-weight: 700; text-shadow: 0 1px 2px #000; }+.kq-bank-col .kq-empty { grid-column: 1 / -1; }+@media (max-width: 480px) {+ .kq-bank-cols { grid-template-columns: 1fr; gap: 12px; }+ .kq-grid { grid-template-columns: repeat(6, 1fr); }+}++@media (prefers-reduced-motion: reduce) {+ .kq-panel, .kq-progress i, .kq-tool-btn, .kq-slot, .kq-cell { transition: none; }+ .kq-modal-card { animation: none; }+ .kq-npc-marker, .kq-dot { animation: none; }+}++/* Loot + mount toasts (Task 09). Mount drops get a celebratory violet accent;+ plain loot a warm gold, matching the bag/portal colour language. */+.kg-toast--loot {+ border-color: rgba(255, 206, 92, 0.45);+}+.kg-toast--mount,+.kg-toast--cmd {+ border-color: rgba(174, 123, 255, 0.6);+ box-shadow: 0 8px 28px rgba(120, 70, 220, 0.3);+}++/* Mount status chip — visible only while riding. Sits clear of the centred hotbar+ and the mobile joystick, naming the steed with a one-tap Dismount. */+.kg-mount {+ position: fixed;+ right: 16px;+ bottom: 104px;+ z-index: 9;+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 7px 10px 7px 12px;+ border-radius: 999px;+ background: var(--kg-panel);+ border: 1px solid rgba(174, 123, 255, 0.55);+ color: var(--kg-text);+ font-size: 13px;+ font-weight: 600;+ box-shadow: 0 8px 28px rgba(0, 0, 0, 0.45);+ animation: kg-mount-in 0.25s ease;+}+.kg-mount[hidden] {+ display: none;+}+@keyframes kg-mount-in {+ from { opacity: 0; transform: translateY(8px); }+ to { opacity: 1; transform: translateY(0); }+}+.kg-mount-ico {+ font-size: 16px;+ line-height: 1;+}+.kg-mount-txt {+ color: var(--kg-dim);+ white-space: nowrap;+}+.kg-mount-txt b {+ color: var(--kg-text);+ font-weight: 700;+ text-transform: capitalize;+}+.kg-mount-btn {+ margin-left: 2px;+ padding: 5px 12px;+ border-radius: 999px;+ border: 1px solid var(--kg-line);+ background: rgba(174, 123, 255, 0.18);+ color: var(--kg-text);+ font: inherit;+ font-size: 12px;+ font-weight: 700;+ cursor: pointer;+ transition: border-color 0.15s, background 0.15s, transform 0.1s;+}+.kg-mount-btn:hover {+ border-color: rgba(174, 123, 255, 0.8);+ background: rgba(174, 123, 255, 0.3);+}+.kg-mount-btn:active {+ transform: scale(0.96);+}+.kg-mount-btn:focus-visible {+ outline: 2px solid var(--kg-accent);+ outline-offset: 2px;}diff --git a/src/game/iso-game.js b/src/game/iso-game.jsindex c33e5768f..586364de9 100644--- a/src/game/iso-game.js+++ b/src/game/iso-game.js@@ -24,6 +24,8 @@ import {Mesh, MeshStandardMaterial, MeshBasicMaterial, PlaneGeometry, BoxGeometry,CylinderGeometry, ConeGeometry, DodecahedronGeometry, IcosahedronGeometry,CircleGeometry, CanvasTexture, RepeatWrapping, DoubleSide,+ Raycaster, Vector2, SphereGeometry, RingGeometry,+ BufferGeometry, Line, LineBasicMaterial, Float32BufferAttribute,} from 'three';import nipplejs from 'nipplejs';@@ -32,13 +34,52 @@ import {loadManifest, resolveAvatarUrl, buildAvatar, newAnim, CLIP_IDLE, CLIP_WALK,} from './avatar-rig.js';import { GUEST_SENTINEL, uploadPendingGuestAvatar } from './play-handoff.js';+import { GameHud } from './game-hud.js';const TILE = 1.0; // world units per tileconst STEP_INTERVAL_MS = 165; // walk cadence — one authoritative step per tile+const INTERACT_ACTION_MS = 380; // cadence for repeated gather/attack while adjacent to a target+// Quest badge glyphs, mirrored from the server (quests.js BADGES), so a player's+// earned badges render as small icons on their nameplate (the in-world profile).+const BADGE_ICONS = { newcomer: '🎓', warrior: '⚔️', forager: '🧺', devoted: '🌟' };const MOVE_LERP = 0.22; // position interpolation toward the server tileconst YAW_LERP = 0.22;const AVATAR_DEFAULT = '/avatars/default.glb';+// Skills surface — display order, label, accent hue, and a line-art glyph for+// each trainable skill. The order mirrors the server's SKILLS array so the panel+// reads consistently; the server stays the source of truth for levels/XP/cap.+const SKILL_ORDER = ['combat', 'woodcutting', 'mining', 'fishing', 'cooking'];+const SKILL_META = {+ combat: { label: 'Combat', hue: '#ff8a8a', icon: 'M5 5l14 14M19 5L5 19' },+ woodcutting: { label: 'Woodcutting', hue: '#6ee787', icon: 'M12 3l5 8H7zM9.5 11h5l2.5 6H7zM12 17v4' },+ mining: { label: 'Mining', hue: '#c8cedb', icon: 'M3 8c5-4 13-4 18 0M12 7v13' },+ fishing: { label: 'Fishing', hue: '#5cb6e6', icon: 'M3 12c4-5 12-5 16 0-4 5-12 5-16 0zM19 12l3-2v4M7 11v.01' },+ cooking: { label: 'Cooking', hue: '#ff9a4d', icon: 'M12 3c2.5 3.5 4 5.5 4 8a4 4 0 0 1-8 0c0-1.6.8-2.7 1.7-3.6.2 1.7 1 2.6 2.3 2.6-1-2.5 0-4.6 0-7z' },+};+const fmtXp = (n) => Math.round(n).toLocaleString('en-US');++// Items the player can eat to heal — mirrors the server item registry's `edible`+// flag (items.js). Kept as a small client-side set, like the walkability mirror,+// so the action bar can offer "Eat" without round-tripping the full registry.+const EDIBLE = new Set(['cookedFish', 'healthPotion']);+const FOOD_LABEL = { cookedFish: 'cooked fish', healthPotion: 'potion' };++// Lightweight item presentation for the death-bag recovery panel: a readable+// label + a chip colour per known item. Unknown items fall back to a titlecase+// of their id and a neutral chip, so a future item never renders blank.+const ITEM_LABEL = {+ wood: 'Wood', stone: 'Stone', coal: 'Coal', fish: 'Raw fish',+ cookedFish: 'Cooked fish', gold: 'Gold',+ axe: 'Axe', pickaxe: 'Pickaxe', rod: 'Fishing rod', hammer: 'Hammer', sword: 'Sword',+};+const ITEM_COLOR = {+ wood: '#a9743f', stone: '#9aa0ac', coal: '#3a3f48', fish: '#5cb6e6',+ cookedFish: '#e6a85c', gold: '#ffce5c',+};+const itemLabel = (id) => ITEM_LABEL[id] || (id ? id.replace(/^\w/, (m) => m.toUpperCase()) : 'Item');+const itemColor = (id) => ITEM_COLOR[id] || '#7d8696';+// ---------------------------------------------------------------------------// GamePlayerView — a player's avatar rig in the tile world. The server owns the// authoritative tile; this view interpolates toward it so movement reads smooth@@ -76,13 +117,21 @@ class GamePlayerView {this.label = document.createElement('div');this.label.className = 'kg-label' + (isLocal ? ' kg-label--me' : '');this.label.innerHTML =- `<span class="kg-label-name"></span><span class="kg-hp"><i></i></span>`;+ `<span class="kg-label-row"><span class="kg-badges"></span><span class="kg-label-name"></span></span><span class="kg-hp"><i></i></span>`;this.nameEl = this.label.querySelector('.kg-label-name');this.hpFill = this.label.querySelector('.kg-hp i');+ this.badgesEl = this.label.querySelector('.kg-badges');this.nameEl.textContent = player.name || 'guest';+ this.badges = '';+ this._renderBadges(player.badges || '');document.getElementById('kg-labels')?.appendChild(this.label);this._renderHp();+ // Mount visuals (Task 09): a steed mesh + saddle lift, attached in applyMount.+ this.mounted = false;+ this._steed = null;+ this._saddleY = 0;+ this._rideRate = 1.5;this._avatarUrl = null;this.setAvatar(player.cosmetic || '');}@@ -107,9 +156,13 @@ class GamePlayerView {this.target.set(w.x, 0, w.z);if (player.name && player.name !== this.nameEl.textContent) this.nameEl.textContent = player.name;+ if ((player.badges || '') !== this.badges) this._renderBadges(player.badges || '');if (player.hp !== this.hp || player.maxHp !== this.maxHp) {this.hp = player.hp; this.maxHp = player.maxHp; this._renderHp();}+ // Keep the authoritative respawn deadline so the local death overlay can+ // count down to it from the synced schema (no client-side fake timer).+ this.respawnAt = player.respawnAt || 0;if (!!player.dead !== this.dead) {this.dead = !!player.dead;this.rig.visible = !this.dead;@@ -127,6 +180,15 @@ class GamePlayerView {if (moved) this._movedAt = performance.now();}+ // Render the comma-separated badge ids as small glyphs ahead of the name.+ _renderBadges(badges) {+ this.badges = badges;+ const ids = badges ? badges.split(',').filter(Boolean) : [];+ this.badgesEl.innerHTML = ids+ .map((id) => BADGE_ICONS[id] ? `<span class="kg-badge-glyph" title="${id}">${BADGE_ICONS[id]}</span>` : '')+ .join('');+ }+_renderHp() {const pct = this.maxHp > 0 ? Math.max(0, Math.min(1, this.hp / this.maxHp)) : 0;this.hpFill.style.width = (pct * 100).toFixed(0) + '%';@@ -137,16 +199,73 @@ class GamePlayerView {tick(dt) {this.rig.position.x += (this.target.x - this.rig.position.x) * MOVE_LERP;this.rig.position.z += (this.target.z - this.rig.position.z) * MOVE_LERP;+ // Saddle lift: a mount raises the rider; on foot the body settles back to ground.+ this.rig.position.y += ((this.mounted ? this._saddleY : 0) - this.rig.position.y) * 0.2;let d = this.yaw - this.curYaw;while (d > Math.PI) d -= Math.PI * 2;while (d < -Math.PI) d += Math.PI * 2;this.curYaw += d * YAW_LERP;this.rig.rotation.y = this.curYaw;- this.anim?.update(dt);+ if (this._steed) {+ this._steed.position.set(this.rig.position.x, 0, this.rig.position.z);+ this._steed.rotation.y = this.curYaw;+ }+ // A mounted, moving rider reads faster — nudge the walk clip rate while riding.+ this.anim?.update(dt * (this.mounted && this.motion === 'walk' ? this._rideRate : 1));+ }++ // Mount or dismount the steed under this avatar. `def` is the registry mount+ // tuning ({ color, accent, scale }) or null to dismount. The steed is a scene+ // sibling (not a child of the async avatar rig), so it survives avatar reloads;+ // tick() keeps it glued under the rider.+ applyMount(def) {+ const want = !!def;+ if (want === this.mounted && (!want || this._steed)) return;+ this.mounted = want;+ if (want) {+ if (this._steed) this.scene.remove(this._steed);+ this._steed = this._buildSteed(def);+ this._steed.position.set(this.rig.position.x, 0, this.rig.position.z);+ this._steed.rotation.y = this.curYaw;+ this.scene.add(this._steed);+ this._saddleY = 0.62 * (def.scale || 1);+ } else if (this._steed) {+ this.scene.remove(this._steed);+ this._steed = null;+ this._saddleY = 0;+ }+ }++ // A low-poly quadruped steed coloured from the registry: body + neck + head,+ // four legs, and a tail + snout accent so dire wolf and war boar read distinct.+ _buildSteed(def) {+ const g = new Group();+ const s = def.scale || 1;+ const body = new MeshStandardMaterial({ color: def.color ?? 0x6b7280, roughness: 0.85 });+ const accent = new MeshStandardMaterial({ color: def.accent ?? 0xb9c2d0, roughness: 0.8 });+ const torso = new Mesh(new BoxGeometry(0.5 * s, 0.42 * s, 1.0 * s), body);+ torso.position.y = 0.5 * s; torso.castShadow = true;+ const neck = new Mesh(new BoxGeometry(0.28 * s, 0.4 * s, 0.3 * s), body);+ neck.position.set(0, 0.72 * s, 0.5 * s); neck.rotation.x = -0.5; neck.castShadow = true;+ const head = new Mesh(new BoxGeometry(0.26 * s, 0.26 * s, 0.4 * s), body);+ head.position.set(0, 0.92 * s, 0.66 * s); head.castShadow = true;+ const snout = new Mesh(new BoxGeometry(0.18 * s, 0.16 * s, 0.18 * s), accent);+ snout.position.set(0, 0.86 * s, 0.86 * s);+ const legGeo = new BoxGeometry(0.12 * s, 0.5 * s, 0.12 * s);+ for (const [lx, lz] of [[-0.18, 0.38], [0.18, 0.38], [-0.18, -0.38], [0.18, -0.38]]) {+ const leg = new Mesh(legGeo, body);+ leg.position.set(lx * s, 0.25 * s, lz * s); leg.castShadow = true;+ g.add(leg);+ }+ const tail = new Mesh(new BoxGeometry(0.08 * s, 0.08 * s, 0.34 * s), accent);+ tail.position.set(0, 0.6 * s, -0.6 * s); tail.rotation.x = 0.6;+ g.add(torso, neck, head, snout, tail);+ return g;}dispose() {this.scene.remove(this.rig);+ if (this._steed) this.scene.remove(this._steed);this.label.remove();}}@@ -161,10 +280,52 @@ export class IsoGame {this.players = new Map(); // sessionId -> GamePlayerViewthis.nodeViews = new Map(); // id -> { group, node }this.mobViews = new Map(); // id -> { group, mob }+ this.npcViews = new Map(); // id -> { group, npc, label, markerEl }+ this.tombViews = new Map(); // id -> { group, tomb, label, nameEl, ttlEl }this.keys = new Set();this.realm = null;this.myId = null;+ // Click-to-interact: a tap on a node/mob/NPC sets a target the loop walks+ // to and then services (gather/attack/talk); a tap on open ground sets a+ // move-to tile. _interactAccum paces repeated gather/attack while adjacent.+ this._target = null; // { kind:'node'|'mob'|'npc'|'tile', id?, tx?, ty? }+ this._interactAccum = 0;+ this.items = {}; // server item registry (mount tuning, icons) — arrives on join+ // Latest authoritative quest snapshot (drives the NPC markers + quest dot).+ this.quests = null;++ // Death & death-bag UI state. _raycaster/_ptr turn a tap into a world pick+ // (used to click an adjacent tombstone). _lootTombId is the bag whose+ // recovery panel is open; _deathInfo carries the last 'died' notice so the+ // respawn overlay can describe what was dropped.+ this._raycaster = new Raycaster();+ this._ptr = new Vector2();+ this._dragMoved = 0;+ this._lootTombId = null;+ this._deathInfo = null;+ this._deathShown = false;++ // Active fishing cast — the line/bobber/ripple visual while a cast is in the+ // water. Local-only (peers don't see our bobber); the authoritative catch+ // result rides back as a 'fish' notice that resolves it. null when idle.+ this._cast = null;++ // Skills panel state: latest server snapshot, open flag, and the live-refresh+ // timer that polls XP while the panel is open so bars fill as XP is earned.+ this._skills = null;+ this._skillsOpen = false;+ this._skillsTimer = null;++ // World chat: open flag (drives the expanded vs. click-through collapsed+ // state) and the per-account mute set. Mutes are keyed by display name —+ // the stable identity until accounts land — and persisted locally;+ // Task 16 migrates this to the account-scoped profile store. The closer+ // fn is the document listener that dismisses an open mute popover.+ this._chatOpen = false;+ this.muted = this._loadMuted();+ this._muteMenuCloser = null;+// Camera: a follow rig at a fixed three-quarter angle. Drag rotates yaw,// wheel/pinch zooms. Pitch is steep for the isometric read.this.camYaw = 0.7; this.camPitch = 0.95; this.camDist = 16;@@ -178,6 +339,16 @@ export class IsoGame {this._bindHud();this._bindInput();+ // Quest/hotbar/bank HUD. Self-contained DOM; intents route back through net.+ this.q = new GameHud({+ onEquip: (i) => this._equipOrRide(i),+ onTurnIn: (id) => this.net?.questTurnIn(id),+ onBankOpen: () => this.net?.bankOpen(),+ onDeposit: (i) => this.net?.bankDeposit(i, 999),+ onWithdraw: (i) => this.net?.bankWithdraw(i, 999),+ onReset: () => this.net?.questOpen(),+ });+this._loop = this._loop.bind(this);requestAnimationFrame(this._loop);}@@ -240,31 +411,54 @@ export class IsoGame {const grid = layout.grid || 48;const size = grid * TILE;- // Ground plane with a subtle tile grid so movement is legible.+ // The mine interior reads as an enclosed cave: a dark rocky floor, rock+ // walls, and a tight, dim atmosphere. Surface realms keep the open sky+ // look. Background + fog are reset on every realm build, so walking back+ // up to the Mainland restores daylight cleanly.+ const isCave = layout.name === 'mine';+ this.scene.background.set(isCave ? 0x130f0b : 0x223a55);+ this.scene.fog.color.set(isCave ? 0x130f0b : 0x223a55);+ this.scene.fog.near = isCave ? 16 : 48;+ this.scene.fog.far = isCave ? 70 : 120;++ // Ground plane with a subtle tile grid so movement is legible. The cave+ // uses a dark rock floor instead of grass.const ground = new Mesh(new PlaneGeometry(size, size),- new MeshStandardMaterial({ map: this._gridTexture(grid), color: 0x6b9a52, roughness: 1 }),+ new MeshStandardMaterial({ map: this._gridTexture(grid, isCave), color: isCave ? 0x2a241d : 0x6b9a52, roughness: 1 }),);ground.rotation.x = -Math.PI / 2;ground.receiveShadow = true;this.staticGroup.add(ground);- // Solid blocks (bank building, pond water, etc.) — render each blocked- // rect as a low box so the no-go zones are visually obvious and match the- // server's walkability exactly.+ // Water bodies are a visual subset of the blocked rects (server marks them in+ // `layout.water`). Render those as low, translucent pools and everything else+ // as solid no-go boxes — both match the server's walkability exactly. A set of+ // per-tile water keys also lets a tap on the pond resolve to a cast.+ const rectKey = (r) => `${r.x0},${r.y0},${r.x1},${r.y1}`;+ const waterRects = new Set((layout.water || []).map(rectKey));+ this._waterTiles = new Set();+ for (const r of layout.water || []) {+ for (let tx = r.x0; tx <= r.x1; tx++) for (let ty = r.y0; ty <= r.y1; ty++) this._waterTiles.add(`${tx},${ty}`);+ }+ // Solid blocks (bank building, walls, etc.) — render each blocked rect as a+ // low box so the no-go zones are visually obvious.for (const b of layout.blocked || []) {+ const isWater = waterRects.has(rectKey(b));const w = (b.x1 - b.x0 + 1) * TILE;const d = (b.y1 - b.y0 + 1) * TILE;- const isWater = layout.name === 'pond';const h = isWater ? 0.25 : 2.4;const box = new Mesh(new BoxGeometry(w, h, d),- new MeshStandardMaterial({- color: isWater ? 0x2c5a86 : 0x4a4f5e,- roughness: isWater ? 0.3 : 0.85,- metalness: isWater ? 0.1 : 0,- transparent: isWater, opacity: isWater ? 0.85 : 1,- }),+ isWater+ ? new MeshStandardMaterial({+ color: 0x2c5a86, roughness: 0.3, metalness: 0.1,+ transparent: true, opacity: 0.85,+ emissive: 0x0a2030, emissiveIntensity: 0.35,+ })+ : isCave+ ? new MeshStandardMaterial({ map: this._rockTexture(), color: 0x6a5f4f, roughness: 1 })+ : new MeshStandardMaterial({ color: 0x4a4f5e, roughness: 0.85 }),);const cx = (b.x0 + b.x1) / 2, cy = (b.y0 + b.y1) / 2;const w0 = this._tileToWorld(cx, cy);@@ -298,6 +492,10 @@ export class IsoGame {this._paintTiles(this._rectTiles(p), 0xae7bff, 0.7);}+ // Fixed NPCs (Aldric the Guide, …) — distinct characters with a nameplate ++ // quest marker. Rebuilt with the realm since they ride in the realm layout.+ this._buildNpcs(layout);+// Frame the camera on the spawn before the local player exists.const sp = this._tileToWorld(layout.spawn?.tx ?? grid / 2, layout.spawn?.ty ?? grid / 2);this._camTarget.set(sp.x, 0, sp.z);@@ -305,6 +503,69 @@ export class IsoGame {this.hud.realm.textContent = (layout.name || 'realm').replace(/^\w/, (m) => m.toUpperCase());}+ // ---------------------------------------------------------------- NPCs+ _buildNpcs(layout) {+ this._disposeNpcs();+ for (const npc of layout.npcs || []) {+ const group = this._buildNpcView(npc);+ const w = this._tileToWorld(npc.tx, npc.ty);+ group.position.set(w.x, 0, w.z);+ group.traverse((o) => { o.userData.npcId = npc.id; }); // raycast → talk target+ this.objectGroup.add(group);++ const label = document.createElement('div');+ label.className = 'kg-npc-label';+ label.innerHTML = `<span class="kg-npc-marker" hidden></span><span class="kg-npc-tag"></span>`;+ label.querySelector('.kg-npc-tag').textContent = npc.name;+ document.getElementById('kg-labels')?.appendChild(label);++ this.npcViews.set(npc.id, { group, npc, label, markerEl: label.querySelector('.kg-npc-marker'), height: 1.9 });+ }+ this._refreshNpcMarkers();+ }++ // A distinct robed guide figure (so it never reads as a player capsule): a+ // hooded body, a face disc, and a small staff. Low-poly, no asset load.+ _buildNpcView(npc) {+ const g = new Group();+ const robe = new Mesh(new CylinderGeometry(0.32, 0.5, 1.3, 12),+ new MeshStandardMaterial({ color: 0x3b5b8c, roughness: 0.85 }));+ robe.position.y = 0.65; robe.castShadow = true;+ const hood = new Mesh(new ConeGeometry(0.36, 0.5, 12),+ new MeshStandardMaterial({ color: 0x2c4468, roughness: 0.85 }));+ hood.position.y = 1.45; hood.castShadow = true;+ const face = new Mesh(new SphereGeometry(0.2, 16, 12),+ new MeshStandardMaterial({ color: 0xe8c9a0, roughness: 0.7 }));+ face.position.y = 1.32;+ const staff = new Mesh(new CylinderGeometry(0.04, 0.04, 1.6, 6),+ new MeshStandardMaterial({ color: 0x6b4a2b, roughness: 1 }));+ staff.position.set(0.42, 0.8, 0); staff.castShadow = true;+ const orb = new Mesh(new IcosahedronGeometry(0.12, 0),+ new MeshStandardMaterial({ color: 0xffce5c, emissive: 0x6b5410, emissiveIntensity: 0.8, roughness: 0.4 }));+ orb.position.set(0.42, 1.65, 0);+ g.add(robe, hood, face, staff, orb);+ return g;+ }++ // Aldric's floating "!" (tutorial in progress) / "?" (a daily ready to claim)+ // marker, derived from the local quest snapshot. Cleared when there's nothing+ // to do at him.+ _refreshNpcMarkers() {+ const tutorialActive = !!(this.quests?.tutorial && !this.quests.tutorial.done);+ const turnIn = (this.quests?.daily?.quests || []).some((q) => q.progress >= q.count && !q.claimed);+ for (const [, v] of this.npcViews) {+ const mark = turnIn ? '?' : tutorialActive ? '!' : '';+ v.markerEl.textContent = mark;+ v.markerEl.hidden = !mark;+ v.markerEl.className = 'kg-npc-marker' + (turnIn ? ' kq-marker-turnin' : ' kq-marker-new');+ }+ }++ _disposeNpcs() {+ for (const [, v] of this.npcViews) { this.objectGroup.remove(v.group); v.label.remove(); }+ this.npcViews.clear();+ }+_rectTiles(r) {const out = [];for (let tx = r.x0; tx <= r.x1; tx++) for (let ty = r.y0; ty <= r.y1; ty++) out.push({ tx, ty });@@ -324,13 +585,14 @@ export class IsoGame {}}- // A faint white tile grid drawn once into a tiling canvas texture.- _gridTexture(grid) {+ // A faint tile grid drawn once into a tiling canvas texture. `dark` swaps the+ // grass palette for a dim rock floor used by the cave (mine) interior.+ _gridTexture(grid, dark = false) {const px = 64;const c = document.createElement('canvas'); c.width = c.height = px;const x = c.getContext('2d');- x.fillStyle = '#5c8a44'; x.fillRect(0, 0, px, px);- x.strokeStyle = 'rgba(255,255,255,0.10)'; x.lineWidth = 2;+ x.fillStyle = dark ? '#241f19' : '#5c8a44'; x.fillRect(0, 0, px, px);+ x.strokeStyle = dark ? 'rgba(0,0,0,0.45)' : 'rgba(255,255,255,0.10)'; x.lineWidth = 2;x.strokeRect(0, 0, px, px);const tex = new CanvasTexture(c);tex.wrapS = tex.wrapT = RepeatWrapping;@@ -339,6 +601,30 @@ export class IsoGame {return tex;}+ // Mottled rock texture for cave walls, drawn once and cached. Speckle + a few+ // dark cracks over a stone base read as rough rock without an image asset.+ _rockTexture() {+ if (this._rockTex) return this._rockTex;+ const px = 128;+ const c = document.createElement('canvas'); c.width = c.height = px;+ const x = c.getContext('2d');+ x.fillStyle = '#4f4538'; x.fillRect(0, 0, px, px);+ for (let i = 0; i < 480; i++) {+ const g = 40 + Math.floor(Math.random() * 55);+ x.fillStyle = `rgba(${g + 18},${g + 8},${g - 6},${0.18 + Math.random() * 0.4})`;+ x.beginPath(); x.arc(Math.random() * px, Math.random() * px, 1 + Math.random() * 3, 0, Math.PI * 2); x.fill();+ }+ x.strokeStyle = 'rgba(12,9,6,0.5)'; x.lineWidth = 1.5;+ for (let i = 0; i < 9; i++) {+ x.beginPath(); x.moveTo(Math.random() * px, Math.random() * px); x.lineTo(Math.random() * px, Math.random() * px); x.stroke();+ }+ const tex = new CanvasTexture(c);+ tex.wrapS = tex.wrapT = RepeatWrapping;+ tex.colorSpace = SRGBColorSpace;+ this._rockTex = tex;+ return tex;+ }+// ---------------------------------------------------------------- connectasync start(name) {if (this.phase === 'world' || this.phase === 'connecting') return;@@ -358,12 +644,21 @@ export class IsoGame {? this.avatarPref : this.localAvatarUrl);await loadManifest();- this.net = new GameNet({ name, avatar: netAvatar });+ // Realm is chosen by ?realm=<name> (each realm is its own room). Until+ // Task 01's portal traversal lands this is how a danger realm like+ // Wilderness is reached directly; the server still validates everything.+ const realm = new URLSearchParams(location.search).get('realm') || 'mainland';+ this.net = new GameNet({ name, avatar: netAvatar, realm, pid: this._playerId() });if (isGuest) uploadPendingGuestAvatar((publicUrl) => this.net?.setAvatar(publicUrl));this.net.on('status', ({ status, error }) => this._onStatus(status, error));this.net.on('realm', (layout) => this._buildRealm(layout));- this.net.on('notice', (n) => this._toast(n));+ this.net.on('items', (r) => this._onItems(r));+ this.net.on('notice', (n) => this._onNotice(n));+ this.net.on('cooked', (c) => this._onCooked(c));+ this.net.on('chat', (m) => this._onChat(m));this.net.on('bank', (b) => this._onBank(b));+ this.net.on('skills', (s) => this._onSkills(s));+ this.net.on('levelup', (l) => this._onLevelup(l));this.net.on('playerAdd', (p, id) => this._playerAdd(p, id));this.net.on('playerChange', (p, id) => this._playerChange(p, id));this.net.on('playerRemove', (id) => this._playerRemove(id));@@ -373,18 +668,36 @@ export class IsoGame {this.net.on('mobAdd', (m, id) => this._mobAdd(m, id));this.net.on('mobChange', (m, id) => this._mobChange(m, id));this.net.on('mobRemove', (id) => this._mobRemove(id));+ this.net.on('tombAdd', (t, id) => this._tombAdd(t, id));+ this.net.on('tombChange', (t, id) => this._tombChange(t, id));+ this.net.on('tombRemove', (id) => this._tombRemove(id));+ this.net.on('died', (d) => this._onDied(d));+ this.net.on('quests', (q) => this._onQuests(q));await this.net.connect();this.myId = this.net.sessionId;this._initJoystick();}+ // Stable account id for persistence (tutorial completion, dailies, badges).+ // Prefers a connected wallet address, else a persistent per-browser guest id.+ _playerId() {+ try {+ const wallet = localStorage.getItem('cc-wallet') || '';+ if (wallet) return wallet;+ let id = localStorage.getItem('kg-pid');+ if (!id) { id = 'g_' + Math.random().toString(36).slice(2) + Date.now().toString(36); localStorage.setItem('kg-pid', id); }+ return id;+ } catch { return ''; }+ }+_onStatus(status, error) {this.hud.status.textContent = status;this.hud.status.dataset.status = status;if (status === 'online') {this.phase = 'world';this._setHudPhase('world');+ this.q?.enterWorld();} else if (status === 'offline' || status === 'failed') {// Keep the world visible if we were already in it (a transient drop);// only fall back to the offline screen if we never connected.@@ -403,9 +716,29 @@ export class IsoGame {// guest blob the server hasn't received the public URL for yet).if (isLocal && this.localAvatarUrl) view.setAvatar(this.localAvatarUrl);this.players.set(id, view);+ view.applyMount(p.mounted ? this._mountDef(p.mount) : null);+ if (isLocal) this._syncLocalHud(p);this._updateOnline();}- _playerChange(p, id) { this.players.get(id)?.apply(p); }+ _playerChange(p, id) {+ const v = this.players.get(id);+ if (!v) return;+ v.apply(p);+ v.applyMount(p.mounted ? this._mountDef(p.mount) : null);+ if (id === this.myId) this._syncLocalHud(p);+ }++ // Push the local player's authoritative inventory/hotbar into the HUD: the+ // hotbar bar, the bank panel's backpack column, and the "Bank" prompt that+ // appears only while standing on a bank-counter tile.+ _syncLocalHud(p) {+ if (!this.q) return;+ this.q.setHotbar(p.hotbar.map((s) => ({ item: s.item, qty: s.qty })), p.activeSlot);+ this.q.setInventory(p.inv.map((s) => ({ item: s.item, qty: s.qty })));+ const onBank = (this.realm?.bankZone || []).some((t) => t.tx === p.tx && t.ty === p.ty);+ this.q.setBankAvailable(onBank);+ this._updateMountChip(p);+ }_playerRemove(id) {const v = this.players.get(id);if (v) { v.dispose(); this.players.delete(id); this._updateOnline(); }@@ -416,6 +749,55 @@ export class IsoGame {if (this.hud?.online) this.hud.online.textContent = String(this.players.size || 0);}+ // ------------------------------------------------------------ items & mounts+ // The server item registry (icons, labels, mount tuning) arrives once on join.+ // Re-apply mounts to every avatar now that their visuals are resolvable.+ _onItems(reg) {+ this.items = reg || {};+ const players = this.net?.state?.players;+ if (players) {+ for (const [id, v] of this.players) {+ const sp = players.get(id);+ if (sp) v.applyMount(sp.mounted ? this._mountDef(sp.mount) : null);+ }+ }+ const me = this.net?.state?.players?.get(this.myId);+ if (me) this._updateMountChip(me);+ }++ _mountDef(id) { return this.items?.[id]?.mount || null; }++ // Equip a hotbar slot; if it holds a mount, also ride it — the natural "tap your+ // steed to mount" gesture. Both are server-authoritative (equip + use intents).+ _equipOrRide(i) {+ if (this.phase !== 'world') return;+ this.net?.equip(i);+ const ps = this.net?.state?.players?.get(this.myId);+ const item = ps?.hotbar?.[i]?.item;+ if (item && this._mountDef(item) && !(ps.mounted && ps.mount === item)) this.net?.use(i);+ }++ // Effective step cadence: a mount lowers it to (its server floor + headroom) so+ // the client never out-paces what the server accepts, yet rides visibly faster.+ _stepInterval() {+ const ps = this.net?.state?.players?.get(this.myId);+ const ms = ps?.mounted ? this._mountDef(ps.mount)?.stepMs : 0;+ return ms ? ms + 22 : STEP_INTERVAL_MS;+ }++ // Mount status chip + Dismount button: shown only while riding, naming the steed+ // from the registry. Driven by the authoritative mounted flag (no client guess).+ _updateMountChip(p) {+ const chip = this.hud?.mount;+ if (!chip) return;+ const show = !!p.mounted && this.phase === 'world';+ if (chip.hidden === show) chip.hidden = !show;+ if (show && this.hud.mountName) {+ const name = this.items?.[p.mount]?.label || (p.mount ? p.mount.replace(/_/g, ' ') : 'mount');+ if (this.hud.mountName.textContent !== name) this.hud.mountName.textContent = name;+ }+ }+// ---------------------------------------------------------------- nodes// Resource nodes (trees/rocks/coal). T7 swaps _buildNodeView for richer// geometry + gather interactions; the add/change/remove plumbing stays.@@ -425,6 +807,7 @@ export class IsoGame {const w = this._tileToWorld(node.tx, node.ty);group.position.set(w.x, 0, w.z);group.visible = !node.depleted;+ group.traverse((o) => { o.userData.nodeId = id; }); // resolve raycast hits → gather targetthis.objectGroup.add(group);this.nodeViews.set(id, { group, node });}@@ -470,6 +853,7 @@ export class IsoGame {const w = this._tileToWorld(mob.tx, mob.ty);group.position.set(w.x, 0, w.z);group.visible = !mob.dead;+ group.traverse((o) => { o.userData.mobId = id; }); // resolve raycast hits → attack targetthis.objectGroup.add(group);this.mobViews.set(id, { group, mob });}@@ -498,10 +882,380 @@ export class IsoGame {return g;}+ // ---------------------------------------------------------------- tombstones+ // Death-bags dropped in danger realms. Each gets a distinct gravestone mesh+ // (so it never reads as a rock node) plus a floating DOM label with the owner+ // name and a live "expires in Xs" countdown driven by the synced expiresAt.+ // Clicking an adjacent bag sends 'tombLoot' and opens the recovery panel.+ _tombAdd(tomb, id) {+ if (this.tombViews.has(id)) { this._tombChange(tomb, id); return; }+ const group = this._buildTombView(id);+ const w = this._tileToWorld(tomb.tx, tomb.ty);+ group.position.set(w.x, 0, w.z);+ this.objectGroup.add(group);++ const label = document.createElement('div');+ label.className = 'kg-tomblabel';+ label.innerHTML = `<span class="kg-tomb-name"></span><span class="kg-tomb-ttl"></span>`;+ const nameEl = label.querySelector('.kg-tomb-name');+ const ttlEl = label.querySelector('.kg-tomb-ttl');+ nameEl.textContent = `${tomb.ownerName || 'someone'}’s bag`;+ document.getElementById('kg-labels')?.appendChild(label);++ this.tombViews.set(id, { group, tomb, label, nameEl, ttlEl });+ }+ _tombChange(tomb, id) {+ const v = this.tombViews.get(id);+ if (!v) return;+ v.tomb = tomb;+ const w = this._tileToWorld(tomb.tx, tomb.ty);+ v.group.position.set(w.x, 0, w.z);+ v.nameEl.textContent = `${tomb.ownerName || 'someone'}’s bag`;+ // Keep an open recovery panel in sync as items flow out of the bag.+ if (this._lootTombId === id) this._renderLootPanel();+ }+ _tombRemove(id) {+ const v = this.tombViews.get(id);+ if (v) { this.objectGroup.remove(v.group); v.label.remove(); this.tombViews.delete(id); }+ // If the open panel's bag just vanished (looted dry or expired), close it.+ if (this._lootTombId === id) this._closeLootPanel();+ }++ _buildTombView(id) {+ const g = new Group();+ // A small earth mound + a glowing headstone slab. The cool violet emissive+ // keys it to the "lootable death-bag" colour used on the panel + portals.+ const mound = new Mesh(+ new CylinderGeometry(0.5, 0.6, 0.18, 16),+ new MeshStandardMaterial({ color: 0x3a2f4a, roughness: 1 }),+ );+ mound.position.y = 0.09; mound.receiveShadow = true;+ const slabMat = new MeshStandardMaterial({ color: 0x6b5a8a, roughness: 0.7, emissive: 0x2a1f4a, emissiveIntensity: 0.6 });+ const slab = new Mesh(new BoxGeometry(0.5, 0.7, 0.14), slabMat);+ slab.position.y = 0.52; slab.castShadow = true;+ const cap = new Mesh(new CylinderGeometry(0.25, 0.25, 0.14, 16, 1, false, 0, Math.PI), slabMat);+ cap.rotation.x = Math.PI / 2; cap.position.set(0, 0.87, 0);+ g.add(mound, slab, cap);+ // Tag every mesh so a raycast hit can resolve back to the tombstone id.+ g.traverse((o) => { o.userData.tombId = id; });+ return g;+ }++ // ---------------------------------------------------------------- death & loot+ // The local player died: stash the notice so the respawn overlay can describe+ // the drop, and close any open bag panel (you can't loot while dead).+ _onDied(info) {+ this._deathInfo = info || null;+ this._closeLootPanel();+ // The 'died' notice can land a frame after the dead-flag patch already+ // showed the overlay — refresh the message so the drop detail isn't lost.+ if (this._deathShown && this.hud.deathMsg) this.hud.deathMsg.textContent = this._deathMessage();+ }++ _deathMessage() {+ const info = this._deathInfo;+ let msg = 'You died.';+ if (info?.byName) msg = `Slain by ${info.byName}.`;+ if (info?.danger && info?.dropped > 0) {+ msg += ` Your bag (${info.dropped} item${info.dropped === 1 ? '' : 's'}) dropped where you fell — get back to recover it.`;+ } else if (info && !info.danger) {+ msg += ' Your belongings are safe here.';+ }+ return msg;+ }++ // A tap (not a drag) in the world. Two world interactions resolve from a pick:+ // click an adjacent tombstone to loot it, or click the pond (water / a shore+ // spot) to cast a line. Camera drags are filtered out before we get here.+ _onTap(clientX, clientY) {+ if (this.phase !== 'world') return;+ const me = this._localView();+ if (!me || me.dead) return;+ this._ptr.x = (clientX / window.innerWidth) * 2 - 1;+ this._ptr.y = -(clientY / window.innerHeight) * 2 + 1;+ this._raycaster.setFromCamera(this._ptr, this.camera);++ // 1) Tombstone under the cursor (dynamic objects).+ if (this.tombViews.size) {+ const hits = this._raycaster.intersectObject(this.objectGroup, true);+ let id = null;+ for (const h of hits) {+ const t = h.object?.userData?.tombId;+ if (t && this.tombViews.has(t)) { id = t; break; }+ }+ if (id) {+ const v = this.tombViews.get(id);+ if (Math.abs(me.tx - v.tomb.tx) > 1 || Math.abs(me.ty - v.tomb.ty) > 1) {+ this._toast({ kind: 'tomb', text: 'Walk up to the bag to loot it.' });+ this._openLootPanel(id); // still show contents so they know what's inside+ } else {+ this.net?.tombLoot(id);+ this._openLootPanel(id);+ }+ return;+ }+ }++ // 2) A resource node, mob, or NPC under the cursor → set it as the target+ // the loop walks to and interacts with (gather / attack / talk).+ const objHits = this._raycaster.intersectObject(this.objectGroup, true);+ for (const hp of objHits) {+ const ud = hp.object?.userData || {};+ if (ud.nodeId && this.nodeViews.has(ud.nodeId)) { this._setTarget('node', ud.nodeId); return; }+ if (ud.mobId && this.mobViews.has(ud.mobId)) { this._setTarget('mob', ud.mobId); return; }+ if (ud.npcId && this.npcViews.has(ud.npcId)) { this._setTarget('npc', ud.npcId); return; }+ }++ // 3) Ground pick: water / a shore spot is a cast intent; otherwise a walkable+ // tile is a click-to-walk move target.+ const tile = this._pickGroundTile();+ if (tile) {+ const onWater = this._waterTiles?.has(`${tile.tx},${tile.ty}`);+ const onSpot = (this.realm?.fishing || []).some((f) => f.tx === tile.tx && f.ty === tile.ty);+ if (onWater || onSpot) { this._attemptCast(); return; }+ if (this._isWalkable(tile.tx, tile.ty)) { this._target = { kind: 'tile', tx: tile.tx, ty: tile.ty }; this._interactAccum = 0; }+ }+ }++ // Set a click-to-interact target (node/mob/npc). Walking + the action itself+ // are serviced by the loop (_stepTowardTarget / _serviceInteraction).+ _setTarget(kind, id) {+ this._target = { kind, id };+ this._interactAccum = INTERACT_ACTION_MS; // act on the first adjacent frame+ }++ // Raycast the static realm geometry (ground + water + painted tiles) and turn+ // the first hit point into a tile index. Returns null if the ray missed.+ _pickGroundTile() {+ const hits = this._raycaster.intersectObject(this.staticGroup, true);+ if (!hits.length) return null;+ const p = hits[0].point;+ const c = (this.realm?.grid ?? 48) / 2;+ return { tx: Math.round(p.x / TILE + c - 0.5), ty: Math.round(p.z / TILE + c - 0.5) };+ }++ // ---------------------------------------------------------------- fishing+ // Cast a line. Mirrors the server's gates client-side for instant feedback+ // (adjacent to water, holding a rod) before sending the intent; the server+ // stays authoritative for the catch roll. The rod is auto-equipped from the+ // hotbar the same way the Cook/Eat actions resolve their requirements, so a+ // player never has to hunt for a slot to fish.+ _attemptCast() {+ const me = this._localView();+ const ps = this.net?.state?.players?.get(this.myId);+ if (!me || !ps || me.dead) return;+ if (!this._nearFishingSpot(ps.tx, ps.ty)) {+ this._toast({ kind: 'fish', text: 'Move next to the water to cast.' });+ return;+ }+ if (!this._ensureRodEquipped(ps)) {+ this._toast({ kind: 'tool', text: 'You need a fishing rod to cast.' });+ return;+ }+ this.net?.fish();+ this._spawnCast(ps.tx, ps.ty);+ }++ _nearFishingSpot(tx, ty) {+ for (const f of this.realm?.fishing || []) {+ if (Math.abs(tx - f.tx) <= 1 && Math.abs(ty - f.ty) <= 1) return true;+ }+ return false;+ }++ _hasRod(ps) {+ return ps.hotbar.some((s) => s.item === 'rod') || ps.inv.some((s) => s.item === 'rod');+ }++ // Make sure the rod is the active hotbar tool. Returns true if it already is or+ // we just equipped it; false if the player has no rod on the hotbar at all.+ _ensureRodEquipped(ps) {+ if (ps.hotbar[ps.activeSlot]?.item === 'rod') return true;+ for (let i = 0; i < ps.hotbar.length; i++) {+ if (ps.hotbar[i].item === 'rod') { this.net?.equip(i); return true; }+ }+ return false;+ }++ // World position of the water tile nearest (tx,ty) — where the bobber lands.+ _nearestWaterWorld(tx, ty) {+ let best = null, bd = Infinity;+ for (const r of this.realm?.water || []) {+ const cx = Math.max(r.x0, Math.min(tx, r.x1));+ const cy = Math.max(r.y0, Math.min(ty, r.y1));+ const dist = (cx - tx) ** 2 + (cy - ty) ** 2;+ if (dist < bd) { bd = dist; best = { tx: cx, ty: cy }; }+ }+ return best ? this._tileToWorld(best.tx, best.ty) : null;+ }++ // Spawn the cast visual: a line from the angler to a bobber floating on the+ // water, with an expanding ripple. Local-only and replaced on each new cast.+ _spawnCast(tx, ty) {+ this._clearCast();+ const w = this._nearestWaterWorld(tx, ty) || this._tileToWorld(tx, ty);+ const group = new Group();++ const baseY = 0.34;+ const bob = new Mesh(+ new SphereGeometry(0.12, 12, 10),+ new MeshStandardMaterial({ color: 0xff5a4d, emissive: 0x4a1009, emissiveIntensity: 0.5, roughness: 0.5 }),+ );+ bob.position.set(w.x, baseY, w.z);+ group.add(bob);++ const ring = new Mesh(+ new RingGeometry(0.16, 0.24, 22),+ new MeshBasicMaterial({ color: 0x9fe4ff, transparent: true, opacity: 0.6, side: DoubleSide }),+ );+ ring.rotation.x = -Math.PI / 2;+ ring.position.set(w.x, 0.27, w.z);+ group.add(ring);++ const lineGeo = new BufferGeometry();+ lineGeo.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 0], 3));+ const line = new Line(lineGeo, new LineBasicMaterial({ color: 0xeaf4ff, transparent: true, opacity: 0.7 }));+ group.add(line);++ this.objectGroup.add(group);+ this._cast = { group, bob, ring, line, lineGeo, baseY, start: performance.now(), resolved: false, resolvedAt: 0, caught: false };+ }++ // Per-frame cast animation: bob the float, loop the ripple, and keep the line+ // anchored to the angler's hands. After the server resolves the cast, play a+ // short bite splash (or quiet sink on a miss) then dispose.+ _tickCast(now) {+ const c = this._cast;+ if (!c) return;+ const t = (now - c.start) / 1000;+ c.bob.position.y = c.baseY + Math.sin(t * 5) * 0.04;++ if (c.resolved) {+ const since = now - c.resolvedAt;+ const k = Math.min(1, since / 280);+ c.ring.scale.setScalar(0.8 + k * (c.caught ? 2.8 : 1.4));+ c.ring.material.opacity = Math.max(0, 0.6 * (1 - k));+ if (since > 320) { this._clearCast(); return; }+ } else {+ const rp = (t % 0.9) / 0.9;+ c.ring.scale.setScalar(0.6 + rp * 1.6);+ c.ring.material.opacity = (1 - rp) * 0.55;+ // Safety net: if the result never arrives (e.g. a silently dropped cast),+ // reel the line in after a beat rather than leaving it dangling.+ if (now - c.start > 2400) { this._clearCast(); return; }+ }++ const me = this._localView();+ if (me) {+ const pos = c.lineGeo.attributes.position;+ pos.setXYZ(0, me.rig.position.x, (me.height || 1.6) * 0.85, me.rig.position.z);+ pos.setXYZ(1, c.bob.position.x, c.bob.position.y, c.bob.position.z);+ pos.needsUpdate = true;+ }+ }++ // Resolve the active cast from the authoritative result (a 'fish'/'full'+ // notice). `caught` greens the bobber and triggers a bigger bite splash.+ _resolveCast(caught) {+ const c = this._cast;+ if (!c || c.resolved) return;+ c.resolved = true;+ c.resolvedAt = performance.now();+ c.caught = !!caught;+ if (caught) c.bob.material.color.set(0x6ee787);+ }++ _clearCast() {+ const c = this._cast;+ if (!c) return;+ this.objectGroup.remove(c.group);+ c.group.traverse((o) => { o.geometry?.dispose?.(); o.material?.dispose?.(); });+ this._cast = null;+ }++ _openLootPanel(id) {+ this._lootTombId = id;+ const panel = this.hud.tombPanel;+ if (!panel) return;+ panel.hidden = false;+ requestAnimationFrame(() => panel.classList.add('kg-tomb-panel--in'));+ this._renderLootPanel();+ }++ _closeLootPanel() {+ this._lootTombId = null;+ const panel = this.hud.tombPanel;+ if (!panel) return;+ panel.classList.remove('kg-tomb-panel--in');+ setTimeout(() => { if (!this._lootTombId) panel.hidden = true; }, 240);+ }++ _renderLootPanel() {+ const panel = this.hud.tombPanel;+ const v = this._lootTombId ? this.tombViews.get(this._lootTombId) : null;+ if (!panel || !v) return;+ const tomb = v.tomb;+ this.hud.tombOwner.textContent = `${tomb.ownerName || 'someone'}’s bag`;+ const items = (tomb.items || []).filter((s) => s.item && s.qty > 0);+ const list = this.hud.tombItems;+ list.innerHTML = '';+ if (!items.length) {+ const empty = document.createElement('div');+ empty.className = 'kg-tomb-empty';+ empty.textContent = 'This bag is empty.';+ list.appendChild(empty);+ this.hud.tombTake.disabled = true;+ } else {+ for (const s of items) {+ const row = document.createElement('div');+ row.className = 'kg-tomb-item';+ row.innerHTML =+ `<span class="kg-tomb-chip" style="--chip:${itemColor(s.item)}"></span>` ++ `<span class="kg-tomb-iname">${itemLabel(s.item)}</span>` ++ `<span class="kg-tomb-iqty">×${s.qty}</span>`;+ list.appendChild(row);+ }+ this.hud.tombTake.disabled = false;+ }+ this._updateTombPanelTtl();+ }++ _updateTombPanelTtl() {+ const v = this._lootTombId ? this.tombViews.get(this._lootTombId) : null;+ if (!v || !this.hud.tombTtl) return;+ const ms = Math.max(0, v.tomb.expiresAt - Date.now());+ this.hud.tombTtl.textContent = `expires in ${Math.ceil(ms / 1000)}s`;+ }+// ---------------------------------------------------------------- banking / notices- // Bank contents arrive here (T9 renders the bank UI). Kept so the server's- // 'bank' message has a real consumer and the latest snapshot is available.- _onBank(payload) { this._bank = payload?.slots || []; }+ // Bank contents arrive here and feed the HUD's bank panel (the "Stored" column).+ _onBank(payload) {+ this._bank = payload?.slots || [];+ this.q?.setBank(this._bank.map((s) => ({ item: s.item, qty: s.qty })));+ }++ // Authoritative quest snapshot: drive the panel, refresh Aldric's "!"/"?"+ // markers, and open the NPC dialog when the snapshot answers a talk.+ _onQuests(snapshot) {+ this.quests = snapshot || null;+ this.q?.setQuests(this.quests);+ this._refreshNpcMarkers();+ if (snapshot?.npc && this.npcViews.has(snapshot.npc)) {+ this.q?.openNpc(this.npcViews.get(snapshot.npc).npc.name);+ }+ }++ // Server notices route here so a few carry an extra flourish beyond the+ // toast: a successful bite reports "+N HP", which we echo as a green flash+ // on the local nameplate so the heal reads on the avatar too.+ _onNotice(n) {+ this._toast(n);+ if (n?.kind === 'eat' && /^\+\d/.test(n.text || '')) this._healFlash();+ // Resolve the in-water cast from the authoritative result: a 'fish' notice is+ // the catch/miss verdict; 'full' (or a tool gate) ends a cast that can't land.+ if (n?.kind === 'fish') this._resolveCast(/caught/i.test(n.text || ''));+ else if ((n?.kind === 'full' || n?.kind === 'tool') && this._cast) this._resolveCast(false);+ }_toast({ kind, text }) {if (!text) return;@@ -513,23 +1267,259 @@ export class IsoGame {setTimeout(() => { el.classList.remove('kg-toast--in'); setTimeout(() => el.remove(), 300); }, 2600);}+ // ---------------------------------------------------------------- cooking & food+ // Contextual action bar. The client surfaces the two world actions it supports+ // today — Cook (at a Roast Pit, with raw fish) and Eat (when hurt and carrying+ // food) — only when they're actually possible, reading the local player's live+ // server state each frame. Both drive the server's cook/consume intents, so a+ // future full inventory UI can reuse the exact same path.+ _updateActions() {+ const bar = this.hud.actions;+ if (!bar) return;+ const me = this._localView();+ const ps = this.net?.state?.players?.get(this.myId);+ if (!me || !ps || me.dead) { if (!bar.hidden) bar.hidden = true; return; }++ // Cook: on/next to a Roast Pit AND carrying raw fish.+ const fishN = this._countItem(ps, 'fish');+ const showCook = fishN > 0 && this._nearCookingTile(ps.tx, ps.ty);+ this._toggleAction(this.hud.cookBtn, showCook, `Cook fish (${fishN})`);++ // Eat: below max HP AND carrying something edible.+ const edible = this._findEdibleSlot(ps);+ const showEat = ps.hp < ps.maxHp && !!edible;+ this._eatRef = showEat ? edible.ref : null;+ this._toggleAction(this.hud.eatBtn, showEat, showEat ? `Eat ${edible.label} (${edible.count})` : 'Eat');++ // Cast: standing beside fishable water. The rod auto-equips on cast, so the+ // button just reflects whether the player owns one — when they don't, it+ // reads "Need a rod" and explains on click (casting is gated, not silent).+ const showCast = this._nearFishingSpot(ps.tx, ps.ty);+ const hasRod = this._hasRod(ps);+ this._toggleAction(this.hud.castBtn, showCast, hasRod ? 'Cast line 🎣' : 'Need a rod 🎣');+ if (this.hud.castBtn) this.hud.castBtn.classList.toggle('kg-action--muted', showCast && !hasRod);++ bar.hidden = !(showCook || showEat || showCast);+ }++ _toggleAction(btn, show, label) {+ if (!btn) return;+ if (btn.hidden === show) btn.hidden = !show;+ if (show) {+ const lbl = btn.querySelector('.kg-action-lbl');+ if (lbl && lbl.textContent !== label) lbl.textContent = label;+ }+ }++ _nearCookingTile(tx, ty) {+ for (const t of this.realm?.cooking || []) {+ if (Math.abs(tx - t.tx) <= 1 && Math.abs(ty - t.ty) <= 1) return true;+ }+ return false;+ }++ _countItem(ps, item) {+ let n = 0;+ for (const s of ps.inv) if (s.item === item) n += s.qty;+ for (const s of ps.hotbar) if (s.item === item) n += s.qty;+ return n;+ }++ // The first edible slot — hotbar before backpack — with the server-resolvable+ // {zone,i} ref, a friendly label, and how many of that food the player holds.+ _findEdibleSlot(ps) {+ const scan = (arr, zone) => {+ for (let i = 0; i < arr.length; i++) {+ const it = arr[i].item;+ if (it && EDIBLE.has(it)) return { ref: { zone, i }, item: it, label: FOOD_LABEL[it] || 'food', count: this._countItem(ps, it) };+ }+ return null;+ };+ return scan(ps.hotbar, 'hotbar') || scan(ps.inv, 'inv');+ }++ // A successful cook ('cooked' event) — pulse the Cook button so the action+ // reads as landed; the honest result (cooked/burned counts) arrives as a toast.+ _onCooked() {+ const btn = this.hud.cookBtn;+ if (!btn || btn.hidden) return;+ btn.classList.remove('kg-action--pulse');+ void btn.offsetWidth; // restart the animation+ btn.classList.add('kg-action--pulse');+ }++ // Flash the local nameplate green when the player eats, so the heal reads on+ // the avatar, not just in a toast.+ _healFlash() {+ const me = this._localView();+ if (!me?.label) return;+ me.label.classList.remove('kg-heal');+ void me.label.offsetWidth;+ me.label.classList.add('kg-heal');+ setTimeout(() => me.label?.classList.remove('kg-heal'), 700);+ }++ // ---------------------------------------------------------------- skills+ // The server replies to a 'skills' request with the local player's own XP+ // detail (raw XP is never broadcast to peers). Cache the snapshot and, when+ // the panel is open, re-render its bars.+ _onSkills(payload) {+ this._skills = payload && payload.skills ? payload : null;+ if (this._skillsOpen) this._renderSkills();+ }++ // A real server 'levelup' event: refresh the panel snapshot (so its bar/level+ // jump immediately) and fire a celebratory toast with the skill's icon.+ _onLevelup({ skill, level } = {}) {+ const meta = SKILL_META[skill];+ if (!meta || !Number.isFinite(level)) return;+ this.net?.skills(); // pull fresh XP so an open panel reflects the new level++ const cap = this._skills?.cap || 99;+ const maxed = level >= cap;+ const el = document.createElement('div');+ el.className = 'kg-levelup';+ el.style.setProperty('--kg-hue', meta.hue);+ el.innerHTML =+ `<span class="kg-levelup-ico"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="${meta.icon}"/></svg></span>` ++ `<span class="kg-levelup-txt">` ++ `<span class="kg-levelup-kicker">${maxed ? 'Skill mastered' : 'Level up'}</span>` ++ `<span class="kg-levelup-main">${meta.label} <b>${level}</b></span>` ++ `</span>`;+ this.hud.levelups?.appendChild(el);+ requestAnimationFrame(() => el.classList.add('kg-levelup--in'));+ setTimeout(() => { el.classList.remove('kg-levelup--in'); setTimeout(() => el.remove(), 420); }, 3400);+ }++ // Open/close the skills drawer. `force` (true/false) sets an explicit state;+ // omitting it toggles. On open we pull a fresh snapshot and start a light poll+ // so XP bars fill in real time as the player gathers/fights.+ _toggleSkills(force) {+ const next = force === undefined ? !this._skillsOpen : !!force;+ if (next === this._skillsOpen) return;+ // Only meaningful in the world; ignore opens from the start/offline screens.+ if (next && this.phase !== 'world') return;+ this._skillsOpen = next;++ const panel = this.hud.skillsPanel;+ this.hud.skillsBtn?.setAttribute('aria-expanded', String(next));+ if (!panel) return;++ if (next) {+ panel.hidden = false;+ void panel.offsetWidth; // reflow so the slide-in transition runs+ panel.classList.add('kg-skills--open');+ this._renderSkills(); // paint cached data (or the loading row)+ this.net?.skills(); // and request the freshest snapshot+ clearInterval(this._skillsTimer);+ this._skillsTimer = setInterval(() => this.net?.skills(), 1500);+ this.hud.skillsClose?.focus();+ } else {+ panel.classList.remove('kg-skills--open');+ clearInterval(this._skillsTimer);+ this._skillsTimer = null;+ if (document.activeElement && panel.contains(document.activeElement)) this.hud.skillsBtn?.focus();+ // Hide after the slide-out so it isn't focusable mid-transition.+ setTimeout(() => { if (!this._skillsOpen) panel.hidden = true; }, 220);+ }+ }++ _renderSkills() {+ const list = this.hud.skillsList;+ if (!list) return;+ const data = this._skills;+ if (!data) {+ list.setAttribute('aria-busy', 'true');+ list.innerHTML = '<li class="kg-skills-loading">Loading your progress…</li>';+ return;+ }+ list.setAttribute('aria-busy', 'false');+ const cap = data.cap || 99;+ if (this.hud.skillsCap) this.hud.skillsCap.textContent = String(cap);+ if (this.hud.skillsTotal) this.hud.skillsTotal.textContent = data.total != null ? String(data.total) : '—';+ if (this.hud.skillsAvg) this.hud.skillsAvg.textContent = data.average != null ? data.average.toFixed(1) : '—';++ const rows = [];+ for (const skill of SKILL_ORDER) {+ const s = data.skills[skill];+ const meta = SKILL_META[skill];+ if (!s || !meta) continue;+ const maxed = s.level >= cap;+ const fresh = s.level <= 1 && (s.xp | 0) === 0;+ let pct, xpLabel, aria;+ if (maxed) {+ pct = 1;+ xpLabel = 'Mastered';+ aria = `${meta.label} mastered, level ${cap}`;+ } else {+ const span = Math.max(1, s.nextXp - s.levelXp);+ const into = Math.max(0, Math.min(span, s.xp - s.levelXp));+ pct = into / span;+ xpLabel = `${fmtXp(into)} / ${fmtXp(span)} XP`;+ aria = `${meta.label} level ${s.level}, ${Math.round(pct * 100)}% to level ${s.level + 1}`;+ }+ const cls = 'kg-skill' + (maxed ? ' kg-skill--max' : '') + (fresh ? ' kg-skill--fresh' : '');+ rows.push(+ `<li class="${cls}" data-skill="${skill}" style="--kg-hue:${meta.hue}" aria-label="${aria}">` ++ `<span class="kg-skill-ico"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="${meta.icon}"/></svg></span>` ++ `<span class="kg-skill-main">` ++ `<span class="kg-skill-top">` ++ `<span class="kg-skill-name">${meta.label}</span>` ++ `<span class="kg-skill-lvl">${maxed ? '<em>MAX</em>' : ''}<b>${s.level}</b><i>/${cap}</i></span>` ++ `</span>` ++ `<span class="kg-skill-bar"><i style="width:${(pct * 100).toFixed(1)}%"></i></span>` ++ `<span class="kg-skill-xp">${xpLabel}</span>` ++ `</span>` ++ `</li>`,+ );+ }+ list.innerHTML = rows.join('');+ }+// ---------------------------------------------------------------- input_bindInput() {window.addEventListener('keydown', (e) => {if (this._typing()) return;- this.keys.add(e.key.toLowerCase());+ const k = e.key.toLowerCase();+ // Skills panel: K toggles, Escape closes it. Handled as discrete actions+ // (not movement keys) so they don't leak into the held-key set.+ if (k === 'k') { e.preventDefault(); this._toggleSkills(); return; }+ if (k === 'escape' && this._skillsOpen) { e.preventDefault(); this._toggleSkills(false); return; }+ // Quests panel: Q toggles, Escape closes any open quest/bank/NPC surface.+ if (k === 'q' && this.phase === 'world') { e.preventDefault(); this.q?.toggleQuests(); return; }+ // Hotbar number keys 1–6: select that slot (and ride a mount on it).+ if (this.phase === 'world' && k >= '1' && k <= '6') { e.preventDefault(); this._equipOrRide(+k - 1); return; }+ if (k === 'escape') { this.q?.closeQuests(); this.q?.closeBank(); this.q?.closeNpc(); }+ // Hotbar 1–6: equip that slot (server validates + patches activeSlot back).+ if (this.phase === 'world' && k >= '1' && k <= '6') { e.preventDefault(); this.net?.equip(parseInt(k, 10) - 1); return; }+ // Chat focus: C (or Enter) opens the chat input once in the world. The+ // _typing() guard above means held movement keys never leak into chat,+ // and opening clears the held set so the avatar doesn't walk while typing.+ if (this.phase === 'world' && (k === 'c' || k === 'enter')) { e.preventDefault(); this._openChat(); return; }+ this.keys.add(k);});window.addEventListener('keyup', (e) => this.keys.delete(e.key.toLowerCase()));window.addEventListener('blur', () => this.keys.clear());this.canvas.addEventListener('pointerdown', (e) => {- this._dragging = true; this._lastPtr = { x: e.clientX, y: e.clientY }; this._downAt = performance.now();+ this._dragging = true; this._lastPtr = { x: e.clientX, y: e.clientY };+ this._downAt = performance.now(); this._dragMoved = 0;+ });+ window.addEventListener('pointerup', (e) => {+ const wasDragging = this._dragging;+ this._dragging = false;+ // A short, near-stationary press over the canvas is a tap → world pick+ // (click an adjacent tombstone to loot it). A drag rotated the camera.+ if (!wasDragging || e.target !== this.canvas) return;+ if (performance.now() - this._downAt < 300 && this._dragMoved < 7) {+ this._onTap(e.clientX, e.clientY);+ }});- window.addEventListener('pointerup', () => { this._dragging = false; });window.addEventListener('pointermove', (e) => {if (!this._dragging) return;const dx = e.clientX - this._lastPtr.x, dy = e.clientY - this._lastPtr.y;this._lastPtr = { x: e.clientX, y: e.clientY };+ this._dragMoved += Math.abs(dx) + Math.abs(dy);this.camYaw -= dx * 0.005;this.camPitch = Math.max(0.45, Math.min(1.25, this.camPitch + dy * 0.004));});@@ -568,7 +1558,9 @@ export class IsoGame {if (this.keys.has('d') || this.keys.has('arrowright')) r += 1;if (this.keys.has('a') || this.keys.has('arrowleft')) r -= 1;if (this._joy) { f += -this._joy.z; r += this._joy.x; }- if (!f && !r) return;+ // No manual input: walk toward a click-to-interact / move target instead.+ if (!f && !r) { if (this._target) this._stepTowardTarget(me); return; }+ this._target = null; // manual movement overrides any click target// Camera basis on the ground plane. forward = camera→target.const fwd = { x: -Math.sin(this.camYaw), z: -Math.cos(this.camYaw) };@@ -598,6 +1590,93 @@ export class IsoGame {this.net?.step(tx, ty, yaw);}+ // The tile of the current target (a node/mob/npc view, or a plain move tile).+ // Returns null — and clears the target — once the target is gone (node+ // depleted, mob dead, view removed), so the loop never chases a ghost.+ _targetTile() {+ const t = this._target;+ if (!t) return null;+ if (t.kind === 'tile') return { tx: t.tx, ty: t.ty };+ if (t.kind === 'node') { const v = this.nodeViews.get(t.id); if (!v || v.node.depleted) return null; return { tx: v.node.tx, ty: v.node.ty }; }+ if (t.kind === 'mob') { const v = this.mobViews.get(t.id); if (!v || v.mob.dead) return null; return { tx: v.mob.tx, ty: v.mob.ty }; }+ if (t.kind === 'npc') { const v = this.npcViews.get(t.id); if (!v) return null; return { tx: v.npc.tx, ty: v.npc.ty }; }+ return null;+ }++ // One greedy 8-way step toward the current target. For interact targets we+ // stop once adjacent (the action fires from _serviceInteraction); for a plain+ // move tile we stop on arrival.+ _stepTowardTarget(me) {+ const t = this._targetTile();+ if (!t) { this._target = null; return; }+ const interact = this._target.kind !== 'tile';+ const adx = Math.abs(me.tx - t.tx), ady = Math.abs(me.ty - t.ty);+ if (interact ? (adx <= 1 && ady <= 1) : (me.tx === t.tx && me.ty === t.ty)) {+ if (!interact) this._target = null; // arrived at a move tile+ return;+ }+ const dtx = Math.sign(t.tx - me.tx);+ const dty = Math.sign(t.ty - me.ty);+ const yaw = Math.atan2(dtx, dty);+ // Prefer the diagonal, then slide along whichever axis is clear; if fully+ // boxed in, give up on the target rather than jitter in place.+ if (dtx && dty && this._isWalkable(me.tx + dtx, me.ty + dty) &&+ (this._isWalkable(me.tx + dtx, me.ty) || this._isWalkable(me.tx, me.ty + dty))) {+ this._sendStep(me.tx + dtx, me.ty + dty, yaw);+ } else if (dtx && this._isWalkable(me.tx + dtx, me.ty)) {+ this._sendStep(me.tx + dtx, me.ty, yaw);+ } else if (dty && this._isWalkable(me.tx, me.ty + dty)) {+ this._sendStep(me.tx, me.ty + dty, yaw);+ } else if (dtx && dty && this._isWalkable(me.tx + dtx, me.ty + dty)) {+ this._sendStep(me.tx + dtx, me.ty + dty, yaw);+ } else {+ this._target = null; // boxed in — drop the target so we don't spin+ }+ }++ // When adjacent to an interact target, perform the action on the right cadence:+ // talk once (NPC), or repeatedly gather/attack (auto-equipping the matching+ // tool) until the node depletes / mob dies. Driven each frame from the loop.+ _serviceInteraction(dt) {+ const t = this._target;+ if (!t || t.kind === 'tile') return;+ const me = this._localView();+ const ps = this.net?.state?.players?.get(this.myId);+ if (!me || !ps || me.dead) return;+ const tile = this._targetTile();+ if (!tile) { this._target = null; return; }+ if (Math.abs(me.tx - tile.tx) > 1 || Math.abs(me.ty - tile.ty) > 1) return; // not there yet++ if (t.kind === 'npc') { this.net?.npcTalk(t.id); this._target = null; return; }++ this._interactAccum += dt * 1000;+ if (this._interactAccum < INTERACT_ACTION_MS) return;+ this._interactAccum = 0;+ if (t.kind === 'node') {+ const v = this.nodeViews.get(t.id);+ if (!v || v.node.depleted) { this._target = null; return; }+ this._equipForGather(ps, v.node.kind);+ this.net?.gather(t.id);+ } else if (t.kind === 'mob') {+ const v = this.mobViews.get(t.id);+ if (!v || v.mob.dead) { this._target = null; return; }+ this._equipTool(ps, 'sword');+ this.net?.attack(t.id);+ }+ }++ // Auto-equip the tool a node kind needs (axe for trees, pickaxe for rock/coal),+ // mirroring the rod auto-equip the fishing flow uses, so a click just works.+ _equipForGather(ps, kind) {+ this._equipTool(ps, kind === 'tree' ? 'axe' : 'pickaxe');+ }+ _equipTool(ps, tool) {+ if (ps.hotbar[ps.activeSlot]?.item === tool) return;+ for (let i = 0; i < ps.hotbar.length; i++) {+ if (ps.hotbar[i].item === tool) { this.net?.equip(i); return; }+ }+ }+// Client-side walkability mirror of the server (bounds + blocked + live node/// mob occupancy) so we don't spam steps the server will reject._isWalkable(tx, ty) {@@ -612,6 +1691,9 @@ export class IsoGame {for (const [, v] of this.mobViews) {if (!v.mob.dead && v.mob.tx === tx && v.mob.ty === ty) return false;}+ for (const [, v] of this.npcViews) {+ if (v.npc.tx === tx && v.npc.ty === ty) return false;+ }return true;}@@ -630,6 +1712,37 @@ export class IsoGame {status: document.getElementById('kg-status'),toasts: document.getElementById('kg-toasts'),hint: document.getElementById('kg-hint'),+ skillsBtn: document.getElementById('kg-skills-btn'),+ skillsPanel: document.getElementById('kg-skills'),+ skillsClose: document.getElementById('kg-skills-close'),+ skillsList: document.getElementById('kg-skills-list'),+ skillsTotal: document.getElementById('kg-skills-total'),+ skillsAvg: document.getElementById('kg-skills-avg'),+ skillsCap: document.getElementById('kg-skills-cap'),+ levelups: document.getElementById('kg-levelups'),+ actions: document.getElementById('kg-actions'),+ cookBtn: document.getElementById('kg-cook'),+ eatBtn: document.getElementById('kg-eat'),+ castBtn: document.getElementById('kg-cast'),+ chat: document.getElementById('kg-chat'),+ chatLog: document.getElementById('kg-chat-log'),+ chatForm: document.getElementById('kg-chat-form'),+ chatInput: document.getElementById('kg-chat-input'),+ chatMutedBtn: document.getElementById('kg-chat-muted-btn'),+ chatMutedN: document.getElementById('kg-chat-muted-n'),+ chatMutedList: document.getElementById('kg-chat-muted'),+ death: document.getElementById('kg-death'),+ deathMsg: document.getElementById('kg-death-msg'),+ deathCount: document.getElementById('kg-death-count'),+ tombPanel: document.getElementById('kg-tomb-panel'),+ tombOwner: document.getElementById('kg-tomb-owner'),+ tombItems: document.getElementById('kg-tomb-items'),+ tombTtl: document.getElementById('kg-tomb-ttl'),+ tombTake: document.getElementById('kg-tomb-take'),+ tombClose: document.getElementById('kg-tomb-close'),+ mount: document.getElementById('kg-mount'),+ mountName: document.getElementById('kg-mount-name'),+ dismountBtn: document.getElementById('kg-dismount'),};const savedName = localStorage.getItem('cc-name') || '';if (savedName) this.hud.nameInput.value = savedName;@@ -647,6 +1760,22 @@ export class IsoGame {this.phase = 'connecting';this.net ? this.net.retry() : this.start(this.hud.nameInput.value || this.hud.nameInput.placeholder);});++ this.hud.skillsBtn?.addEventListener('click', () => this._toggleSkills());+ this.hud.skillsClose?.addEventListener('click', () => this._toggleSkills(false));++ // Death-bag recovery panel: "Take all" re-sends tombLoot (useful once the+ // pack has space again); the X just dismisses the panel (the bag stays).+ this.hud.tombTake?.addEventListener('click', () => { if (this._lootTombId) this.net?.tombLoot(this._lootTombId); });+ this.hud.tombClose?.addEventListener('click', () => this._closeLootPanel());++ // Contextual action bar: cook a batch of fish, or eat the first food slot.+ this.hud.cookBtn?.addEventListener('click', () => this.net?.cook(5));+ this.hud.eatBtn?.addEventListener('click', () => { if (this._eatRef) this.net?.consume(this._eatRef); });+ this.hud.dismountBtn?.addEventListener('click', () => this.net?.dismount());+ this.hud.castBtn?.addEventListener('click', () => this._attemptCast());++ this._bindChat();this._setHudPhase('start');}@@ -655,9 +1784,284 @@ export class IsoGame {this.hud.offline.hidden = phase !== 'offline';this.hud.topbar.hidden = !(phase === 'world' || phase === 'connecting');this.hud.hint.hidden = phase !== 'world';+ // The contextual action bar only makes sense in-world; hide it elsewhere so+ // a reconnect/offline screen never shows stale Cook/Eat buttons.+ if (this.hud.actions && phase !== 'world') this.hud.actions.hidden = true;+ if (this.hud.mount && phase !== 'world') this.hud.mount.hidden = true;+ // The skills toggle is only meaningful once in the world; leaving it closes+ // the panel so a reconnect/offline screen never shows a stale drawer.+ if (phase !== 'world') this._toggleSkills(false);+ // World chat shows only in-world. Reveal the panel on entry; on exit close+ // and hide it so the start/offline screens stay clean.+ if (this.hud.chat) {+ this.hud.chat.hidden = phase !== 'world';+ if (phase !== 'world') this._closeChat(true);+ }+ // Death overlay + bag panel are world-only; clear them on any exit so a+ // reconnect never strands a respawn countdown or an orphaned bag panel.+ if (phase !== 'world') {+ this._deathInfo = null; this._deathShown = false;+ if (this.hud.death) this.hud.death.hidden = true;+ this._closeLootPanel();+ }document.body.classList.toggle('kg-loading-cursor', phase === 'connecting');}+ // ---------------------------------------------------------------- chat+ // World chat: send/receive realm-wide messages, route `/commands` through the+ // server command system, and mute players client-side. The panel is collapsed+ // (click-through) until focused so it never blocks the world.++ _loadMuted() {+ try {+ const raw = JSON.parse(localStorage.getItem('kg-muted') || '[]');+ return new Set(Array.isArray(raw) ? raw.filter((n) => typeof n === 'string') : []);+ } catch { return new Set(); }+ }++ _saveMuted() {+ try { localStorage.setItem('kg-muted', JSON.stringify([...this.muted])); } catch { /* storage may be unavailable */ }+ }++ _bindChat() {+ if (!this.hud.chat) return;+ this.hud.chatForm?.addEventListener('submit', (e) => { e.preventDefault(); this._sendChat(); });+ // Focusing the input expands the panel; blurring with nothing typed collapses it.+ this.hud.chatInput?.addEventListener('focus', () => this._openChat());+ this.hud.chatInput?.addEventListener('blur', (e) => {+ // Stay open if focus moved to another chat control (a sender name, the+ // Muted button, the mute menu) — only collapse when focus truly leaves.+ if (this.hud.chat?.contains(e.relatedTarget)) return;+ if (!this.hud.chatInput.value.trim()) this._closeChat();+ });+ this.hud.chatInput?.addEventListener('keydown', (e) => {+ // Esc clears + closes; everything else stays in the field (the global+ // keydown bails on _typing(), so movement keys never fire while chatting).+ if (e.key === 'Escape') { e.preventDefault(); this.hud.chatInput.value = ''; this._closeChat(); }+ e.stopPropagation();+ });+ this.hud.chatMutedBtn?.addEventListener('click', () => this._toggleMutedList());+ this._updateMutedCount();+ }++ _openChat() {+ if (!this.hud.chat || this.phase !== 'world') return;+ this.keys.clear(); // drop held movement keys so the avatar doesn't walk while typing+ if (!this._chatOpen) {+ this._chatOpen = true;+ this.hud.chat.classList.add('kg-chat--open');+ this._scrollChat();+ }+ if (document.activeElement !== this.hud.chatInput) this.hud.chatInput?.focus();+ }++ _closeChat(force) {+ this._closeMuteMenu();+ this._toggleMutedList(false);+ if (!this._chatOpen && !force) return;+ this._chatOpen = false;+ this.hud.chat?.classList.remove('kg-chat--open');+ if (document.activeElement === this.hud.chatInput) this.hud.chatInput.blur();+ }++ _sendChat() {+ const input = this.hud.chatInput;+ if (!input) return;+ const text = input.value.trim();+ input.value = '';+ if (!text) { this._closeChat(); return; }+ // Server is authoritative: it sanitizes, rate-limits, routes `/commands`, and+ // echoes accepted messages back to everyone (us included) as 'chat' events.+ this.net?.chat(text);+ input.focus(); // keep the field hot for a flowing conversation+ }++ _onChat(msg) {+ if (!msg || typeof msg.text !== 'string') return;+ const line = this._appendChatLine(msg);+ if (!line) return;+ // Hide muted senders (but never our own messages, even to a namesake).+ if (!msg.system && msg.id !== this.myId && this.muted.has(msg.name)) {+ line.classList.add('kg-chat-line--muted');+ return;+ }+ this._scrollChat();+ }++ _appendChatLine(msg) {+ const log = this.hud.chatLog;+ if (!log) return null;+ const line = document.createElement('div');+ line.className = 'kg-chat-line';+ if (msg.system) {+ line.classList.add('kg-chat-line--system');+ if (msg.kind === 'error') line.classList.add('kg-chat-line--error');+ const t = document.createElement('span');+ t.className = 'kg-chat-text';+ t.textContent = msg.text;+ line.appendChild(t);+ } else {+ const name = msg.name || 'player';+ line.dataset.name = name;+ const isMe = msg.id && msg.id === this.myId;+ const nameEl = document.createElement('button');+ nameEl.type = 'button';+ nameEl.className = 'kg-chat-name' + (isMe ? ' kg-chat-name--me' : '');+ nameEl.textContent = name;+ if (isMe) {+ nameEl.disabled = true;+ } else {+ nameEl.title = `Mute ${name}`;+ nameEl.setAttribute('aria-label', `Mute ${name}`);+ nameEl.addEventListener('click', (e) => this._openMuteMenu(e, name));+ }+ const t = document.createElement('span');+ t.className = 'kg-chat-text';+ t.textContent = msg.text;+ line.append(nameEl, t);+ }+ log.appendChild(line);+ // Bound the scrollback so a long session can't grow the DOM without limit.+ while (log.children.length > 120) log.removeChild(log.firstChild);+ return line;+ }++ // Local-only system line (mute confirmations) — same look as server replies.+ _sysLine(text, kind) {+ this._onChat({ system: true, kind: kind || 'system', text, ts: Date.now() });+ }++ _scrollChat() {+ const log = this.hud.chatLog;+ if (!log) return;+ // Auto-scroll only when already near the bottom (or collapsed, which always+ // pins to the latest) so reading scrollback isn't yanked away.+ const nearBottom = log.scrollHeight - log.scrollTop - log.clientHeight < 60;+ if (nearBottom || !this._chatOpen) log.scrollTop = log.scrollHeight;+ }++ // ----- mute ------------------------------------------------------------++ _openMuteMenu(e, name) {+ if (!name || !this.hud.chat) return;+ this._closeMuteMenu();+ const muted = this.muted.has(name);+ const menu = document.createElement('div');+ menu.className = 'kg-chat-menu';+ menu.setAttribute('role', 'menu');+ const btn = document.createElement('button');+ btn.type = 'button';+ btn.className = 'kg-chat-menu-btn';+ btn.setAttribute('role', 'menuitem');+ btn.textContent = (muted ? 'Unmute ' : 'Mute ') + name;+ btn.addEventListener('click', () => {+ if (muted) this._unmute(name); else this._mute(name);+ this._closeMuteMenu();+ });+ menu.appendChild(btn);+ this.hud.chat.appendChild(menu);+ // Float the popover just above the clicked name, clamped inside the panel.+ const target = e.currentTarget.getBoundingClientRect();+ const host = this.hud.chat.getBoundingClientRect();+ const left = Math.max(0, Math.min(target.left - host.left, host.width - menu.offsetWidth));+ menu.style.left = `${left}px`;+ menu.style.bottom = `${host.bottom - target.top + 4}px`;+ this._muteMenu = menu;+ btn.focus();+ // Dismiss on outside click or Escape.+ this._muteMenuCloser = (ev) => {+ if (ev.type === 'keydown' && ev.key !== 'Escape') return;+ if (ev.type === 'pointerdown' && menu.contains(ev.target)) return;+ this._closeMuteMenu();+ };+ setTimeout(() => {+ document.addEventListener('pointerdown', this._muteMenuCloser, true);+ document.addEventListener('keydown', this._muteMenuCloser, true);+ }, 0);+ }++ _closeMuteMenu() {+ if (this._muteMenuCloser) {+ document.removeEventListener('pointerdown', this._muteMenuCloser, true);+ document.removeEventListener('keydown', this._muteMenuCloser, true);+ this._muteMenuCloser = null;+ }+ if (this._muteMenu) { this._muteMenu.remove(); this._muteMenu = null; }+ }++ _mute(name) {+ if (!name) return;+ this.muted.add(name);+ this._saveMuted();+ this._applyMuteState(name);+ this._updateMutedCount();+ if (this._mutedListOpen) this._renderMutedList();+ this._sysLine(`Muted ${name}. Their messages are hidden.`);+ }++ _unmute(name) {+ if (!this.muted.delete(name)) return;+ this._saveMuted();+ this._applyMuteState(name);+ this._updateMutedCount();+ if (this._mutedListOpen) this._renderMutedList();+ this._sysLine(`Unmuted ${name}.`);+ }++ // Reveal or hide every existing line from a sender as their mute state flips —+ // so unmuting restores the scrollback, not just future messages.+ _applyMuteState(name) {+ const muted = this.muted.has(name);+ for (const line of this.hud.chatLog?.children || []) {+ if (line.dataset && line.dataset.name === name) {+ line.classList.toggle('kg-chat-line--muted', muted);+ }+ }+ if (!muted) this._scrollChat();+ }++ _updateMutedCount() {+ if (this.hud.chatMutedN) this.hud.chatMutedN.textContent = String(this.muted.size);+ }++ _toggleMutedList(force) {+ const list = this.hud.chatMutedList;+ if (!list) return;+ const open = force === undefined ? list.hidden : !!force;+ this._mutedListOpen = open;+ this.hud.chatMutedBtn?.setAttribute('aria-expanded', String(open));+ if (open) { this._renderMutedList(); list.hidden = false; }+ else list.hidden = true;+ }++ _renderMutedList() {+ const list = this.hud.chatMutedList;+ if (!list) return;+ list.replaceChildren();+ if (!this.muted.size) {+ const empty = document.createElement('div');+ empty.className = 'kg-chat-muted-empty';+ empty.textContent = 'No muted players.';+ list.appendChild(empty);+ return;+ }+ for (const name of [...this.muted].sort((a, b) => a.localeCompare(b))) {+ const row = document.createElement('div');+ row.className = 'kg-chat-muted-row';+ const nm = document.createElement('span');+ nm.className = 'kg-chat-muted-name';+ nm.textContent = name;+ const btn = document.createElement('button');+ btn.type = 'button';+ btn.className = 'kg-chat-unmute';+ btn.textContent = 'Unmute';+ btn.setAttribute('aria-label', `Unmute ${name}`);+ btn.addEventListener('click', () => this._unmute(name));+ row.append(nm, btn);+ list.appendChild(row);+ }+ }+// ---------------------------------------------------------------- loop_loop() {requestAnimationFrame(this._loop);@@ -668,10 +2072,16 @@ export class IsoGame {if (this.phase === 'world') {this._stepAccum += now - (this._stepLast || now);this._stepLast = now;- if (this._stepAccum >= STEP_INTERVAL_MS) { this._stepAccum = 0; this._attemptStep(); }+ if (this._stepAccum >= this._stepInterval()) { this._stepAccum = 0; this._attemptStep(); }+ this._serviceInteraction(dt);for (const [, v] of this.players) v.tick(dt);this._updateCamera();this._updateLabels();+ this._updateNpcLabels();+ this._updateTombLabels();+ this._updateDeathOverlay();+ this._updateActions();+ this._tickCast(now);} else {this._stepLast = now;this._idleCamera(dt);@@ -722,6 +2132,64 @@ export class IsoGame {}}+ // Project each NPC's nameplate + quest marker to screen space.+ _updateNpcLabels() {+ if (!this.npcViews.size) return;+ const w = window.innerWidth, h = window.innerHeight;+ const v = new Vector3();+ for (const [, nv] of this.npcViews) {+ v.set(nv.group.position.x, nv.height + 0.5, nv.group.position.z).project(this.camera);+ if (v.z > 1) { nv.label.style.display = 'none'; continue; }+ nv.label.style.display = '';+ const sx = (v.x * 0.5 + 0.5) * w;+ const sy = (-v.y * 0.5 + 0.5) * h;+ nv.label.style.transform = `translate(-50%, -100%) translate(${sx.toFixed(1)}px, ${sy.toFixed(1)}px)`;+ }+ }++ // Project each tombstone's headstone to screen space, place its DOM label, and+ // tick the live "expires in Xs" countdown straight off the synced expiresAt.+ _updateTombLabels() {+ if (!this.tombViews.size) return;+ const w = window.innerWidth, h = window.innerHeight;+ const now = Date.now();+ const v = new Vector3();+ for (const [, tv] of this.tombViews) {+ v.set(tv.group.position.x, 1.2, tv.group.position.z).project(this.camera);+ if (v.z > 1) { tv.label.style.display = 'none'; continue; }+ tv.label.style.display = '';+ const sx = (v.x * 0.5 + 0.5) * w;+ const sy = (-v.y * 0.5 + 0.5) * h;+ tv.label.style.transform = `translate(-50%, -100%) translate(${sx.toFixed(1)}px, ${sy.toFixed(1)}px)`;+ const secs = Math.max(0, Math.ceil((tv.tomb.expiresAt - now) / 1000));+ tv.ttlEl.textContent = `${secs}s`;+ tv.label.classList.toggle('kg-tomb-soon', secs <= 45);+ }+ if (this._lootTombId) this._updateTombPanelTtl();+ }++ // Show/hide the respawn overlay from the local player's authoritative state.+ // The countdown reads the synced respawnAt; the overlay clears the instant the+ // server marks us alive again (the schema flip), never a client-side guess.+ _updateDeathOverlay() {+ const me = this._localView();+ const death = this.hud.death;+ if (!death) return;+ if (me?.dead) {+ if (!this._deathShown) {+ this._deathShown = true;+ death.hidden = false;+ this.hud.deathMsg.textContent = this._deathMessage();+ }+ const ms = Math.max(0, (me.respawnAt || 0) - Date.now());+ this.hud.deathCount.textContent = me.respawnAt ? `Respawning in ${Math.ceil(ms / 1000)}s` : 'Respawning…';+ } else if (this._deathShown) {+ this._deathShown = false;+ this._deathInfo = null;+ death.hidden = true;+ }+ }+_onResize() {this.camera.aspect = window.innerWidth / window.innerHeight;this.camera.updateProjectionMatrix();@@ -729,9 +2197,17 @@ export class IsoGame {}destroy() {+ clearInterval(this._skillsTimer);+ this._skillsTimer = null;+ this._closeMuteMenu();this.net?.destroy();for (const [, v] of this.players) v.dispose();this.players.clear();+ for (const [, tv] of this.tombViews) { this.objectGroup.remove(tv.group); tv.label.remove(); }+ this.tombViews.clear();+ this._disposeNpcs();+ this.q?.destroy();+ this._clearCast();this._nipple?.destroy();}}diff --git a/src/game/items.js b/src/game/items.jsnew file mode 100644index 000000000..7358e5b31--- /dev/null+++ b/src/game/items.js@@ -0,0 +1,29 @@+// Item display metadata for the /play client — names + glyphs the hotbar and+// inventory render. The authoritative item ids and quantities come from the+// server schema (GamePlayer.inv / .hotbar); this map is presentation only and+// mirrors the server's item vocabulary (tools, gathered resources, currency).+// Unknown ids degrade gracefully to a readable label + initial glyph so a new+// server-side item never renders as a blank slot.++export const ITEM_DISPLAY = {+ axe: { name: 'Axe', glyph: '🪓' },+ pickaxe: { name: 'Pickaxe', glyph: '⛏️' },+ rod: { name: 'Fishing rod', glyph: '🎣' },+ hammer: { name: 'Hammer', glyph: '🔨' },+ sword: { name: 'Sword', glyph: '⚔️' },+ wood: { name: 'Wood', glyph: '🪵' },+ stone: { name: 'Stone', glyph: '🪨' },+ coal: { name: 'Coal', glyph: '🪨' },+ fish: { name: 'Fish', glyph: '🐟' },+ gold: { name: 'Gold', glyph: '🪙' },+};++export function itemDisplay(id) {+ if (!id) return null;+ const known = ITEM_DISPLAY[id];+ if (known) return known;+ const name = String(id)+ .replace(/[-_]/g, ' ')+ .replace(/^\w/, (m) => m.toUpperCase());+ return { name, glyph: String(id).charAt(0).toUpperCase() };+}diff --git a/src/game/keybindings.js b/src/game/keybindings.jsnew file mode 100644index 000000000..d84686da1--- /dev/null+++ b/src/game/keybindings.js@@ -0,0 +1,191 @@+// Central keybinding registry for the isometric MMO client (/play).+//+// Single source of truth for action -> key. Both the renderer (iso-game.js) and+// the controls UI (iso-controls.js) route through this instead of hard-coding+// key literals, so a player can rebind anything and it persists. Movement+// (WASD / arrows) stays a held-key set in the renderer; this map owns the+// discrete actions the world guide specifies (hotbar, panels, camera, system).+//+// Persistence is per account. Until Task 16 (account-keyed persistence) lands we+// key on the chosen display name — the only stable account proxy the client has+// — through localStorage. `_load`/`_save` are the single seam Task 16 swaps for a+// server-backed store without touching any caller.++// Canonical action list, in display order, grouped for the settings UI. `def` is+// the default key (already normalized: lowercase, single tokens like 'escape').+// `fixed: true` marks system keys that must not be rebound (rebinding the key+// that closes dialogs would let a player lock themselves out of the UI).+export const ACTIONS = [+ { id: 'hotbar1', label: 'Hotbar slot 1', group: 'Hotbar', def: '1' },+ { id: 'hotbar2', label: 'Hotbar slot 2', group: 'Hotbar', def: '2' },+ { id: 'hotbar3', label: 'Hotbar slot 3', group: 'Hotbar', def: '3' },+ { id: 'hotbar4', label: 'Hotbar slot 4', group: 'Hotbar', def: '4' },+ { id: 'hotbar5', label: 'Hotbar slot 5', group: 'Hotbar', def: '5' },+ { id: 'hotbar6', label: 'Hotbar slot 6', group: 'Hotbar', def: '6' },+ { id: 'hotbarClear', label: 'Clear hotbar selection', group: 'Hotbar', def: '0' },+ { id: 'inventory', label: 'Inventory', group: 'Panels', def: 'i' },+ { id: 'map', label: 'Map', group: 'Panels', def: 'm' },+ { id: 'build', label: 'Build', group: 'Panels', def: 'b' },+ { id: 'chat', label: 'Chat', group: 'Panels', def: 'c' },+ { id: 'friends', label: 'Friends', group: 'Panels', def: 'f' },+ { id: 'skills', label: 'Skills', group: 'Panels', def: 'k' },+ { id: 'rotateCam', label: 'Rotate camera', group: 'Camera', def: 'r' },+ { id: 'closeModal', label: 'Close / cancel', group: 'System', def: 'escape', fixed: true },+ { id: 'confirm', label: 'Confirm', group: 'System', def: 'enter', fixed: true },+];++const ACTION_BY_ID = new Map(ACTIONS.map((a) => [a.id, a]));+const STORE_PREFIX = 'kg-keybinds:';++// Normalize a KeyboardEvent.key into a stable token used everywhere (map keys,+// storage, lookups). Letters/digits lowercase; space and named keys spelled out.+export function normalizeKey(key) {+ if (!key) return '';+ if (key === ' ' || key === 'Spacebar') return 'space';+ return String(key).toLowerCase();+}++// Human label for a key token, for the settings UI and hints.+export function keyLabel(token) {+ if (!token) return '—';+ const named = {+ escape: 'Esc',+ enter: 'Enter',+ space: 'Space',+ tab: 'Tab',+ arrowup: '↑',+ arrowdown: '↓',+ arrowleft: '←',+ arrowright: '→',+ backspace: '⌫',+ delete: 'Del',+ ' ': 'Space',+ };+ if (named[token]) return named[token];+ return token.length === 1 ? token.toUpperCase() : token.replace(/^\w/, (m) => m.toUpperCase());+}++export function defaultBindings() {+ const m = {};+ for (const a of ACTIONS) m[a.id] = a.def;+ return m;+}++export class Keybindings {+ constructor(accountKey = '') {+ this.accountKey = accountKey || '_';+ this.map = { ...defaultBindings(), ...this._load() };+ // Repair any unknown/missing ids (e.g. after an action list change) so the+ // stored map can never drift out of sync with the canonical actions.+ for (const a of ACTIONS) if (!this.map[a.id]) this.map[a.id] = a.def;+ this._listeners = new Set();+ }++ // Swap the persistence scope at runtime (called once the player picks a name).+ // Re-reads that account's saved map, falling back to defaults.+ setAccount(accountKey) {+ const next = accountKey || '_';+ if (next === this.accountKey) return;+ this.accountKey = next;+ this.map = { ...defaultBindings(), ...this._load() };+ for (const a of ACTIONS) if (!this.map[a.id]) this.map[a.id] = a.def;+ this._emit();+ }++ get(id) {+ return this.map[id];+ }++ // Which action a key currently triggers, or null. Fixed system keys win so+ // 'escape'/'enter' always resolve to their system action.+ actionFor(token) {+ const key = normalizeKey(token);+ for (const a of ACTIONS) if (a.fixed && this.map[a.id] === key) return a.id;+ for (const a of ACTIONS) if (!a.fixed && this.map[a.id] === key) return a.id;+ return null;+ }++ // Assign `token` to `id`. Returns { ok, reason?, conflicts } where conflicts is+ // the list of OTHER action ids that share this key (the caller decides whether+ // to warn or auto-clear; we keep both bound and surface the clash, matching how+ // most game settings present it). Rebinding a fixed action is refused.+ set(id, token) {+ const action = ACTION_BY_ID.get(id);+ if (!action) return { ok: false, reason: 'unknown', conflicts: [] };+ if (action.fixed) return { ok: false, reason: 'fixed', conflicts: [] };+ const key = normalizeKey(token);+ if (!key) return { ok: false, reason: 'empty', conflicts: [] };+ // Reserve the system keys — assigning Esc/Enter to a normal action would+ // shadow closing/confirming dialogs.+ if (key === this.map.closeModal || key === this.map.confirm) {+ return { ok: false, reason: 'reserved', conflicts: [] };+ }+ this.map[id] = key;+ this._save();+ this._emit();+ return { ok: true, conflicts: this.conflictsFor(id) };+ }++ conflictsFor(id) {+ const key = this.map[id];+ const out = [];+ for (const a of ACTIONS) if (a.id !== id && this.map[a.id] === key) out.push(a.id);+ return out;+ }++ // All keys bound to more than one action -> [{ key, ids }]. Drives the live+ // conflict warnings in the settings panel.+ allConflicts() {+ const byKey = new Map();+ for (const a of ACTIONS) {+ const k = this.map[a.id];+ if (!byKey.has(k)) byKey.set(k, []);+ byKey.get(k).push(a.id);+ }+ const out = [];+ for (const [key, ids] of byKey) if (ids.length > 1) out.push({ key, ids });+ return out;+ }++ reset() {+ this.map = defaultBindings();+ this._save();+ this._emit();+ }++ subscribe(fn) {+ this._listeners.add(fn);+ return () => this._listeners.delete(fn);+ }+ _emit() {+ for (const fn of this._listeners) {+ try {+ fn(this.map);+ } catch (e) {+ console.error('[keybindings] listener threw:', e);+ }+ }+ }++ // ----- persistence seam (Task 16 replaces these two) -------------------+ _storeKey() {+ return STORE_PREFIX + this.accountKey;+ }+ _load() {+ try {+ const raw = localStorage.getItem(this._storeKey());+ if (!raw) return {};+ const parsed = JSON.parse(raw);+ return parsed && typeof parsed === 'object' ? parsed : {};+ } catch {+ return {};+ }+ }+ _save() {+ try {+ localStorage.setItem(this._storeKey(), JSON.stringify(this.map));+ } catch {+ /* storage disabled — bindings stay session-only */+ }+ }+}diff --git a/src/walk-net.js b/src/walk-net.jsindex 27f200cca..8268d86a2 100644--- a/src/walk-net.js+++ b/src/walk-net.js@@ -86,6 +86,7 @@ export class WalkNet {this._lastSentAt = 0;this._reconnectTimer = null;this._destroyed = false;+ this._connectGen = 0;}on(event, fn) {@@ -124,13 +125,18 @@ export class WalkNet {async connect() {if (this._destroyed) return;this._closeRoom();+ // Bump a generation token so a slower in-flight connect (e.g. a manual+ // retry racing the auto-reconnect timer) can detect it's been superseded+ // after its await resolves and discard the room it joined, rather than+ // orphaning a second live socket — the same duplicate-chat leak.+ const gen = ++this._connectGen;this._setStatus('connecting');try {this.client = new Client(this.url);// `token` is the server's filterBy key (matchmaking): clients with the// same coin mint join one room instance. `coin`/`coinName`/… seed that// room's identity the first time it's created. Empty coin → mainland.- this.room = await this.client.joinOrCreate(ROOM_NAME, {+ const room = await this.client.joinOrCreate(ROOM_NAME, {name: this.name,avatar: this.avatar,agent: this.agent,@@ -140,6 +146,11 @@ export class WalkNet {coinSymbol: this.coinSymbol,coinImage: this.coinImage,});+ if (this._destroyed || gen !== this._connectGen) {+ try { room.leave(); } catch {}+ return;+ }+ this.room = room;this.mySessionId = this.room.sessionId;// Colyseus 0.16 moved schema callbacks behind getStateCallbacks(room)diff --git a/tasks/iso-mmo/README.md b/tasks/iso-mmo/README.mdnew file mode 100644index 000000000..7ea5f77e8--- /dev/null+++ b/tasks/iso-mmo/README.md@@ -0,0 +1,97 @@+# Isometric MMO — Build Tasks++This directory holds self-contained build prompts for the tile-based isometric+multiplayer game served at `/play`. Each `task-NN-*.md` is an independent,+end-to-end feature spec. Hand any one to an engineer (or agent) and it should be+buildable to completion without further context.++## The codebase you are working in++**Authoritative game server** — Colyseus rooms (standalone Node process, not Vercel):+- `multiplayer/src/rooms/GameRoom.js` — the room: validates every client intent, owns all state.+- `multiplayer/src/rooms/realms.js` — realm/map definitions + geometry helpers (`inBounds`, `isBlocked`, `portalAt`, `inRect`, `realmLayout`).+- `multiplayer/src/schemas/game.js` — `@colyseus/schema` state (`GameState`, `GamePlayer`, `Slot`, `ResourceNode`, `Mob`, `Tombstone`).+- `multiplayer/src/index.js` — server entry; registers rooms (`game_mainland`, `walk_world`).++**Game client** — vanilla JS + Three.js, built by Vite:+- `src/game/iso-game.js` — renderer, HUD, input, scene build (`_buildRealm`), message handlers.+- `src/game/game-net.js` — Colyseus client connection + message bus (`net.on(...)`, `net.send(...)`).+- `src/game/iso-game.css` — game UI styles.+- `public/play.html` / `dist/play.html` — the `/play` entry document.++**Wallet / Solana** — `src/wallet-auth.js`, `src/wallet.js`, `src/solana.js`.++**Backend HTTP** — Vercel functions in `api/` (use for persistence, token quotes,+payment verification — anything that is not a live WebSocket concern).++## Current baseline (already built — do not rebuild)++Single realm only (Mainland). Working: click-to-walk movement with server-side+walkability validation, camera zoom/rotate, 24-slot inventory + 6-slot hotbar+with drag/swap/stack-to-999, resource gathering (tree/axe, rock/pickaxe, coal),+melee combat vs. mobs, training dummies, skill XP + leveling (cap 99), fountain+healing + passive regen, 48-slot bank, gold awarded on kills.++Key constants in `GameRoom.js`: `INV_SIZE=24`, `HOTBAR_SIZE=6`, `BANK_SIZE=48`,+`MAX_STACK=999`. Skills: `combat`, `woodcutting`, `mining`, `fishing`, `cooking`.++## Engineering standards (apply to EVERY task)++These are non-negotiable and override any urge to cut corners:++1. **Real data and real integrations only.** No mocks, no fake/sample arrays, no+ stubbed responses, no `setTimeout` fake progress. Wire real RPC, real APIs,+ real on-chain calls, real persistence.+2. **Server-authoritative.** The client sends intent; the server validates+ everything (bounds, adjacency, ownership, cooldowns, rate limits, balances)+ before mutating state. Never trust a client payload.+3. **Wire it end-to-end.** Schema → server handler → network message → client+ handler → rendered UI → user-reachable control. A feature with no way to+ reach it in the UI is not done. No dead buttons, no orphan handlers.+4. **Every state is designed.** Loading, empty, error, populated, overflow. Tell+ the user what to do next; never show a blank void or an unexplained failure.+5. **No TODOs, no stubs, no commented-out code, no `throw "not implemented"`.**+ If you write it, finish it.+6. **Match existing patterns.** Follow the rate-limit, cooldown, `priv`-map,+ `clean()`, `_addItem`, `_adjacent`, and message-naming conventions already in+ `GameRoom.js`. Follow `iso-game.js` conventions for scene groups and HUD.+7. **Persistence-aware.** Anything the player earns or changes must survive a+ disconnect once Task 16 (persistence) lands. Until then, write through the+ same save interface that task defines — do not bake in in-memory-only assumptions.+8. **Verify before claiming done.** Run the server + client, exercise the feature+ in a browser, confirm no console errors and real network traffic. State+ explicitly what you verified.++## Build order (dependencies)++Foundations first — several tasks unblock the rest:++- **Task 01 (realm traversal)** unblocks 02, 03, 04, 05, 06, 08, 22, 23.+- **Task 16 (persistence)** unblocks/needed-by 10, 12, 15, 17, 19, 20, 21, 23.+- **Task 17 (wallet auth)** unblocks 18; **Task 18 (token)** unblocks 19, 20.++| # | Task | Depends on |+|----|------|-----------|+| 01 | Multi-realm support & portal traversal | — |+| 02 | Player death & tombstone death-bags | 01 |+| 03 | Mob AI: roam, aggro, chase, contact damage | 01 |+| 04 | PvP combat & safe-zone enforcement | 01, 03 |+| 05 | Fishing | 01 |+| 06 | Cooking & edible food healing | 01, 05 |+| 07 | Building: firepit, shack & /pickup | 01 |+| 08 | Mainland mine interior | 01 |+| 09 | Mob loot drops & mounts | 02, 03 |+| 10 | Quests: tutorial & daily quests | 16 |+| 11 | Skills panel UI & progression feedback | — |+| 12 | Hotbar number keys & rebindable keybindings | 16 |+| 13 | Chat slash commands | 14 |+| 14 | World chat: rate limit, length cap, mute | — |+| 15 | Friends: requests, presence, direct messages | 16, 17 |+| 16 | Account-keyed player persistence | 17 (account id) |+| 17 | Wallet sign-in & token-balance gate | — |+| 18 | On-chain token: treasury, burn, USD pricing | 17 |+| 19 | Spinner wheel | 18 |+| 20 | Marketplace: gold & gold-for-token listings | 16, 18 |+| 21 | Cosmetics shop | 16 |+| 22 | Additional realms & Arena (rollers, level-gated cave) | 01 |+| 23 | Multi-server world instances | 16 |diff --git a/tasks/iso-mmo/task-01-realm-traversal.md b/tasks/iso-mmo/task-01-realm-traversal.mdnew file mode 100644index 000000000..a7c5b2fd8--- /dev/null+++ b/tasks/iso-mmo/task-01-realm-traversal.md@@ -0,0 +1,76 @@+# Task 01 — Multi-realm support & portal traversal++## Context++The game server only ever runs one map. `multiplayer/src/rooms/GameRoom.js`+hardcodes `const MAINLAND = REALMS.mainland` and binds all geometry helpers to+it. `multiplayer/src/index.js` registers a single room `game_mainland`. Yet+`multiplayer/src/rooms/realms.js` already fully defines four realms — `mainland`,+`wilderness`, `whisperwood`, `pond` — each with `spawn`, `safe`/`pvp`/`danger`+flags, `blocked`, `bankZone`, `fountain`, `nodes`, `mobs`, `fishing`, `cooking`,+`safeCamp`, and `portals` with `{x0,y0,x1,y1,to,toTx,toTy}` destinations. There is+a `portalAt(realm, tx, ty)` helper and a `realmLayout(realm)` serializer, but+**nothing calls them** and players can never leave Mainland.++Note: `GameRoom.onJoin` hand-builds the `realm` client message and omits+`fishing`, `cooking`, `safeCamp`, and `portals`. The client (`iso-game.js`+`_buildRealm`) already reads `layout.fishing`, `layout.cooking`, and+`layout.portals` — so it renders portals but the server never sends them.++## Goal++Make the game multi-realm. Players step onto a portal tile and arrive in the+destination realm at its `toTx,toTy`, with the world (nodes, mobs, geometry,+flags) fully swapped, and `safe`/`pvp`/`danger` rules applied per realm.++## What to build++1. **Parameterize `GameRoom` by realm.** Accept a realm name via room options /+ definition (e.g. `onCreate(options)` reads `options.realm`, default+ `mainland`). Replace the `MAINLAND` constant with `this.realm = REALMS[name]`+ and rebind `isBlocked`/`inBounds`/spawn/fountain/bankZone to it. `_seedWorld`,+ `onJoin`, healing, and respawn must all use `this.realm`.+2. **Register every realm.** In `index.js`, register a room per realm+ (`game_mainland`, `game_wilderness`, `game_whisperwood`, `game_pond`) or one+ `game` definition filtered by `realm` so each realm is its own instance.+ Players in different realms must not see or affect each other.+3. **Send the full layout on join.** Replace the hand-built `realm` message with+ `realmLayout(this.realm)` so `fishing`, `cooking`, `safeCamp`, `portals`,+ `safe`, `pvp`, `danger` all reach the client.+4. **Portal detection on movement.** In `_handleStep`, after a valid step, call+ `portalAt(this.realm, p.tx, p.ty)`. If a portal is hit, transition the player:+ - Carry the player's full state (inventory, hotbar, gold, skills/XP, bank,+ hp, cosmetic) to the destination realm room. Use Colyseus seat reservation+ (`matchMaker.reserveSeatFor`) and send the client a `transfer` message with+ the destination room id + reservation + spawn tile, OR consolidate realms+ into one room that swaps the player's active realm + reseeds their view.+ Pick one approach and implement it completely — state must not be lost.+ - On arrival the player spawns at `toTx,toTy` of the destination realm.+5. **Client transition.** `iso-game.js` / `game-net.js`: handle the `transfer`+ message by reconnecting/rejoining the destination room (or rebuilding the+ realm if single-room), preserving the camera and avatar. No flfrom-scratch+ reload, no flash of the wrong map. Show a brief, designed transition (fade or+ portal flash) — real, not a fake timer.+6. **Per-realm rules wired now** (deeper behavior is owned by later tasks, but+ the flags must be respected and readable): expose `realm.safe/pvp/danger` to+ the systems that need them; ensure Mainland/Whisperwood/Pond stay safe and+ Wilderness is danger+pvp outside its `safeCamp`.++## Definition of done++- Walking onto each Mainland portal tile lands you in Wilderness / Whisperwood /+ Pond at the correct return tile, and the reverse portals bring you back.+- Inventory, hotbar, gold, skills, bank, hp, and avatar are identical before and+ after a transition (verified by inspection).+- Players in different realms are isolated (two browser sessions confirm it).+- Client renders each realm's geometry, fishing/cooking tiles, safe camp, and+ portals from the server-sent layout. No console errors.+- HUD realm label updates to the destination realm name.++## Dependencies & follow-ons++Foundation task — unblocks 02, 03, 04, 05, 06, 08, 22, 23. Additional realm data+(Wilderness North/East, Arena) is added in Task 22 once traversal exists.++---+Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.diff --git a/tasks/iso-mmo/task-02-death-tombstones.md b/tasks/iso-mmo/task-02-death-tombstones.mdnew file mode 100644index 000000000..c59f95d98--- /dev/null+++ b/tasks/iso-mmo/task-02-death-tombstones.md@@ -0,0 +1,66 @@+# Task 02 — Player death & tombstone death-bags++## Context++`multiplayer/src/schemas/game.js` already defines a `Tombstone` schema+(`id`, `owner`, `ownerName`, `tx`, `ty`, `items: [Slot]`, `expiresAt`) and+`GameState.tombstones` is a `MapSchema`. `GamePlayer` has `dead` and `respawnAt`+fields. The simulation tick in `GameRoom._tick` already respawns a dead player+(`if (p.dead) { ... p.dead = false; ... }`). **But nothing ever sets+`p.dead = true`** — there is no damage-to-players path and no tombstone is ever+created. Players are effectively immortal. Realms carry a `danger` flag+(`realms.js`): Wilderness is `danger: true`; Mainland/Whisperwood/Pond are not.++## Goal++When a player's HP reaches zero, they die: respawn at the realm's safe spawn+after a delay, and — only in `danger` realms — drop a tombstone holding part of+their inventory that they (and, after a grace window, anyone) can recover before+it expires.++## What to build++1. **Death trigger.** Add a `_killPlayer(p)` path invoked whenever player HP hits+ 0 (from mob contact damage in Task 03, PvP in Task 04, or any future source).+ Set `p.dead = true`, `p.motion = 'idle'`, `p.respawnAt = now + RESPAWN_PLAYER_MS`,+ and broadcast a `died` notice to the client.+2. **Tombstone drop (danger realms only).** On death in a `danger` realm, move a+ defined subset of the player's items into a new `Tombstone` at the death tile:+ - Decide and document the drop rule (e.g. equipped tools kept, stackable+ resources and non-tool items dropped). Keep it deterministic and fair.+ - Populate `items`, `owner`, `ownerName`, `tx/ty`, and+ `expiresAt = now + TOMBSTONE_TTL_MS`. Insert into `state.tombstones`.+ - In safe realms, no tombstone is created and no items are lost.+3. **Per-realm isolation.** Because each realm is its own room (Task 01),+ tombstones already cannot collide across realms — confirm a death in one+ realm never affects another player's view elsewhere.+4. **Recovery.** Add an `onMessage('tombLoot', ...)` handler: validate the player+ is adjacent to the tombstone, then transfer items back into their inventory+ (`_addItem`, respecting full-inventory leftover). Enforce ownership: only the+ `owner` may loot until a grace window passes (`now > expiresAt - GRACE_MS`),+ after which anyone adjacent may loot. Remove the tombstone when empty.+5. **Expiry.** In `_tick`, delete tombstones past `expiresAt`.+6. **Client.** Render tombstones in the object group (`iso-game.js`) as a+ distinct mesh/marker with the owner name. Clicking an adjacent tombstone sends+ `tombLoot` and opens a small recovery panel showing its contents. Designed+ empty state ("This bag is empty") and a clear "expires in Xs" countdown driven+ by `expiresAt` (real value, not a fake timer). Death shows a respawn overlay+ with the real countdown to `respawnAt`.++## Definition of done++- Dying in Wilderness drops a tombstone with the correct items; dying in a safe+ realm does not.+- The owner can recover items by walking back and clicking; after the grace+ window others can; expired tombstones vanish server-side and client-side.+- Respawn returns the player to the realm spawn with full HP after the delay.+- Inventory math is exact (no item duplication or loss). No console errors.++## Dependencies++Requires Task 01 (realms + per-realm rooms). Damage sources that cause death are+delivered by Task 03 (mobs) and Task 04 (PvP); build death/tombstone mechanics so+those tasks only need to call `_killPlayer`.++---+Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.diff --git a/tasks/iso-mmo/task-03-mob-ai.md b/tasks/iso-mmo/task-03-mob-ai.mdnew file mode 100644index 000000000..04f0f9569--- /dev/null+++ b/tasks/iso-mmo/task-03-mob-ai.md@@ -0,0 +1,62 @@+# Task 03 — Mob AI: roam, aggro, chase, contact damage++## Context++Mobs are static targets. `realms.js` defines mobs with `roam` and `aggro` flags+(Wilderness has goblins/ogre with `roam: true, aggro: true`; Mainland has+training dummies with both `false`). The `Mob` schema (`game.js`) has an+`aggroId` field ("session id of the player this mob is chasing"). But+`GameRoom._tick` only handles mob respawn — **mobs never move, never aggro, and+never damage players.** Combat is one-directional (player hits mob).++## Goal++Give mobs server-authoritative behavior: roamers wander, aggressive mobs detect+nearby players, chase them, and deal contact damage during a hit window —+feeding the death/tombstone system (Task 02). Dummies stay inert for practice.++## What to build++1. **Carry behavior flags into state.** When seeding (`_seedWorld`), persist each+ mob's `roam`/`aggro` (off-schema in a server-side map, or add fields) plus a+ spawn/home tile for leashing. Add tuning constants (aggro radius, leash+ radius, move interval, contact damage, attack cooldown, mob HP regen).+2. **Mob simulation in `_tick`** (or a dedicated faster mob tick):+ - **Roam:** idle mobs with `roam` occasionally step to a random adjacent+ walkable tile within a leash radius of home. Reuse the same walkability+ rules as players (`inBounds`, `isBlocked`, node/mob/player occupancy).+ - **Aggro acquisition:** an `aggro` mob with no target scans for the nearest+ living, non-dead player within aggro radius and in the same realm; set+ `aggroId`. Respect safe zones — a mob must not enter or aggro inside a+ `safeCamp` (`inRect`) or in a `safe` realm.+ - **Chase:** a mob with an `aggroId` steps one tile toward that player each+ move tick (greedy pathing around obstacles). Drop aggro and return home if+ the player dies, leaves the realm, enters the safe camp, or exceeds the+ leash radius.+ - **Contact damage:** when adjacent to its target and its attack cooldown is+ ready, deal damage to the player (`p.hp -= dmg`, clamp at 0). If HP hits 0,+ call `_killPlayer` (Task 02). Set a `hitTs`-style marker so the client can+ flash the player.+3. **Mount/loot drops** are owned by Task 09 — leave a clean hook on mob death.+4. **Client.** Mobs already render and tween position from synced `tx/ty`;+ confirm chasing reads smoothly. Show a damage flash + floating damage number+ when the local player is hit, and an aggro indicator on hostile mobs.+ Player HP bar reflects incoming damage in real time.++## Definition of done++- Goblins/ogre in Wilderness wander, notice a nearby player, chase, and deal+ damage; standing in the safe camp stops them at the fence.+- Training dummies on Mainland never move or attack.+- A player can be killed by mobs, triggering Task 02 death/tombstone in danger+ realms. Movement remains smooth; no teleporting mobs; no console errors.+- Mob CPU cost is bounded (no O(players×mobs) blowups per frame — scans run on+ the sim tick, not the patch rate).++## Dependencies++Requires Task 01 (realms). Calls `_killPlayer` from Task 02. Leaves the kill hook+for Task 09 (loot/mounts).++---+Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.diff --git a/tasks/iso-mmo/task-04-pvp-safezones.md b/tasks/iso-mmo/task-04-pvp-safezones.mdnew file mode 100644index 000000000..aaf6e5b9f--- /dev/null+++ b/tasks/iso-mmo/task-04-pvp-safezones.md@@ -0,0 +1,60 @@+# Task 04 — PvP combat & safe-zone enforcement++## Context++`_handleAttack` in `GameRoom.js` only resolves attacks against mobs+(`state.mobs.get(...)`). There is no player-vs-player combat. Realms carry the+rules already: `realms.js` marks `pvp: true` on Wilderness (with a southern+`safeCamp` rectangle that disables PvP) and `pvp: false` on Mainland,+Whisperwood, and Pond. The `inRect` helper exists for safe-camp tests.++## Goal++Allow players to attack other players, but only where the realm rules permit:+PvP enabled realms outside any safe camp. Safe realms and safe camps fully+prevent player damage.++## What to build++1. **Target resolution.** Extend the attack path to accept a player target+ (e.g. `attack` payload distinguishes `{ kind: 'mob'|'player', id }`, or add a+ parallel `attackPlayer` message). Resolve the target player from+ `state.players`.+2. **PvP gating (server-authoritative).** Permit a player hit only when ALL hold:+ - `this.realm.pvp === true`.+ - Neither attacker nor target is inside `this.realm.safeCamp`+ (`inRect(safeCamp, tx, ty)`), and the realm is not `safe`.+ - Attacker and target are adjacent (`_adjacent`), both alive, not the same+ player, and the attack cooldown is ready.+ Reject (with a client `notice`) in all other cases — including any attempt to+ hit a player on Mainland/Whisperwood/Pond.+3. **Damage + death.** Apply damage using the existing damage formula (combat+ level + sword bonus + variance). On HP 0, call `_killPlayer` (Task 02) so the+ victim drops a tombstone in danger realms. Award the killer appropriately+ (define and document: e.g. combat XP; decide whether gold/loot transfers —+ keep it consistent with the tombstone model so loot flows through the bag, not+ a direct steal).+4. **Anti-abuse.** Keep PvP under the same attack rate limit/cooldown as PvE.+ Prevent spawn-camping basics: brief post-respawn protection (a short+ invulnerability window where the player cannot deal or take player damage).+5. **Client.** Make other players targetable (click) only where PvP is legal;+ show a clear affordance (e.g. hostile cursor / outline) when over an+ attackable player and a "safe zone" indicator where PvP is disabled. Floating+ damage numbers and HP bars for the involved players. A killfeed/notice on a+ PvP kill.++## Definition of done++- Two sessions can fight in Wilderness outside the camp; neither can damage the+ other inside the camp or in any safe realm (server rejects it, not just UI).+- A PvP death drops the victim's tombstone (Task 02) and applies the documented+ reward to the killer. Respawn protection prevents instant re-kills.+- No way to bypass the gate from a crafted client payload. No console errors.++## Dependencies++Requires Task 01 (realm flags/rooms) and Task 02 (`_killPlayer`/tombstones).+Shares the damage model with Task 03.++---+Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.diff --git a/tasks/iso-mmo/task-05-fishing.md b/tasks/iso-mmo/task-05-fishing.mdnew file mode 100644index 000000000..3fa52256b--- /dev/null+++ b/tasks/iso-mmo/task-05-fishing.md@@ -0,0 +1,53 @@+# Task 05 — Fishing++## Context++The `fishing` skill exists on `GamePlayer` (`game.js`) and `realms.js` defines+`fishing` tiles (shoreline coordinates) on Whisperwood and Pond, serialized to+the client via `realmLayout`. The client `_buildRealm` already paints fishing+spots. A `rod` tool is in the starter kit and `STACKABLE` already includes+`'fish'`. **But there is no fishing handler** — no way to cast, no catch roll, no+fish item awarded, and `priv.xp` doesn't even track `fishing` consistently+(`onJoin` seeds `xp: { woodcutting, mining, fishing, combat }` — confirm fishing+and add cooking where missing). Fishing XP is never granted anywhere.++## Goal++A complete fishing loop: equip the rod, stand next to fishable water, cast, and —+after a real per-cast resolution — receive raw fish and fishing XP, scaled by+skill and spot quality.++## What to build++1. **Cast handler.** `onMessage('fish', ...)`: validate the player is alive, the+ `rod` is on the active hotbar slot, the player is adjacent to a `fishing` tile+ of the current realm, and a fishing cooldown has elapsed. Rate-limit it+ (reuse the `gather` bucket pattern or add a `fish` limit).+2. **Catch resolution.** Roll success against fishing skill + spot quality (define+ a clear curve — higher skill = higher catch rate and/or better yield). On+ success, `_addItem(p, 'fish', n)` (respect full-inventory leftover) and+ `_grantXp(sessionId, p, 'fishing', amount)`. On a miss, give a small XP trickle+ or none, and a "the fish got away" notice. Apply a per-cast cooldown so casting+ has cadence (real async resolution on the sim/cooldown clock — no fake timer).+3. **Spot quality.** Allow tuning per realm/tile (e.g. Pond's open water richer+ than Whisperwood ponds). Keep data in `realms.js` if it needs to vary.+4. **Client.** When the rod is equipped and the player clicks an adjacent fishing+ tile, send `fish` and show a cast animation/line + bobber, then resolve to a+ caught-fish toast or a miss toast. Disable casting (with a hint) when no rod is+ equipped or not adjacent to water. Update the fishing skill display on level-up.++## Definition of done++- Equipping the rod and clicking adjacent water in Whisperwood/Pond yields raw+ fish over repeated casts, with fishing XP and visible level-ups.+- Casting is rejected (with a helpful notice) without a rod, away from water, or+ when the inventory is full. Catch rate visibly improves as fishing level rises.+- No console errors; server validates every cast (no client-claimed catches).++## Dependencies++Requires Task 01 (realm layout incl. fishing tiles delivered to client). Feeds+Task 06 (cooking consumes raw fish).++---+Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.diff --git a/tasks/iso-mmo/task-06-cooking-food.md b/tasks/iso-mmo/task-06-cooking-food.mdnew file mode 100644index 000000000..aa2c50d75--- /dev/null+++ b/tasks/iso-mmo/task-06-cooking-food.md@@ -0,0 +1,54 @@+# Task 06 — Cooking & edible food healing++## Context++The `cooking` skill exists on `GamePlayer`, and `realms.js` defines a `cooking`+tile cluster on Pond labeled "the Roast Pit", serialized via `realmLayout` and+painted by the client. There is **no cooking handler, no cooked-fish item, and no+way to eat food to heal.** Note: `GameRoom.onJoin` seeds `priv.xp` without a+`cooking` key — add it. Healing today is only the fountain + passive regen.++## Goal++Cook raw `fish` into `cookedFish` at the Roast Pit for cooking XP, and let players+eat cooked fish (and other consumables) from inventory/hotbar to restore HP.++## What to build++1. **Cook handler.** `onMessage('cook', ...)`: validate alive, holding `fish`,+ and adjacent to a `cooking` tile of the current realm (the Roast Pit). Apply a+ cook cooldown + rate limit. Convert one (or a batch) `fish` → `cookedFish`:+ decrement the raw stack, `_addItem(p, 'cookedFish', n)`, grant cooking XP. Add+ a small burn-chance at low cooking levels that consumes the fish without a+ cooked result (improves with level) — keep it fair and documented. Add+ `cookedFish` to `STACKABLE`.+2. **Eat/consume handler.** `onMessage('consume', ...)`: validate the referenced+ slot holds an edible item (`cookedFish`, and any `potion` items introduced by+ shop/loot later). Restore HP (`cookedFish` a fixed/level-scaled heal; potions+ their own values), consume one from the stack, apply a short consume cooldown.+ Never overheal past `maxHp`. Works from inventory or hotbar.+3. **Item registry.** Introduce a small server-side item definition map (heal+ amount, edible flag, stackable flag) so consumables are data-driven, not+ hardcoded in branches. Use it from `consume` and from `_addItem`/`STACKABLE`.+4. **Client.** At the Roast Pit, clicking with raw fish (or a "Cook" action)+ sends `cook` and shows a cooking animation + result toast; burned results are+ communicated honestly. Right-click / "Eat" on a cooked-fish or potion slot+ sends `consume` and animates the HP gain. Disable cooking away from a pit with+ a hint. Cooking skill display updates on level-up.++## Definition of done++- At the Pond Roast Pit, raw fish convert to cooked fish with cooking XP and+ visible level-ups; cooking elsewhere is rejected with a helpful notice.+- Eating cooked fish restores HP (capped at max) from inventory and hotbar;+ potions consume correctly when present.+- Burn chance falls as cooking level rises. No item dupe/loss. No console errors.++## Dependencies++Requires Task 01 (cooking tiles in layout) and Task 05 (raw fish supply). The+consumable/item registry here is reused by Task 09 (loot), Task 20 (marketplace),+and Task 21 (shop).++---+Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.diff --git a/tasks/iso-mmo/task-07-building-firepit-shack.md b/tasks/iso-mmo/task-07-building-firepit-shack.mdnew file mode 100644index 000000000..257bdedee--- /dev/null+++ b/tasks/iso-mmo/task-07-building-firepit-shack.md@@ -0,0 +1,61 @@+# Task 07 — Building: firepit, shack & /pickup++## Context++There is no building system. Players gather `wood`, `stone`, and `coal` but have+nothing to spend them on beyond the bank. The world has a fountain for healing+but no player-placed structures. Movement is tile-stepped and the client already+has a scene object group for dynamic world objects.++## Goal++A complete placement system for two structures, plus pickup:+- **Firepit** — costs 20 stone + 20 coal + 50 wood, lasts ~30s, heals players who+ stand adjacent (like the fountain), then decays. Placeable in allowed realms.+- **Shack** — costs 500 wood + 200 stone, Whisperwood only, one per player,+ decorative landmark (no internal storage), persistent until picked up.+- **/pickup** — removes a structure you own, freeing the shack's one-per-player+ slot for re-placement.++## What to build++1. **Schema.** Add a `Structure` schema (`id`, `kind: 'firepit'|'shack'`, `owner`,+ `ownerName`, `tx`, `ty`, `expiresAt` (0 = permanent), optional `locked`) and a+ `structures` `MapSchema` on `GameState`. Structures occupy/are solid on their+ tile (factor into `_isWalkable`).+2. **Placement handler.** `onMessage('build', { kind, tx, ty })`: validate alive;+ target tile is in-bounds, walkable, adjacent to the player, and not on a+ portal/bank/fountain/resource tile; the realm allows that structure (shack →+ Whisperwood only; firepit → allowed realms); the player owns < the cap (shack+ one-per-player across realms); and the player has the exact material cost.+ Deduct materials atomically, create the structure, set `expiresAt` for firepit.+3. **Firepit healing + decay.** In `_tick`, heal players adjacent to any firepit+ (reuse the fountain heal logic), and delete firepits past `expiresAt`.+4. **Pickup + lock.** Implement `/pickup` (see Task 13 command routing, but the+ server action lives here): list/remove structures the caller owns; picking up+ a shack frees the slot. Implement `/lock` and `/unlock` to toggle a structure's+ `locked` flag so it ignores stray clicks.+5. **Client build mode.** Add a build menu (from the hotbar/`B` key) listing+ buildable structures with their costs and whether the player can afford them.+ Entering build mode shows a ghost preview that snaps to tiles and turns+ red/green for invalid/valid placement; left-click places (sends `build`),+ right-click cancels; movement clicks are suppressed until exit. Render+ firepits (with a real countdown ring from `expiresAt`) and shacks in the+ object group. Designed empty/affordability states ("Need 200 more wood").++## Definition of done++- A firepit can be built only when you have 20 stone + 20 coal + 50 wood; it+ heals adjacent players and disappears after its lifetime.+- A shack can be built only in Whisperwood, one per player; building a second is+ rejected until the first is picked up; `/pickup` frees the slot.+- `/lock`/`/unlock` protect structures from mis-clicks. Materials are deducted+ exactly (no negative balances, no free builds). No console errors.++## Dependencies++Requires Task 01 (realm rules per structure). `/pickup` `/lock` `/unlock` routing+comes from Task 13; implement the server-side actions here and expose them.++---+Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.diff --git a/tasks/iso-mmo/task-08-mine-interior.md b/tasks/iso-mmo/task-08-mine-interior.mdnew file mode 100644index 000000000..a3c385562--- /dev/null+++ b/tasks/iso-mmo/task-08-mine-interior.md@@ -0,0 +1,46 @@+# Task 08 — Mainland mine interior++## Context++The world guide describes a mine entrance on the Mainland that leads to an+interior mining area dense with rocks and coal. Today Mainland has only a handful+of surface `rock`/`coal` nodes (`realms.js`), and there is no interior space.+Realm traversal + portals now exist (Task 01), so an interior is just another+realm reachable through an entrance tile.++## Goal++Add a mining interior reachable from a Mainland mine entrance: an enclosed cave+map rich in rock and coal nodes, with a return portal to the Mainland entrance.++## What to build++1. **Define the interior realm** in `realms.js` (e.g. `mine`): an enclosed cave+ grid, `safe: true` (no PvP/death — it is a Mainland-side resource area unless+ you intentionally make it dangerous; default safe), walled `blocked` regions+ forming cave corridors, a spawn at the entrance, and a dense set of `rock` and+ `coal` nodes. No bank/fountain. A return portal to the Mainland mine entrance.+2. **Mainland entrance.** Add a portal rectangle on Mainland (the mine entrance+ tile) with `to: 'mine'` and matching return coordinates, mirroring the existing+ portal pattern. Register the `mine` realm/room in `index.js` (Task 01 pattern).+3. **Visuals.** Give the interior a cave look in the client (`iso-game.js`+ `_buildRealm` reads the layout; darker ground/walls, rock-textured blocks).+ Keep it readable and performant.+4. **Balance.** Tune node counts and respawn timers so the mine is a meaningfully+ better mining spot than the surface without trivializing progression.++## Definition of done++- Walking onto the Mainland mine entrance transports the player into the cave+ interior; the return portal brings them back to the entrance tile.+- The interior has working rock/coal nodes (pickaxe gathers them, mining XP+ granted) and renders as a distinct cave space. No console errors.+- Players in the mine are isolated from the surface (separate room/instance).++## Dependencies++Requires Task 01 (multi-realm traversal + portals). Uses the existing gathering+system unchanged.++---+Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.diff --git a/tasks/iso-mmo/task-09-loot-mounts.md b/tasks/iso-mmo/task-09-loot-mounts.mdnew file mode 100644index 000000000..65da53fdf--- /dev/null+++ b/tasks/iso-mmo/task-09-loot-mounts.md@@ -0,0 +1,54 @@+# Task 09 — Mob loot drops & mounts++## Context++When a mob dies in `_handleAttack`, the player gets gold + combat XP and the mob+respawns — but no items drop. The world guide says mobs occasionally drop+**mounts**, which players can ride for faster movement and leave with a+`/dismount` command. There is currently no loot table, no mount item, and no+mounted-movement system. Tasks 02/03/04 left a clean "mob death" hook.++## Goal++A loot system that drops items (notably mounts) from mob kills on a rolled+chance, plus a mount system: equip a mount to move faster, and dismount on+command.++## What to build++1. **Loot tables.** Add a data-driven drop table keyed by mob `kind` (e.g.+ goblin/ogre have a small mount-drop chance plus any other intended drops).+ Roll on mob death (both PvE and, if applicable, the mob-death hook from Task+ 03). Award items via `_addItem`; if the inventory is full, drop the loot into a+ ground bag (reuse the Task 02 tombstone/bag mechanics) rather than vanishing.+2. **Mount item + state.** Define mount items in the item registry (Task 06).+ Add player mount state (e.g. `mounted` flag / `mount` id on `GamePlayer`).+ Equipping/using a mount item from the hotbar mounts the player.+3. **Mounted movement.** While mounted, increase effective movement speed. Since+ movement is tile-stepped and server-validated, implement speed as a reduced+ step cooldown / higher step rate-limit headroom for mounted players — keep it+ server-authoritative (no client-claimed speed). Decide and document whether+ gathering/combat are restricted while mounted.+4. **/dismount.** Wire the `/dismount` command (routing from Task 13; action+ here): clear mount state and return to normal speed. Also auto-dismount on+ death.+5. **Client.** Render the mount under/around the avatar when mounted, animate+ faster locomotion, and show a mount indicator in the HUD. A kill that drops a+ mount shows a celebratory, honest notice ("The ogre dropped a mount!"). Mount+ from the hotbar; `/dismount` (or a HUD button) to get off.++## Definition of done++- Killing mobs occasionally yields real drops per the table; mounts can be+ obtained, equipped, and ridden for visibly faster travel; `/dismount` works and+ death auto-dismounts.+- Loot never silently disappears on a full inventory (it bags on the ground).+- Speed is enforced server-side. No console errors.++## Dependencies++Requires Task 03 (mob death hook) and Task 02 (ground-bag mechanics for overflow+loot). Uses the item registry from Task 06. `/dismount` routing from Task 13.++---+Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.diff --git a/tasks/iso-mmo/task-10-quests.md b/tasks/iso-mmo/task-10-quests.mdnew file mode 100644index 000000000..318608ea3--- /dev/null+++ b/tasks/iso-mmo/task-10-quests.md@@ -0,0 +1,63 @@+# Task 10 — Quests: tutorial & daily quests++## Context++New players spawn with a starter kit (`onJoin` hands out axe/pickaxe/rod/sword)+but there is **no guidance and no objectives system.** The world guide describes+a tutorial NPC that walks new players through tools, bank, and the marketplace,+plus daily quests with gather/combat objectives, gold/item/XP rewards, and a+daily reset. None of this exists.++## Goal++Two complementary systems:+- **Tutorial** — a first-session, step-by-step onboarding driven by a Mainland+ NPC that unlocks/teaches core actions (move, gather, hotbar, bank, marketplace)+ at the right pace and tracks completion per account.+- **Daily quests** — a rotating set of objectives (chop X wood, mine X stone,+ catch X fish, kill X mobs in realm Y) that grant rewards and reset on a daily+ schedule.++## What to build++1. **NPC entity.** Add an NPC to Mainland (data in `realms.js` or an NPC table):+ a fixed, interactable character near spawn. Clicking/approaching opens a+ dialog. Render it client-side as a distinct character with a name tag and an+ "!" / "?" quest marker reflecting available/turn-in state.+2. **Quest engine (server).** Define quests as data: `id`, `type`+ (`gather`/`combat`/`tutorial-step`), target item/mob/realm, count, and reward+ (gold, items, XP, optional badge). Track per-player progress server-side+ (`priv` and, once Task 16 lands, persisted). Increment progress from the real+ action hooks — gathering (`_handleGather`), kills (`_handleAttack`), fishing+ (Task 05) — not from client claims. Detect completion and allow turn-in for+ rewards (granted via `_addItem`/gold/`_grantXp`).+3. **Tutorial flow.** A scripted ordered list of steps; advancing requires the+ player to actually perform the action (gather once, open the bank, open the+ marketplace, etc.). Persist tutorial completion so it does not repeat. Unlocks+ should feel paced, not dumped at once.+4. **Daily quests.** Assign a daily set per account; reset on a fixed daily+ schedule (compute next-reset timestamp; expose it to the client for a real+ countdown). Rewards include gold/items/XP and sometimes a profile badge+ (badge stored on the account; surfaced wherever the profile renders).+5. **Client quest UI.** A quest panel (HUD button + maybe `Q`) showing active+ tutorial step and daily quests with live progress bars, reward previews, a+ real reset countdown, and turn-in buttons. NPC dialog UI for accepting/turning+ in. Designed empty state ("All dailies complete — back tomorrow") and+ completion toasts.++## Definition of done++- A fresh account is guided through the core loop by the NPC; the tutorial does+ not replay after completion.+- Daily quests track real progress from real actions, can be turned in for+ rewards, and reset on schedule with an accurate countdown.+- Badges awarded by quests appear on the player profile. No console errors; no+ client-side progress spoofing possible.++## Dependencies++Requires Task 16 (persistence) so tutorial completion, daily assignment, progress,+and badges survive sessions. Reads action hooks from gathering/combat/fishing.++---+Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.diff --git a/tasks/iso-mmo/task-11-skills-ui.md b/tasks/iso-mmo/task-11-skills-ui.mdnew file mode 100644index 000000000..9efda98aa--- /dev/null+++ b/tasks/iso-mmo/task-11-skills-ui.md@@ -0,0 +1,53 @@+# Task 11 — Skills panel UI & progression feedback++## Context++Progression works server-side: `_grantXp` accumulates per-skill XP in the `priv`+map and `levelForXp` converts it to a level (cap 99), broadcasting only the+integer level on `GamePlayer` (`combat`, `woodcutting`, `mining`, `fishing`,+`cooking`). The client renders none of this as a dedicated surface — there is no+skills panel, no XP bar, no level-up feedback, and the current level cap is not+shown anywhere. Some content is meant to be skill-gated (e.g. a level-gated+cave in Task 22; the spinner requires an average skill level — Task 19).++## Goal++A skills UI that shows each skill's level, progress to the next level, and the+cap, with satisfying level-up feedback — plus a reusable "average skill level"+read other systems can gate on.++## What to build++1. **Expose XP progress.** The schema broadcasts only levels (kept lean on+ purpose). Add a way for a player to see their own XP progress: send the+ requesting client its private XP map + the XP thresholds (e.g. an+ `onMessage('skills', ...)` that replies with current XP, XP for current and+ next level, and the cap). Do not broadcast XP to peers.+2. **Level-up events.** When `_grantXp` raises a level, send the client a+ `levelup` notice ({ skill, level }) so the UI can celebrate it.+3. **Average-skill helper.** Add a server helper computing the player's average+ skill level (used by Task 19's spin gate and any future gates). Expose it where+ needed; keep the computation authoritative.+4. **Client skills panel.** A HUD-accessible panel (button + a key, e.g. `K`)+ listing all five skills with: level, an XP progress bar to next level (from the+ `skills` reply), and the level cap. Show total/average level. Live-update on+ `levelup`. Designed states for level 1 (fresh) through 99 (maxed: "Mastered").+5. **Level-up feedback.** A non-intrusive celebratory toast/animation on+ `levelup` with the skill icon and new level. No fake numbers — driven by real+ server events.++## Definition of done++- The skills panel shows accurate levels, XP-to-next, and the cap for the local+ player, updating live as XP is earned.+- Leveling a skill triggers a visible level-up celebration.+- Peers cannot see each other's raw XP. The average-skill helper returns correct+ values for gating. No console errors.++## Dependencies++None hard; pairs with Task 19 (spin gate uses the average-skill helper) and Task+22 (cave level gate). Persistence (Task 16) keeps levels across sessions.++---+Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.diff --git a/tasks/iso-mmo/task-12-keybindings.md b/tasks/iso-mmo/task-12-keybindings.mdnew file mode 100644index 000000000..619d2c55b--- /dev/null+++ b/tasks/iso-mmo/task-12-keybindings.md@@ -0,0 +1,51 @@+# Task 12 — Hotbar number keys & rebindable keybindings++## Context++The client (`iso-game.js`) handles movement and camera input and has a 6-slot+hotbar with an `equip` message, but **the number keys 1–6 are not wired to+select hotbar slots**, and there is no keybindings settings UI. The world guide+specifies defaults: `I` inventory, `M` map, `B` build, `C` chat, `F` friends,+`R` rotate camera, `1–6` hotbar, `0` clear hotbar selection, `Esc` close top+modal, `Enter` confirm. `R` rotate already exists; others are partial or missing.++## Goal++Wire all default keybindings, including hotbar 1–6 and 0-to-clear, and add a+settings UI to rebind any action, persisted per account.++## What to build++1. **Central keybinding map.** Introduce a single source of truth for actions →+ keys (default to the spec above). Route all keydown handling through it instead+ of scattered literal key checks. Guard so bindings don't fire while typing in+ chat or an input field.+2. **Hotbar keys.** `1`–`6` set `activeSlot` (send `equip`); `0` clears selection+ (`activeSlot = -1`). Reflect the active slot visually in the hotbar.+3. **Panel toggles.** `I`/`M`/`B`/`C`/`F` open/close their panels (wire to the+ inventory, map, build (Task 07), chat (Task 14), friends (Task 15) surfaces as+ they exist; for not-yet-built panels, wire the toggle to the placeholder the+ owning task will fill — do not leave a dead key). `Esc` closes the top-most+ modal; `Enter` confirms the focused dialog. `R` keeps rotating the camera.+4. **Rebinding UI.** A Settings → Controls panel listing every action and its+ current key, with a "click to rebind → press a key" capture flow. Detect and+ warn on conflicts; allow reset-to-defaults. Persist the custom map per account+ (Task 16; until then, persist to the same save interface).+5. **Accessibility.** Visible focus states, keyboard navigability of the settings+ panel itself, and ARIA labels on the rebind controls.++## Definition of done++- Pressing 1–6 selects the matching hotbar slot and 0 clears it; the active slot+ is visually obvious and used by world clicks.+- All default keys perform their action and none fire while typing in chat.+- Rebinding any action works, conflicts are surfaced, reset-to-defaults works,+ and custom bindings persist across sessions. No console errors.++## Dependencies++Toggles connect to panels owned by Tasks 07/14/15; wire them as those land.+Persistence of custom bindings uses Task 16.++---+Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.diff --git a/tasks/iso-mmo/task-13-slash-commands.md b/tasks/iso-mmo/task-13-slash-commands.mdnew file mode 100644index 000000000..7ee9a6cb0--- /dev/null+++ b/tasks/iso-mmo/task-13-slash-commands.md@@ -0,0 +1,53 @@+# Task 13 — Chat slash commands++## Context++There is no command system in the game. The world guide lists player commands:+`/pickup` (pick up your firepit/shack), `/lock` and `/unlock` (protect structures+from mis-clicks), `/dismount` (leave a mount), `/who` (list nearby players in your+realm), and `/help` (list commands). Several of these have their action logic+defined in other tasks (`/pickup` `/lock` `/unlock` → Task 07; `/dismount` →+Task 09). This task builds the parser/router and the self-contained commands.++## Context dependency++Slash commands are entered through chat, so build on the world chat input from+Task 14 (or, if building first, add a minimal command input that Task 14 absorbs).++## What to build++1. **Command router (server).** A single parser that receives chat input+ beginning with `/`, splits command + args, validates the command exists and+ the caller may run it, dispatches to a handler, and returns a result message+ to that client. Unknown commands return a helpful error. Rate-limit commands.+2. **Wire the commands:**+ - `/pickup` — invoke the Task 07 structure-pickup action (list owned+ structures or pick up the targeted/nearest one; free the shack slot).+ - `/lock` / `/unlock` — toggle the Task 07 structure `locked` flag for the+ owner's adjacent structure.+ - `/dismount` — invoke the Task 09 dismount action.+ - `/who` — reply with the list of players currently in the caller's realm+ (real `state.players`, count + names), respecting any privacy/mute rules.+ - `/help` — reply with the list of available commands + one-line descriptions,+ generated from the command registry (never a hardcoded duplicate list).+3. **Client.** Typing a `/command` in chat sends it through the command path;+ command replies render as system messages distinct from player chat.+ Autocomplete/hint for command names is a plus (show matching commands as the+ user types `/`). `/help` output is readable and scannable.++## Definition of done++- Each command runs its real action and returns accurate output; `/help` lists+ exactly the registered commands; `/who` reflects real realm occupancy.+- Commands for actions the caller can't perform (no structure to pick up, not+ mounted) return a clear, honest message rather than failing silently.+- Commands are rate-limited and validated server-side. No console errors.++## Dependencies++Requires Task 14 (chat input) and the action implementations in Task 07+(`/pickup` `/lock` `/unlock`) and Task 09 (`/dismount`). `/who` and `/help` are+self-contained here.++---+Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.diff --git a/tasks/iso-mmo/task-14-world-chat.md b/tasks/iso-mmo/task-14-world-chat.mdnew file mode 100644index 000000000..9e6a3045a--- /dev/null+++ b/tasks/iso-mmo/task-14-world-chat.md@@ -0,0 +1,51 @@+# Task 14 — World chat: rate limit, length cap, mute++## Context++The game room (`GameRoom.js`) has no chat. The sibling room+`multiplayer/src/rooms/WalkRoom.js` already implements a working chat (message+handling around lines 191/346–351) with the patterns this game should reuse:+sanitization, rate limiting, and broadcast. The world guide specifies world chat+focused with `C`, messages to everyone online, per-window rate limits, rejection+of overly long messages, and the ability to mute players.++## Goal++A world chat for the game realm: send/receive messages to everyone in the realm,+rate-limited and length-capped, with client-side mute.++## What to build++1. **Server chat handler.** Add `onMessage('chat', ...)` to `GameRoom`: sanitize+ with the existing `clean()` helper, enforce a max length (reject longer+ messages with a notice), and rate-limit using the established bucket pattern+ (`_rateOk`, e.g. a `chat` limit). Broadcast accepted messages to the realm with+ sender id + name + sanitized text + server timestamp. Reuse `WalkRoom`'s+ approach so behavior is consistent across the two experiences.+2. **Scope.** Chat is per-realm (each realm is its own room), matching player+ visibility. Do not leak messages across realms/instances.+3. **Command passthrough.** Messages starting with `/` route to the command+ system (Task 13) instead of broadcasting.+4. **Client chat UI.** A chat panel + input focused with `C` (Task 12 binding):+ scrollback of recent messages with sender names, send on `Enter`, auto-scroll,+ and an unobtrusive collapsed state. Show rejected-message feedback (too long /+ rate-limited) inline. Distinguish system/command replies from player messages.+5. **Mute.** Let a player mute another (e.g. click a name → Mute). Muted senders'+ messages are hidden client-side. Persist the mute list per account (Task 16).+ Provide an unmute path and a view of who is muted.++## Definition of done++- Two sessions in the same realm see each other's messages in real time; sessions+ in different realms do not.+- Over-length and flood messages are rejected server-side with clear feedback.+- Muting hides a player's messages and persists; unmuting restores them.+- `/` messages go to commands, not chat. No console errors.++## Dependencies++Reuses `WalkRoom` chat patterns. Feeds Task 13 (command input). Mute persistence+uses Task 16.++---+Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.diff --git a/tasks/iso-mmo/task-15-friends.md b/tasks/iso-mmo/task-15-friends.mdnew file mode 100644index 000000000..7863d4dc3--- /dev/null+++ b/tasks/iso-mmo/task-15-friends.md@@ -0,0 +1,56 @@+# Task 15 — Friends: requests, presence, direct messages++## Context++There is no social graph. Players cannot add each other, see who is online, or+message privately. The world guide describes a friends system: add by search or+invite, mutual accept required, see who is online and which realm they are in,+and send direct messages. (Parties and teleport-to-friend are explicitly NOT in+scope — do not build those.)++## Goal++An account-level friends system: send/accept friend requests, see friends'+online status and current realm, and exchange direct messages.++## What to build++1. **Account identity.** Friends are keyed to accounts (wallet address from Task+ 17), not ephemeral session ids — a friendship must survive reconnects and+ realm changes. Use the persistence layer (Task 16).+2. **Friend graph API.** Backend endpoints (Vercel functions in `api/`, or a+ dedicated store) for: search users by display name, send a friend request,+ accept/decline, remove a friend, and list friends. Requests are pending until+ accepted; both directions stored consistently. Validate the requester owns the+ account (auth from Task 17). Guard against spam/self-add/duplicate requests.+3. **Presence + location.** Track which accounts are online and their current+ realm. Since players connect to per-realm Colyseus rooms, publish presence+ from the server (a shared presence store — Redis presence is already wired in+ `index.js` when `REDIS_URI` is set; use it, or the persistence store) so a+ friend's online/offline + realm shows accurately across instances.+4. **Direct messages.** Allow sending a DM to a friend whether or not they are in+ the same realm. Deliver in real time if online; queue + deliver on next login+ if offline (persisted). Respect the mute list (Task 14). Rate-limit + length-+ cap like world chat.+5. **Client friends UI.** A friends panel (HUD + `F` binding from Task 12):+ incoming/outgoing requests with accept/decline, the friends list with live+ online/offline + realm badges, a search-to-add flow, and a DM thread view with+ unread indicators. Designed empty state ("No friends yet — search to add+ someone") and offline/error states.++## Definition of done++- A request can be sent, accepted, and the friendship appears for both accounts+ and persists across sessions.+- Friends' online status and current realm display accurately, including across+ separate realm instances.+- DMs deliver live when online and arrive on next login when offline; muted users+ are suppressed; spam is rate-limited. No console errors.++## Dependencies++Requires Task 16 (persistence) and Task 17 (account identity/auth). Uses presence+infra referenced in `index.js`. Honors Task 14 mute list.++---+Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.diff --git a/tasks/iso-mmo/task-16-persistence.md b/tasks/iso-mmo/task-16-persistence.mdnew file mode 100644index 000000000..c9164c406--- /dev/null+++ b/tasks/iso-mmo/task-16-persistence.md@@ -0,0 +1,64 @@+# Task 16 — Account-keyed player persistence++## Context++All game state is in-memory and lost on disconnect. `GameRoom.onJoin` builds a+fresh `GamePlayer` every time (empty inventory + starter kit), and the per-player+`priv` map (XP, bank, cooldowns) is created on join and deleted on leave+(`onLeave`). Nothing is saved. The world guide promises that display name,+inventory, hotbar, bank, gold, skills, tutorial progress, daily quests, placed+structures, friends, cosmetics, and profile badge all save automatically. This+is the foundation the economy and social systems depend on.++## Goal++Persist each player's full progression keyed to their account so a returning+player resumes exactly where they left off, across realms and reconnects.++## What to build++1. **Account key.** Use the authenticated account id (wallet address from Task+ 17) as the persistence key. Before auth lands, key on a stable id from the+ join handshake, but design the interface around the account id so Task 17 is a+ drop-in.+2. **Persistence store.** Choose and wire a real durable store reachable from the+ standalone multiplayer process (e.g. the same backend datastore the rest of+ the platform uses, exposed via `api/` endpoints the game server calls, or a+ direct DB/KV client). No local-only JSON files that die with the instance, no+ in-memory fakes. Must work across multiple server instances (Task 23).+3. **Persisted profile shape.** Define a single serializable profile:+ `name`, `inv`, `hotbar`, `activeSlot`, `bank`, `gold`, skill XP (all five,+ including `cooking`), `hp/maxHp`, `cosmetic`/equipped cosmetics + owned+ cosmetics (Task 21), placed structures (Task 07), tutorial completion + daily+ quest state + badges (Task 10), friends + mute list (Tasks 14/15), keybindings+ (Task 12), and current realm + tile (so they resume in place, or at a safe+ spawn if that realm is unsafe to resume into).+4. **Load on join / save on change.** On `onJoin`, load the profile (or create a+ new one with the starter kit on first ever login) and hydrate `GamePlayer` ++ `priv`. Save on meaningful mutations — debounced/throttled to avoid write+ storms (mirror the debounced-save pattern in `block-store.js` /+ `blockStore.flushAll()` used by `WalkRoom`), and flush on `onLeave`,+ `onDispose`, and server shutdown (`index.js` already calls+ `blockStore.flushAll()` on SIGTERM — hook the player store into the same path).+5. **Cross-realm continuity.** When a player transitions realms (Task 01), their+ profile follows; persistence is account-scoped, not room-scoped.+6. **Integrity.** Saves are atomic per account (no partial writes corrupting a+ profile). Concurrent logins of the same account are handled (reject the second,+ or hand off) so two sessions can't fork-and-clobber a profile.++## Definition of done++- Gather/earn/bank/level/build, disconnect, reconnect — everything is exactly as+ left, including across a server restart.+- A brand-new account starts with the correct starter kit; an existing account+ never gets reset.+- Saves are debounced under load and flushed on leave/shutdown; no write storms,+ no lost last-second changes. No console errors.++## Dependencies++Pairs with Task 17 (account id). Required by Tasks 10, 12, 14, 15, 19, 20, 21,+23. Reuse the `block-store.js` debounced-save + flush conventions.++---+Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.diff --git a/tasks/iso-mmo/task-17-wallet-auth.md b/tasks/iso-mmo/task-17-wallet-auth.mdnew file mode 100644index 000000000..29ebe8f3b--- /dev/null+++ b/tasks/iso-mmo/task-17-wallet-auth.md@@ -0,0 +1,58 @@+# Task 17 — Wallet sign-in & token-balance gate++## Context++The `/play` entry (`public/play.html`) lets anyone in — there is no sign-in and+no account identity beyond an ephemeral Colyseus session id. The platform already+has wallet plumbing (`src/wallet-auth.js`, `src/wallet.js`, `src/solana.js`) and+the multiplayer server has a holder-gate secret pattern (`HOLDER_PASS_SECRET` in+`index.js`, `multiplayer/src/holder-pass.js`). The world guide specifies: sign in+with a Solana wallet (the wallet address IS the account; no email/password), and+hold at least 1 unit of the game token in the connected wallet to play.++## Goal++Gate `/play` behind a wallet sign-in that produces a verified account identity,+and require a minimum token balance to enter, with the wallet address used as the+persistence/account key everywhere.++## What to build++1. **Sign-in flow (client).** On `/play`, require connecting a Solana wallet and+ signing a login message (reuse `src/wallet-auth.js`/`wallet.js`). Sign a+ server-issued nonce so the signature can't be replayed. Surface connect /+ signing / signed states clearly; never ask for a seed phrase.+2. **Signature verification (server/api).** Verify the signed nonce server-side+ to authenticate the wallet address. Issue a short-lived token/session the game+ server trusts (extend the existing holder-pass signing approach so the+ standalone Colyseus process can validate it — it already refuses to boot in+ prod without `HOLDER_PASS_SECRET`). The Colyseus `onAuth`/join must validate+ this and bind the verified wallet address to the session.+3. **Token-balance gate.** Read the connected wallet's balance of the game token+ from a real Solana RPC (use the platform's existing RPC config). Require+ ≥ 1 token to play. Enforce on the server at join (not just client UI) so the+ gate can't be bypassed. Re-check on a sensible cadence, not just once, if you+ want to drop players who offload below the threshold — document the policy.+4. **Account binding.** Pass the verified wallet address into the game as the+ account id, which Task 16 uses as the persistence key and Task 15 uses for the+ social graph. The displayed name maps to this account.+5. **States.** Designed screens for: wallet not installed, not connected,+ signature rejected, balance too low (with a clear path to acquire the token /+ link to funding), and verifying. Honest errors, no dead ends.++## Definition of done++- Reaching `/play` requires connecting + signing; an unsigned or forged session+ cannot join the game room (server-enforced).+- A wallet holding < 1 token is refused with a clear, actionable message; ≥ 1+ token gets in.+- The verified wallet address is the account id used for persistence and friends.+ Balance is read from real RPC, not assumed. No console errors.++## Dependencies++Foundation for Task 16 (account key), Task 18 (token), and Task 15 (account+identity). Reuses existing wallet/Solana modules + holder-pass secret.++---+Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.diff --git a/tasks/iso-mmo/task-18-token-economy.md b/tasks/iso-mmo/task-18-token-economy.mdnew file mode 100644index 000000000..130b589cf--- /dev/null+++ b/tasks/iso-mmo/task-18-token-economy.md@@ -0,0 +1,58 @@+# Task 18 — On-chain token: treasury, burn & USD pricing++## Context++The game references an on-chain token used for premium actions (paid wheel spins,+token-priced marketplace sales) but there is **no token integration in the game+code** — no mint config, no treasury wallet, no burn, no USD-based price quoting,+no payment verification. The platform has Solana tooling (`src/solana.js`,+`api/` functions, payment helpers under `api/payments/`) to build on. This task+establishes the shared on-chain primitives that Tasks 19 and 20 consume.++## Goal++A reusable, real on-chain token layer: read the live token price, quote a USD+amount as a token amount, build/verify payment transactions, and route proceeds+to burn + treasury per the configured split.++## What to build++1. **Config.** Centralize the token mint address, decimals, treasury wallet+ address, and split policy in config/env (no hardcoded literals scattered+ around). Fail loudly if required values are missing in production, mirroring+ the `HOLDER_PASS_SECRET` boot guard.+2. **Live price + USD quoting.** Fetch the token's live USD price from a real+ source (the price feed/oracle the platform already uses — e.g. the Pump.fun /+ market data path). Provide `quoteTokenForUsd(usd)` returning the token amount+ at current price, with a short server-side quote validity window so a quoted+ price can't be exploited after the market moves.+3. **Payment build + verify.** Server issues a quote (amount, recipient split,+ nonce, expiry). Client wallet signs/sends one transaction. Server verifies the+ on-chain transaction: correct amount, correct destinations (burn address ++ treasury per split), confirmed on-chain, nonce unused, within expiry. Only a+ verified payment unlocks the paid action. Never trust a client "paid" claim.+4. **Burn + treasury split.** Implement the split primitive (e.g. 50/50 for paid+ spins: half to the burn address, half to treasury; and the 95/5 seller/treasury+ split for marketplace token sales). Make the split a parameter so Tasks 19/20+ reuse the same verified-payment path with different ratios.+5. **Auditability.** Record each settled payment (payer, amount, split, tx+ signature, purpose) in the persistence store for reconciliation. Expose a+ minimal internal read path; do not log secrets.++## Definition of done++- A USD amount quotes to a correct token amount at the live price, with an+ enforced quote expiry.+- A real signed transaction is verified end-to-end (amount + burn/treasury+ destinations + confirmation) before the paid action is granted; replays and+ underpayments are rejected.+- Burn and treasury receive the configured shares on a real transaction. Settled+ payments are recorded. No secrets logged. No console errors.++## Dependencies++Requires Task 17 (authenticated wallet). Consumed by Task 19 (paid spins) and+Task 20 (token-priced listings). Uses existing Solana/payment infra + price feed.++---+Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.diff --git a/tasks/iso-mmo/task-19-spinner-wheel.md b/tasks/iso-mmo/task-19-spinner-wheel.mdnew file mode 100644index 000000000..75b90d9fa--- /dev/null+++ b/tasks/iso-mmo/task-19-spinner-wheel.md@@ -0,0 +1,61 @@+# Task 19 — Spinner wheel++## Context++There is no spinner/prize-wheel feature anywhere in the game. The world guide+describes a wheel on the Mainland (near a casino landmark): a 20-segment prize+table, one free spin every 12 hours, and on-demand paid spins costing $3 USD+worth of the game token (50% burned, 50% to treasury). Spinning requires an+average skill level of 5. About 1 in 20 spins awards gold; the rest award wood,+stone, or coal in varying amounts. The paid spin does not consume the free-spin+timer.++## Goal++A complete spinner: a Mainland wheel object that opens a spin UI, with a gated+free spin on a 12h cooldown and paid spins settled on-chain, both drawing from+one server-authoritative prize table.++## What to build++1. **Wheel object + gate.** Place a wheel near the Mainland casino landmark+ (`realms.js`/object table); clicking it opens the spinner UI. Server-side,+ require the player's average skill level ≥ 5 (use the Task 11 average-skill+ helper) to spin; otherwise reject with a clear notice.+2. **Prize table (authoritative).** Define the 20-segment table server-side with+ real probabilities (~1/20 gold; remainder wood/stone/coal in varying amounts).+ The SERVER rolls the outcome — the client animation must land on the+ server-decided segment, never decide the prize itself. Award via+ `_addItem`/gold (respect full-inventory leftover; bag overflow if needed).+3. **Free spin.** One free spin per 12h per account. Track `nextFreeSpinAt` in the+ persisted profile (Task 16); expose it so the client shows a real countdown.+ Reject early free spins server-side.+4. **Paid spin.** Cost = $3 USD worth of token via Task 18 `quoteTokenForUsd`.+ Flow: server issues a quote → client wallet signs one transaction → server+ verifies it (Task 18) with a 50/50 burn/treasury split → only then roll ++ award the prize. The paid spin does NOT alter the free-spin timer. Reject the+ spin if payment verification fails.+5. **Client spinner UI.** A wheel with the 20 segments, a spin animation that+ resolves to the server's chosen segment, the free-spin countdown, and a+ "Paid spin ($3 in token)" button that runs the payment flow with clear pending/+ confirming/success/failure states. Prize result shown honestly (exact item ++ amount). Designed states for: not eligible (avg level < 5, with how-to),+ free-spin-not-ready, wallet/payment errors.++## Definition of done++- Players below average skill level 5 cannot spin (server-enforced).+- The free spin works once per 12h with an accurate countdown and cannot be+ spun early.+- Paid spins require a real verified on-chain payment ($3 in token, 50% burn /+ 50% treasury) before awarding; the animation always matches the server outcome;+ the free timer is untouched. Prizes match the table distribution over many+ spins. No console errors.++## Dependencies++Requires Task 11 (average-skill helper), Task 16 (free-spin timer persistence),+and Task 18 (token quote + verified payment + split).++---+Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.diff --git a/tasks/iso-mmo/task-20-marketplace.md b/tasks/iso-mmo/task-20-marketplace.mdnew file mode 100644index 000000000..0b4608572--- /dev/null+++ b/tasks/iso-mmo/task-20-marketplace.md@@ -0,0 +1,61 @@+# Task 20 — Marketplace: gold & gold-for-token listings++## Context++Players earn gold (mob kills) and gather stacks of resources, but there is no way+to trade with other players. The `api/marketplace*` endpoints in this repo are+the platform's AGENT marketplace — unrelated to the in-game item economy; do not+repurpose them. The world guide describes an in-game marketplace opened from a+HUD button (cart icon), with Buy / Sell / My Listings tabs, two listing types:+- **Gold listings** — trade items for gold; buyer pays gold, seller receives the+ full amount (no fee).+- **Gold-for-token listings** — a seller lists in-game gold priced in USD; buyers+ pay on-chain with the game token. Payment splits 95% to seller / 5% to treasury.++## Goal++A full player-to-player marketplace with both listing types, server-authoritative+escrow of listed goods, and on-chain settlement for token listings.++## What to build++1. **Listing store.** Persist listings (Task 16 store / `api/`): `id`, `seller`+ account, type (`gold` | `goldForToken`), the offered item(s) or gold amount,+ price (gold amount, or USD for token listings), status, timestamps. Listings+ are account-scoped and survive sessions/instances.+2. **Escrow on list.** When a player lists, remove the offered item/gold from+ their inventory immediately (escrow) so they can't list-and-spend the same+ goods. Returning unsold goods on cancel restores them. No duplication.+3. **Gold listings (buy).** A buyer with enough gold buys: atomically debit buyer+ gold, credit seller the full amount, deliver escrowed item(s) to the buyer+ (bag overflow if inventory full). No treasury cut.+4. **Gold-for-token listings (buy).** Buyer pays on-chain via Task 18: server+ quotes the token amount from the listing's USD price, buyer's wallet sends one+ transaction, server verifies it with a 95/5 seller/treasury split, then+ delivers the escrowed in-game gold to the buyer and records the sale. Seller+ receives 95% of the token to their wallet; 5% to treasury. Reject on failed+ verification; never release goods before settlement.+5. **Marketplace UI.** A HUD cart button (works anywhere, no need to stand at a+ building) opening tabs:+ - **Buy** — browse active listings (filter/sort by item, price), buy flow with+ gold or wallet payment per listing type.+ - **Sell** — pick inventory items / gold amount, set price + type, confirm.+ - **My Listings** — view/cancel own listings (cancel returns escrow).+ Designed loading/empty ("No listings yet — be the first to sell")/error states,+ and clear pending/confirming states for on-chain buys.++## Definition of done++- Listing escrows the goods; cancel returns them; nothing can be double-spent.+- Gold purchases transfer item↔gold atomically with no fee and no dupe/loss.+- Token purchases require a real verified on-chain payment with the 95/5 split+ before the gold is released; the seller is paid 95% and treasury 5%.+- Two sessions can complete a real trade each way. No console errors.++## Dependencies++Requires Task 16 (persistence/escrow store) and Task 18 (token quote + verified+payment + split). Distinct from the platform agent marketplace.++---+Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.diff --git a/tasks/iso-mmo/task-21-cosmetics-shop.md b/tasks/iso-mmo/task-21-cosmetics-shop.mdnew file mode 100644index 000000000..ceb91ab2a--- /dev/null+++ b/tasks/iso-mmo/task-21-cosmetics-shop.md@@ -0,0 +1,53 @@+# Task 21 — Cosmetics shop++## Context++`GamePlayer` has a `cosmetic` field and players can set an avatar URL+(`_handleAvatar`, validated by `cleanAvatarUrl`), but there is no shop and no+catalog of purchasable looks. The world guide describes a cosmetic shop selling+visual-only outfits/styles (no combat effect), with rotating daily and weekly+offers, bought with gold, and equipped from the dashboard cosmetics page.++## Goal++A cosmetics shop where players spend gold on visual-only cosmetics from a rotating+catalog, own them permanently, and equip/unequip them — with no gameplay effect.++## What to build++1. **Cosmetic catalog.** Define cosmetics as data: `id`, name, visual asset/style,+ gold price, rarity, and rotation window (daily/weekly). Keep it data-driven and+ extendable. Cosmetics are strictly visual — never touch combat/stats.+2. **Rotation.** Compute the current daily and weekly offer sets from a fixed+ schedule (deterministic from the date, server-authoritative), exposing the next+ rotation time for a real countdown. Some cosmetics are always available; others+ only during their rotation.+3. **Purchase (server).** A buy handler: validate the cosmetic is currently+ offered and the player has enough gold; debit gold; add the cosmetic to the+ account's owned-cosmetics set (persisted, Task 16). Reject duplicates (already+ owned) and insufficient gold with clear notices.+4. **Equip/unequip.** Let the player equip an owned cosmetic (sets `cosmetic` /+ equipped-cosmetic state, broadcast so peers see it) or revert to default.+ Persist the equipped selection. Equipping affects only appearance.+5. **Client UI.** A cosmetics shop surface (HUD/dashboard) showing the rotating+ catalog with prices, owned vs. buyable state, affordability, a real rotation+ countdown, and buy buttons; plus a cosmetics page to equip/unequip owned items+ with a live preview on the avatar. Designed empty ("You don't own any cosmetics+ yet"), affordability, and confirmation states.++## Definition of done++- The shop shows a correct rotating catalog with an accurate next-rotation+ countdown; offers change on schedule.+- Buying debits gold, grants permanent ownership, prevents duplicate purchase,+ and rejects when gold is short.+- Equipping an owned cosmetic changes the avatar's appearance for the player and+ peers, persists across sessions, and never alters gameplay. No console errors.++## Dependencies++Requires Task 16 (owned cosmetics + equipped selection persistence). Uses the+existing avatar/cosmetic rendering path.++---+Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.diff --git a/tasks/iso-mmo/task-22-additional-realms-arena.md b/tasks/iso-mmo/task-22-additional-realms-arena.mdnew file mode 100644index 000000000..cc379fef2--- /dev/null+++ b/tasks/iso-mmo/task-22-additional-realms-arena.md@@ -0,0 +1,62 @@+# Task 22 — Additional realms & Arena (rollers, level-gated cave)++## Context++`realms.js` defines four realms (mainland, wilderness, whisperwood, pond) and+Task 01 made traversal real. The world guide describes more areas not yet built:+- **Wilderness North** — a smaller northern area reached from the top of the main+ Wilderness; PvP across the whole map (no safe camp); lower mob density; a+ level-gated cave at the far north requiring high enough combat skill to enter.+- **Wilderness East** — a full-size wild area east of the main Wilderness, also+ reachable from the north edge of the Pond; PvP + mob danger like the Wilderness.+- **Arena** — a dedicated PvP scene reached from a Mainland arena plaza (with a+ small practice boxing ring on the Mainland itself); has moving floor "rollers"+ that push players, plus spectator seating.++## Goal++Add these realms with their distinguishing mechanics, fully connected to the+existing portal network and rule systems.++## What to build++1. **Wilderness North.** Define the realm (`pvp: true, danger: true`, no+ `safeCamp`, lower mob density). Add the portal pair connecting the top of the+ main Wilderness to its south return. At the far north, a **level-gated cave+ portal**: entry requires the player's combat level ≥ a threshold (use the Task+ 11 helper); server rejects under-level entry with a clear notice. Build the+ cave as its own realm/instance beyond the gate.+2. **Wilderness East.** Define the realm (`pvp: true, danger: true`), with portal+ pairs to the east edge of the main Wilderness AND the north edge of the Pond+ (add the matching portals on those existing realms). Populate nodes/mobs to+ match Wilderness danger.+3. **Arena + boxing ring.** Add an arena plaza area on the Mainland (a small+ walkable boxing ring for practice — visual + tile region, no death risk) and a+ portal into the full **Arena** realm. The Arena is a PvP scene (`pvp: true`)+ with:+ - **Rollers** — tiles that, on the sim tick, push a standing player one tile in+ the roller's direction (server-authoritative, respecting walkability). Learn-+ the-flow movement, not teleporting.+ - Spectator/seating tiles (non-combat zones) and a south return strip to the+ Mainland plaza.+4. **Registration + client visuals.** Register all new realms/rooms (Task 01+ pattern in `index.js`). Give each a fitting look in `_buildRealm` (cave,+ wild-north, wild-east, arena with visible rollers + seating). Ensure portals+ render and the HUD realm label updates.++## Definition of done++- Wilderness North and East are reachable through real portals, enforce PvP++ danger, and connect where the guide says (incl. Pond↔East).+- The northern cave rejects under-combat-level players and admits qualified ones.+- The Mainland boxing ring is walkable/safe; the Arena is reachable, PvP-enabled,+ and rollers push players server-side along their direction; the return strip+ works. No console errors.++## Dependencies++Requires Task 01 (traversal), Task 04 (PvP rules for the wild realms + arena),+Task 02/03 (death + mobs in the wild realms), and Task 11 (combat-level gate).++---+Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.diff --git a/tasks/iso-mmo/task-23-multi-server.md b/tasks/iso-mmo/task-23-multi-server.mdnew file mode 100644index 000000000..7ec490de6--- /dev/null+++ b/tasks/iso-mmo/task-23-multi-server.md@@ -0,0 +1,56 @@+# Task 23 — Multi-server world instances++## Context++The server runs as a single set of realm instances. The world guide describes two+selectable world instances ("Server 1" and "Server 2") on the same host: a player+picks one at login, their items and gold are shared between them (account-scoped),+but players on one server cannot see players on the other. `multiplayer/src/index.js`+already supports horizontal scaling via Redis driver + presence when `REDIS_URI`+is set, and Colyseus room filtering (`filterBy`) is already used for `walk_world`.++## Goal++Let players choose between two (or N) independent world instances at login.+Instances are fully isolated for presence/visibility but share one account-scoped+profile, so progression is identical regardless of which server you join.++## What to build++1. **Server dimension on rooms.** Add a `server` (instance) key to game room+ matchmaking — e.g. `filterBy(['realm', 'server'])` so each (realm, server)+ pair is its own room and players only ever match within their chosen server.+ Mirror the existing `walk_world` filtering pattern.+2. **Login selection.** On `/play` (after wallet sign-in, Task 17), present a+ server picker showing the available instances with live population counts+ (real, from presence/matchmaking — not faked). The choice is passed as a join+ option and pins all of that session's realm rooms to the chosen server.+3. **Shared account profile.** Because persistence (Task 16) is account-scoped,+ the same profile loads on either server — items, gold, skills, bank, etc. are+ identical. Verify a player can earn on Server 1, switch to Server 2, and see+ the same inventory. Guard against the same account being live on both servers+ simultaneously in a way that could clobber the profile (single active session+ per account, per Task 16 integrity rule).+4. **Isolation.** Players on different servers never appear in each other's+ realms, chat (Task 14), or `/who` (Task 13). Presence/friends (Task 15) should+ still show a friend's online status and which server+realm they're on.+5. **Population display + balancing.** Show real per-server population at the+ picker; optionally recommend the less-full server. No fake numbers.++## Definition of done++- The login picker lists the servers with real population counts; choosing one+ pins the session to it.+- Two sessions on different servers cannot see or interact with each other in any+ realm/chat/who, but the SAME account on either server has identical progression.+- Friends presence reflects which server+realm a friend is on. No profile+ clobbering across servers. No console errors.++## Dependencies++Requires Task 16 (account-scoped persistence + single-active-session rule) and+Task 17 (account identity). Uses the Redis driver/presence + `filterBy` infra+already present in `index.js`. Interacts with Tasks 13/14/15 for isolation.++---+Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.diff --git a/tests/cooking.test.js b/tests/cooking.test.jsnew file mode 100644index 000000000..db79308b4--- /dev/null+++ b/tests/cooking.test.js@@ -0,0 +1,68 @@+// Task 06 — cooking & edible food. These cover the data-driven core the cooking+// feature rests on: the item registry's edibility/heal/stack facts (which the+// server's consume handler reads) and the burn-chance curve (which the cook+// handler rolls against). Both live in the dependency-free items module so they+// can be asserted without standing up a Colyseus room.+import { describe, it, expect } from 'vitest';+import {+ ITEMS, STACKABLE_ITEMS, isEdible, isStackable, healValue, cookBurnChance,+} from '../multiplayer/src/items.js';++describe('item registry — consumables', () => {+ it('cooked fish is a stackable, edible heal of 11', () => {+ expect(ITEMS.cookedFish).toMatchObject({ stackable: true, edible: true, heal: 11 });+ expect(isEdible('cookedFish')).toBe(true);+ expect(isStackable('cookedFish')).toBe(true);+ expect(healValue('cookedFish')).toBe(11);+ });++ it('health potion is edible with its own heal value', () => {+ expect(isEdible('healthPotion')).toBe(true);+ expect(healValue('healthPotion')).toBe(28);+ });++ it('raw fish and tools are not edible and heal nothing', () => {+ expect(isEdible('fish')).toBe(false);+ expect(isEdible('axe')).toBe(false);+ expect(healValue('fish')).toBe(0);+ expect(healValue('axe')).toBe(0);+ expect(healValue('nonexistent')).toBe(0);+ });++ it('STACKABLE_ITEMS includes cooked fish + raw fish but not tools', () => {+ expect(STACKABLE_ITEMS.has('cookedFish')).toBe(true);+ expect(STACKABLE_ITEMS.has('fish')).toBe(true);+ expect(STACKABLE_ITEMS.has('axe')).toBe(false);+ expect(STACKABLE_ITEMS.has('sword')).toBe(false);+ });+});++describe('cookBurnChance — fair, falling burn curve', () => {+ it('starts at 40% for a level-1 cook', () => {+ expect(cookBurnChance(1)).toBeCloseTo(0.4, 10);+ });++ it('never burns once trained, and stays clamped at high levels', () => {+ expect(cookBurnChance(40)).toBe(0);+ expect(cookBurnChance(99)).toBe(0);+ // Below-floor inputs are treated as level 1 (max burn), never negative.+ expect(cookBurnChance(0)).toBeLessThanOrEqual(0.4);+ expect(cookBurnChance(-5)).toBeLessThanOrEqual(0.4);+ });++ it('is monotonically non-increasing and bounded in [0, 0.4]', () => {+ let prev = Infinity;+ for (let lvl = 1; lvl <= 99; lvl++) {+ const c = cookBurnChance(lvl);+ expect(c).toBeGreaterThanOrEqual(0);+ expect(c).toBeLessThanOrEqual(0.4);+ expect(c).toBeLessThanOrEqual(prev + 1e-12);+ prev = c;+ }+ });++ it('reaches zero burn somewhere in the high 30s', () => {+ expect(cookBurnChance(30)).toBeGreaterThan(0);+ expect(cookBurnChance(38)).toBe(0);+ });+});