Add playable hub travel with durable character transfers
This commit is contained in:
@@ -201,7 +201,7 @@ function combatForm(kind:string){
|
||||
const fields=form('Create mob','create-mob',()=>({mob:{...values.read(),model:model.value,behavior:behavior.value,attackId:attack.value,lootId:loot.value,...Object.fromEntries(inputs.map(v=>[v.key,Number(v.input.value)]))}}));
|
||||
fields.append(values.node,field('Model preset',model),field('Behavior',behavior),field('Attack profile',attack),field('Loot table',loot),...inputs.map(v=>field(v.label,v.input)),node('p','Health/power = base × level × (1 + world age in days × scaling). Defence is flat. Aggressive creatures pursue within the leash; guards defend their detection radius; passive creatures retaliate only when attacked. Models remain placeholders until milestone 4.5.','muted'));
|
||||
}else if(kind==='loot'){
|
||||
const items=[...catalog.items,...(catalog.gathering?.consumables??[]),...(catalog.gathering?.resources??[]).filter(r=>r.output==='self'),...['wood','ore','herb','bandage','axe','flint_and_steel','fishing_pole'].map(id=>({id,name:statLabel(id)}))];
|
||||
const items=[...catalog.items,...(catalog.gathering?.consumables??[]),...(catalog.gathering?.resources??[]).filter(r=>r.output==='self'),...['wood','ore','herb','bandage','escape_stone','axe','flint_and_steel','fishing_pole'].map(id=>({id,name:statLabel(id)}))];
|
||||
const entries=repeat('Loot entries','Add loot entry',()=>{const group=node('div','','catalog-fields'),item=contentChoice(items),amount=number(1,1,100,'1'),chance=number(100,0,100),pool=text('',40),weight=number(1,1,10000,'1');pool.required=false;group.append(field('Item',item),field('Quantity',amount),field('Drop chance (%)',chance),field('Weighted group (blank = independent)',pool),field('Group weight',weight));return{node:group,read:()=>({item:item.value,amount:Number(amount.value),chance:Number(chance.value),group:pool.value.trim(),weight:Number(weight.value)})}},[],32);
|
||||
const fields=form('Create loot table','create-loot',()=>({loot:{...values.read(),entries:entries.read()}}));fields.append(values.node,entries.node,node('p','Blank groups roll independently; 100% is guaranteed. Each named group selects one entry by weight, then rolls that entry’s chance. Finisher luck affects non-guaranteed chances. New mobs leave a lootable corpse; the corpse is shared and may be looted by nearby players.','muted'));
|
||||
}else{
|
||||
|
||||
@@ -25,7 +25,7 @@ function openCommand(op: string, worldId = '', target = '', value = '') {
|
||||
const create = op === 'create-world', rename = op === 'rename';
|
||||
$('command-title').textContent = labels[op];
|
||||
$('command-context').textContent = create ? 'Deployment: GitOps / ArgoCD' : `${worldId}${target ? ` / ${target}` : ''}`;
|
||||
$('world-input-label').hidden = !create;
|
||||
$('world-input-label').hidden = !create; $('world-kind-label').hidden=!create;
|
||||
$<HTMLInputElement>('world-input').required = create;
|
||||
$('value-input-label').hidden = !create && !rename;
|
||||
$('value-caption').textContent = create ? 'Seed' : 'Character name';
|
||||
@@ -133,7 +133,7 @@ for (const id of ['close-command','cancel-command']) $(id).onclick = () => comma
|
||||
$('close-character').onclick = () => characterMenu.close();
|
||||
$<HTMLFormElement>('command-form').onsubmit = async event => {
|
||||
event.preventDefault(); const submit = $<HTMLButtonElement>('submit-command'); submit.disabled = true;
|
||||
const body = { ...draft, worldId: draft.op === 'create-world' ? $<HTMLInputElement>('world-input').value : draft.worldId, value: ['rename','create-world'].includes(draft.op) ? $<HTMLInputElement>('value-input').value : '', reason: $<HTMLTextAreaElement>('reason-input').value, confirm: $<HTMLInputElement>('confirm-input').value };
|
||||
const body = { ...draft, op:draft.op==='create-world'&&$<HTMLSelectElement>('world-kind').value==='hub'?'create-hub':draft.op, worldId: draft.op === 'create-world' ? $<HTMLInputElement>('world-input').value : draft.worldId, value: ['rename','create-world'].includes(draft.op) ? $<HTMLInputElement>('value-input').value : '', reason: $<HTMLTextAreaElement>('reason-input').value, confirm: $<HTMLInputElement>('confirm-input').value };
|
||||
try { await api('/api/control/commands', body); $<HTMLDialogElement>('command-dialog').close(); notify('Action queued. Execution status is recorded in the audit log.'); await refresh(); }
|
||||
catch (e) { $('command-error').textContent = (e as Error).message; }
|
||||
finally { submit.disabled = false; }
|
||||
|
||||
@@ -547,6 +547,7 @@ export interface WorldInfo {
|
||||
capacity: number;
|
||||
collapseInSeconds: number;
|
||||
id: string;
|
||||
kind?: string;
|
||||
online: number;
|
||||
phase: string;
|
||||
radius: number;
|
||||
|
||||
+16
-15
@@ -1,4 +1,5 @@
|
||||
import './style.css';
|
||||
import { showTravel } from './travel';
|
||||
import { createIcons, Crosshair, Settings2, X, Flame, LogOut, Hourglass, Swords, Pickaxe, HeartPulse, Gem, Backpack, ChevronUp, ChevronDown, ChevronLeft, ChevronRight, ArrowRight, RefreshCw } from 'lucide';
|
||||
import { WorldView } from './world-view';
|
||||
import type { Character, Chunk, Entity, Intent, Snapshot } from './generated';
|
||||
@@ -8,7 +9,7 @@ import { InputActions, isEditing, type InputAction } from './input-actions';
|
||||
import { hasOpenMenu, registerMenu } from './menu-focus';
|
||||
|
||||
type Recipe = { Inputs: Record<string, number>; Outputs: Record<string, number> };
|
||||
type Config = { worldId: string; development: boolean; worlds: { id: string; url: string }[]; recipes: Record<string, Recipe>; playerSpeed: number; gatherRange: number; attackRange: number };
|
||||
type Config = { worldId: string; kind: string; development: boolean; worlds: { id: string; url: string }[]; recipes: Record<string, Recipe>; playerSpeed: number; gatherRange: number; attackRange: number };
|
||||
const $ = <T extends HTMLElement = HTMLElement>(id: string) => document.getElementById(id) as T;
|
||||
const visible = (id: string, show: boolean) => { $(id).hidden = !show; };
|
||||
const pretty = (s: string) => s.replaceAll('_', ' ').replace(/^./, c => c.toUpperCase());
|
||||
@@ -60,7 +61,7 @@ async function api<T>(path: string, body?: unknown): Promise<T> {
|
||||
}
|
||||
function notice(message: string) { $('notice').textContent = message; visible('notice', true); clearTimeout(noticeTimer); noticeTimer = setTimeout(() => visible('notice', false), 3500); }
|
||||
function send(op: string, target = '', x = 0, z = 0, slot = '') {
|
||||
if (ws?.readyState !== WebSocket.OPEN || !snapshot || snapshot.self.entity.state !== 'alive') return;
|
||||
if (ws?.readyState !== WebSocket.OPEN || !snapshot || !['alive','eligible'].includes(snapshot.self.entity.state)) return;
|
||||
const intent: Intent = { op, target, x, z, slot, seq: ++sequence };
|
||||
ws.send(JSON.stringify(intent));
|
||||
}
|
||||
@@ -104,7 +105,6 @@ function connect() {
|
||||
$('connection-status').textContent = 'Connected'; $('connection-dot').parentElement!.classList.remove('offline');
|
||||
const state = value.self.entity.state;
|
||||
if (state === 'dead') showEnding('A life, remembered.', 'This character is permanently dead. Their belongings remain in this world.', false);
|
||||
else if (state === 'eligible') showEnding('A passage forward.', 'The Harbinger has fallen. Your character and belongings can continue to a new world.', true);
|
||||
else if (value.self.remainingSeconds <= 0) showEnding('Rest until tomorrow.', 'Your daily play time is complete. Your keystone will return you to your previous location after 00:00 UTC.', false);
|
||||
};
|
||||
ws.onclose = async () => {
|
||||
@@ -159,7 +159,7 @@ function minimap(s: Snapshot) {
|
||||
}
|
||||
function updateHUD(s: Snapshot) {
|
||||
const c = s.self, w = s.world;
|
||||
visible('game-controls', true); visible('movement', c.entity.state === 'alive' && $('inventory').hidden && $('settings').hidden);
|
||||
visible('game-controls', true); visible('movement', ['alive','eligible'].includes(c.entity.state) && $('inventory').hidden && $('settings').hidden);
|
||||
$('character-name').textContent = c.entity.name;
|
||||
$('character-level').textContent = `Level ${c.level || 1}`;
|
||||
$('character-experience').textContent = experienceText(c);
|
||||
@@ -179,10 +179,15 @@ function updateHUD(s: Snapshot) {
|
||||
$('season-clock').textContent = time(w.phase === 'gathering' ? w.bossInSeconds : w.collapseInSeconds);
|
||||
$('season-detail').textContent = w.phase === 'gathering' ? 'Until the Harbinger' : `${Math.round(w.safeRadius)}m of world remaining`;
|
||||
$('season-progress').style.width = `${w.safeRadius / w.radius * 100}%`;
|
||||
visible('boss-bar', w.phase === 'cataclysm'); $('boss-health').style.width = `${w.bossHp / w.bossMaxHp * 100}%`; $('boss-count').textContent = `${Math.ceil(w.bossHp)} / ${Math.ceil(w.bossMaxHp)}`;
|
||||
visible('boss-bar', w.phase === 'cataclysm' || w.phase === 'won'); $('boss-health').style.width = `${w.bossHp / w.bossMaxHp * 100}%`; $('boss-count').textContent = w.phase==='won'?'Portal at 0, 0':`${Math.ceil(w.bossHp)} / ${Math.ceil(w.bossMaxHp)}`;
|
||||
$('coordinates').textContent = `${Math.round(c.entity.position.x)}, ${Math.round(c.entity.position.z)}`;
|
||||
$('chunk-count').textContent = `${view.chunks.size} chunks`;
|
||||
if (!$('inventory').hidden) inventory(c);
|
||||
if(w.kind==='hub'){ $('phase-label').textContent='THE HUB';$('season-clock').textContent='Permanent haven';$('season-detail').textContent='Crafting allowed · No experience gained'; }
|
||||
if(w.phase==='won'){ $('season-clock').textContent='Portal open';$('season-detail').textContent='Find the victory portal at 0, 0'; }
|
||||
visible('target-boss',w.kind!=='hub');$('target-boss').textContent=w.phase==='won'?'Find victory portal':'Target Harbinger';$('target-boss').setAttribute('aria-label',w.phase==='won'?'Find victory portal':'Target Harbinger');
|
||||
visible('dev-boss',config.development&&w.kind!=='hub');
|
||||
$<HTMLButtonElement>('attack').disabled=w.kind==='hub'||w.phase==='won';$<HTMLButtonElement>('gather').disabled=w.kind==='hub'||w.phase==='won';
|
||||
selection(view.selected); minimap(s);
|
||||
if (s.message && s.message !== lastNotice) { notice(s.message); lastNotice = s.message; }
|
||||
}
|
||||
@@ -252,6 +257,8 @@ async function boot() {
|
||||
}, 50);
|
||||
const [loadedConfig, chunks] = await Promise.all([api<Config>('/api/config'), api<Chunk[]>('/api/preview'), view.load()]);
|
||||
config = loadedConfig;
|
||||
const travelButton=document.createElement('button');travelButton.id='travel';travelButton.textContent='Travel';travelButton.title='World travel';$('inventory-toggle').before(travelButton);
|
||||
travelButton.onclick=()=>{if(!snapshot)return;input.clear();walkTo=undefined;pendingAction=undefined;send('move');void showTravel({worldId:config.worldId,route:config.kind==='hub'?'hub':snapshot.world.phase==='won'?'portal':'escape',beforeTravel:()=>{requestedClose=true;},afterTravel:departed=>{requestedClose=departed;}});};
|
||||
$<HTMLInputElement>('zoom').value = String(view.distance);
|
||||
view.addChunks(chunks); view.updateEntities(chunks.flatMap(c => c.resources));
|
||||
$('connection-status').textContent = 'World online';
|
||||
@@ -262,19 +269,13 @@ async function boot() {
|
||||
else if (me?.character) {
|
||||
$<HTMLDialogElement>('arrival').close();
|
||||
if (me.character.entity.state === 'dead') showEnding('A life, remembered.', 'This character is permanently dead. A fresh world is a new beginning.', false);
|
||||
else if (me.character.entity.state === 'eligible') showEnding('A passage forward.', 'Your survivor passage is saved.', true);
|
||||
else connect();
|
||||
} else {
|
||||
if (me?.active) {
|
||||
visible('join-form', false);
|
||||
const link = document.createElement('a'); link.href = `/game?world=${encodeURIComponent(me.active.worldId)}`; link.className = 'command'; link.textContent = `Continue ${me.active.name} in ${me.active.worldId}`; $('passages').append(link);
|
||||
}
|
||||
const passages = await api<{ characterId: string; sourceWorld: string; name: string }[]>('/api/passages').catch(() => []);
|
||||
for (const passage of passages.filter(p => p.sourceWorld !== config.worldId)) {
|
||||
const button = document.createElement('button'); button.textContent = `Continue as ${passage.name}`;
|
||||
button.onclick = async () => { try { await api('/api/join', { name: '', passage: passage.characterId }); $<HTMLDialogElement>('arrival').close(); connect(); } catch (e) { $('arrival-error').textContent = String((e as Error).message); } };
|
||||
$('passages').append(button);
|
||||
const link = document.createElement('a'); link.href = me.active.state==='transit'?'/':`/game?world=${encodeURIComponent(me.active.worldId)}`; link.className = 'command'; link.textContent = me.active.state==='transit'?'Resume travel from your account':`Continue ${me.active.name} in ${me.active.worldId}`; $('passages').append(link);
|
||||
}
|
||||
if(config.kind==='hub'){visible('join-form',false);$('arrival-error').textContent='Enter a hub through travel from your current character. Open your account to continue.';}
|
||||
}
|
||||
$<HTMLFormElement>('join-form').onsubmit = async event => {
|
||||
event.preventDefault(); const button = $<HTMLButtonElement>('join'); button.disabled = true;
|
||||
@@ -292,7 +293,7 @@ async function boot() {
|
||||
document.querySelectorAll<HTMLButtonElement>(`[data-close="${id}"]`).forEach(button=>button.onclick=()=>menu.close());
|
||||
}
|
||||
$('jump').onclick = () => input.trigger('jump'); $('attack').onclick = () => input.trigger('attack'); $('gather').onclick = () => input.trigger('gather'); $('heal').onclick = () => input.trigger('heal'); $('keystone').onclick = () => input.trigger('return');
|
||||
$('target-boss').onclick = () => { selection(snapshot?.entities.find(e => e.id === 'boss')); walkTo = { x: 0, z: 0 }; pendingAction = { op: 'attack', target: 'boss' }; lastProgress = undefined; lastProgressAt = Date.now(); };
|
||||
$('target-boss').onclick = () => { if(snapshot?.world.phase==='won'){walkTo={x:0,z:0};pendingAction=undefined;return;} selection(snapshot?.entities.find(e => e.id === 'boss')); walkTo = { x: 0, z: 0 }; pendingAction = { op: 'attack', target: 'boss' }; lastProgress = undefined; lastProgressAt = Date.now(); };
|
||||
$('dev-boss').onclick = () => void api('/api/dev/boss', {}).catch(e => notice(e.message));
|
||||
$('reconnect').onclick = () => location.reload();
|
||||
$('new-character').onclick = () => { requestedClose = true; ws?.close(); location.reload(); };
|
||||
@@ -310,7 +311,7 @@ async function boot() {
|
||||
view.canvas.addEventListener('pointerdown', event => {
|
||||
if (!snapshot || hasOpenMenu() || $<HTMLDialogElement>('arrival').open || $<HTMLDialogElement>('ending').open || event.button !== 0) return;
|
||||
const hit = view.pick(event.clientX, event.clientY);
|
||||
if (hit.entity) { selection(hit.entity); action(['boss', 'sentinel','mob','player'].includes(hit.entity.kind) ? 'attack' : 'gather'); }
|
||||
if (hit.entity) { if(hit.entity.kind==='portal'){$('travel').click();return;} selection(hit.entity); action(['boss', 'sentinel','mob','player'].includes(hit.entity.kind) ? 'attack' : 'gather'); }
|
||||
else if (hit.point) { selection(); walkTo = hit.point; pendingAction = undefined; }
|
||||
});
|
||||
Object.defineProperty(window, '__aeternalis', { value: { diagnostics: () => view.diagnostics(), get snapshot() { return snapshot; }, get walkTo() { return walkTo; }, get pendingAction() { return pendingAction; }, get keys() { return input.keys; } }, configurable: true });
|
||||
|
||||
@@ -21,7 +21,7 @@ export function playerContent(record:RecordCharacter,enabled:boolean,onQueued:()
|
||||
for(const i of catalog.items)choice.append(new Option(`${i.name} (${i.id})`,i.id));
|
||||
for(const r of catalog.gathering?.resources??[])if(r.output==='self')choice.append(new Option(r.name,r.id));
|
||||
for(const i of catalog.gathering?.consumables??[])choice.append(new Option(i.name,i.id));
|
||||
for(const id of ['axe','flint_and_steel','fishing_pole','wood','ore','herb','bandage'])choice.append(new Option(statLabel(id),id));
|
||||
for(const id of ['axe','flint_and_steel','fishing_pole','wood','ore','herb','bandage','escape_stone'])choice.append(new Option(statLabel(id),id));
|
||||
notice.textContent='Items go into the bag. Equipment requirements still apply when equipping.';break;
|
||||
case 'remove-item':
|
||||
for(const i of v.items??[]){const slot=Object.entries(v.equipment??{}).find(([,id])=>id===i.id)?.[0];choice.append(new Option(`${i.name}${slot?` [${statLabel(slot)}]`:''} · ${i.id}`,i.id));}
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { Character } from './generated';
|
||||
import './theme';
|
||||
|
||||
export type RecordCharacter = { id: string; account: string; worldId: string; name: string; state: string; character: { view: Character; bornAt: string; diedAt?: string; deathReason?: string; dailySeconds: number } };
|
||||
export type World = { id: string; phase: string; living: number; dead: number; capacity: number; createdAt: string; bossAt: string; closed: boolean; available: boolean; revision: number; catalogVersion: number };
|
||||
export type World = { id: string; kind: string; phase: string; living: number; dead: number; capacity: number; createdAt: string; bossAt: string; closed: boolean; available: boolean; revision: number; catalogVersion: number };
|
||||
export type Command = { id: string; worldId: string; actor: string; op: string; target: string; value: string; reason: string; status: string; result: string; createdAt: number; completedAt: number };
|
||||
export const $ = <T extends HTMLElement = HTMLElement>(id: string) => document.getElementById(id) as T;
|
||||
export const el = <K extends keyof HTMLElementTagNameMap>(tag: K, text = '', className = '') => { const node = document.createElement(tag); node.textContent = text; node.className = className; return node; };
|
||||
|
||||
+5
-3
@@ -1,4 +1,5 @@
|
||||
import './portal.css';
|
||||
import { showTravel } from './travel';
|
||||
import { permanentTitles, progressionSummary } from './progression';
|
||||
import { $, api, APIError, badge, cell, date, el, gameURL, icons, icon, table, type RecordCharacter, type World } from './portal-shared';
|
||||
|
||||
@@ -16,9 +17,10 @@ function renderWorlds(worlds: World[]) {
|
||||
const heading = el('div', '', 'world-name'); heading.append(el('h3', world.id), badge(!world.available ? 'offline' : world.phase));
|
||||
const population = el('div', '', 'world-stat'); population.append(el('span', 'Living'), el('strong', `${world.living} / ${world.capacity}`));
|
||||
const clock = el('div', '', 'world-stat'); clock.append(el('span', world.phase === 'gathering' ? 'Harbinger arrives' : 'Season'), el('strong', world.phase === 'gathering' ? date(world.bossAt) : world.phase === 'cataclysm' ? 'The world is collapsing' : 'Ended'));
|
||||
if(world.kind==='hub'){clock.replaceChildren(el('span','Hub instance'),el('strong','Permanent haven · No XP'));}
|
||||
const active = account?.active;
|
||||
const resume = active?.worldId === world.id;
|
||||
const transfer = active?.state === 'eligible' && active.worldId !== world.id && world.phase === 'gathering';
|
||||
const transfer = false;
|
||||
const open = world.available && (resume || (!world.closed && world.living < world.capacity && ['gathering', 'cataclysm'].includes(world.phase) && (!active || transfer)));
|
||||
const action = el('a', resume ? 'Continue' : transfer ? 'Use passage' : 'Enter world', `button ${open ? '' : 'disabled'}`);
|
||||
if (open) action.href = gameURL(world.id); else { action.setAttribute('aria-disabled', 'true'); action.title = active && !resume && !transfer ? `Living character in ${active.worldId}` : 'World unavailable for arrivals'; }
|
||||
@@ -33,8 +35,8 @@ function renderAccount() {
|
||||
if (!account) { history.append(el('p', 'Sign in to see your characters.', 'empty')); return; }
|
||||
if (account.active) {
|
||||
const r = account.active; const summary = el('div', '', 'active-life'); const title = el('div', '', 'active-life-summary');
|
||||
title.append(el('h3', r.name), el('p', `${r.worldId} / ${r.state === 'eligible' ? 'Passage earned' : `${Math.ceil(r.character.view.entity.hp)} health`}`, 'muted'), progressionSummary(r.character.view));
|
||||
const link = el('a', 'Continue journey', 'button'); link.href = gameURL(r.worldId); link.append(icon('arrow-right')); summary.append(title, link);
|
||||
title.append(el('h3', r.name), el('p', `${r.state==='transit'?'Travel in progress':r.worldId} / ${r.state === 'eligible' ? 'Passage earned' : `${Math.ceil(r.character.view.entity.hp)} health`}`, 'muted'), progressionSummary(r.character.view));
|
||||
const link = el('a', r.state==='transit'?'Resume travel':'Continue journey', 'button'); link.href = r.state==='transit'?'#':gameURL(r.worldId);if(r.state==='transit')link.onclick=e=>{e.preventDefault();void showTravel();}; link.append(icon('arrow-right')); summary.append(title, link);
|
||||
const titles = el('section', '', 'active-titles'); titles.append(el('h3', 'Permanent titles'), permanentTitles(r.character.view.titles)); parent.append(summary, titles);
|
||||
}
|
||||
else parent.append(el('p', 'Your next life is waiting in an open world.', 'empty'));
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
.travel-dialog{box-sizing:border-box;width:min(540px,calc(100vw - 28px));max-height:90dvh;overflow:auto;padding:26px;border:1px solid #6b8279;border-radius:16px;background:#192923;color:#e9eee6;box-shadow:0 18px 80px #0008;font:15px/1.5 system-ui,sans-serif;z-index:100}
|
||||
.travel-dialog::backdrop{background:#08100bc2}.travel-dialog h2{margin:0 0 12px}.travel-dialog label{display:grid;gap:8px}.travel-dialog p{color:#c5d2c7}.travel-dialog select,.travel-dialog button{font:inherit;color:inherit;background:#2d4438;border:1px solid #65816f;border-radius:7px;padding:10px}.travel-dialog select{width:100%}.travel-dialog footer{display:flex;flex-wrap:wrap;gap:8px;margin-top:18px}.travel-dialog button{cursor:pointer}.travel-dialog button:disabled{opacity:.5;cursor:wait}.travel-dialog button:last-child{background:#44634a}.travel-dialog [role=status]{min-height:24px}
|
||||
.travel-dialog footer a{align-self:center;color:#c5e8d0;padding:10px}.actions{flex-wrap:wrap;max-width:100%}.actions #travel{font-size:11px}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { api, el, gameURL, type World } from './portal-shared';
|
||||
import { registerMenu } from './menu-focus';
|
||||
import './travel.css';
|
||||
|
||||
type Transfer = { id: string; source: string; sourceKind: string; destination: string; route: string; status: string; acceptedWorld: string };
|
||||
type Departure = { worldId: string; route: 'hub' | 'escape' | 'portal'; beforeTravel?: () => void; afterTravel?: (departed: boolean) => void };
|
||||
let open = false;
|
||||
export async function showTravel(source?: Departure) {
|
||||
if (open) return; open = true;
|
||||
const dialog = el('dialog', '', 'travel-dialog');
|
||||
const heading = el('h2', 'Travel'), description = el('p'), status = el('p'); status.setAttribute('role', 'status');
|
||||
const label = el('label', 'Destination'), select = el('select'); label.append(select);
|
||||
const close = el('button', 'Close'), refresh = el('button', 'Refresh destinations'), go = el('button', 'Travel');
|
||||
const account = el('a','Account'); account.href='/';
|
||||
const footer = el('footer'); footer.append(close, refresh, account, go); dialog.append(heading, description, label, status, footer); document.body.append(dialog);
|
||||
let transfer: Transfer | null = null, busy = false, prepared = false;
|
||||
const requestId = crypto.randomUUID();
|
||||
const menu = registerMenu(dialog, () => { dialog.close(); dialog.remove(); menu.dispose(); open = false; if (prepared && source) location.href = '/'; });
|
||||
close.onclick = menu.close; dialog.oncancel = event => { event.preventDefault(); menu.close(); };
|
||||
dialog.showModal(); menu.opened();
|
||||
async function load() {
|
||||
go.disabled = true;
|
||||
try {
|
||||
const [pending, worlds] = await Promise.all([api<Transfer | null>('/api/travel'), api<World[]>('/api/worlds')]);
|
||||
transfer = pending ?? transfer;
|
||||
if (!source && !transfer) { description.textContent='No journey is waiting to finish.'; status.textContent='Refresh your account to continue your character.'; return; }
|
||||
const fromHub = transfer ? transfer.sourceKind === 'hub' : source?.route === 'hub';
|
||||
description.textContent = transfer ? 'Your character and belongings are saved in transit. Choose an available destination to finish your journey.' : source?.route === 'portal' ? 'Stand beside the victory portal to enter a hub. Your character, belongings and progression travel with you.' : fromHub ? 'Switch hub instances or enter a survival world. Once there, you need an escape stone or a Harbinger victory to return.' : 'Consumes one escape stone to reach a hub. Escaping does not count as surviving this world.';
|
||||
const previous = select.value || transfer?.destination;
|
||||
select.replaceChildren();
|
||||
for (const w of worlds.filter(w => w.available && !w.closed && w.living < w.capacity && ['hub', 'gathering', 'cataclysm'].includes(w.phase) && (fromHub || w.kind === 'hub') && (transfer || w.id !== source?.worldId))) {
|
||||
select.append(new Option(`${w.id} · ${w.kind === 'hub' ? 'Hub' : w.phase === 'cataclysm' ? 'Collapsing world' : 'Survival world'} · ${w.living}/${w.capacity}`, w.id));
|
||||
}
|
||||
if ([...select.options].some(o => o.value === previous)) select.value = previous!;
|
||||
go.textContent = transfer ? 'Finish travel' : source?.route === 'escape' ? 'Use escape stone & travel' : 'Travel';
|
||||
go.disabled = !select.options.length || (!source && !transfer);
|
||||
status.textContent = select.options.length ? '' : 'No destination is available. Your saved character remains safe in transit if departure already completed.';
|
||||
} catch (e) { status.textContent = (e as Error).message; }
|
||||
}
|
||||
refresh.onclick = () => { if (!busy) void load(); };
|
||||
go.onclick = async () => {
|
||||
if (busy) return; busy = true; go.disabled = refresh.disabled = close.disabled = true; select.disabled = true;
|
||||
try {
|
||||
source?.beforeTravel?.();
|
||||
if (!transfer) {
|
||||
if (!source) throw new Error('No pending journey. Refresh your account.');
|
||||
transfer = await api<Transfer>(`/worlds/${source.worldId}/api/travel/prepare`, { requestId, destination: select.value, route: source.route });
|
||||
}
|
||||
prepared = true;
|
||||
if (transfer.status !== 'accepted') transfer = await api<Transfer>(`/worlds/${select.value}/api/travel/accept`, { transferId: transfer.id });
|
||||
location.href = gameURL(transfer.acceptedWorld);
|
||||
} catch (e) {
|
||||
// Recover either side of a lost HTTP response from durable server state.
|
||||
const message = (e as Error).message;
|
||||
try {
|
||||
if (transfer) { const saved = await api<Transfer | null>(`/api/travel?id=${encodeURIComponent(transfer.id)}`); if (saved?.status === 'accepted') { location.href = gameURL(saved.acceptedWorld); return; } }
|
||||
await load(); if (transfer) prepared = true;
|
||||
} catch { /* Keep the current transfer ID available for retry. */ }
|
||||
status.textContent = `${message} You can retry or return to your account to resume travel.`;
|
||||
} finally { busy = false; source?.afterTravel?.(prepared); go.disabled = !select.options.length || (!source && !transfer); refresh.disabled = close.disabled = select.disabled = false; if(prepared && !dialog.isConnected) location.href='/'; }
|
||||
};
|
||||
await load();
|
||||
}
|
||||
@@ -97,6 +97,8 @@ export class WorldView {
|
||||
this.scene.add(mesh); peers.parts.push(mesh);
|
||||
});
|
||||
this.batches.set('player', peers);
|
||||
const portalMesh = new T.InstancedMesh(new T.TorusGeometry(2,.22,8,40).translate(0,2.5,0),new T.MeshBasicMaterial({color:'#86ffe0'}),8);
|
||||
portalMesh.count=0;portalMesh.userData.kind='portal';this.scene.add(portalMesh);this.batches.set('portal',{parts:[portalMesh],entities:[]});
|
||||
const corpseMesh = new T.InstancedMesh(new T.BoxGeometry(1.1, 0.45, 2.1), new T.MeshStandardMaterial({ color: '#77766d' }), 2048);
|
||||
corpseMesh.count = 0; corpseMesh.userData.kind = 'corpse'; this.scene.add(corpseMesh);
|
||||
this.batches.set('corpse', { parts: [corpseMesh], entities: [] });
|
||||
|
||||
Reference in New Issue
Block a user