Build playable Aeternalis foundation and GitOps deployment pipeline

This commit is contained in:
dingo
2026-09-05 12:52:51 -04:00
parent 93703b20bc
commit ff87b8a544
66 changed files with 6567 additions and 0 deletions
+223
View File
@@ -0,0 +1,223 @@
import './style.css';
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';
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 };
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());
const time = (seconds: number) => seconds >= 86400 ? `${Math.floor(seconds / 86400)}d ${Math.floor(seconds % 86400 / 3600)}h` : seconds >= 3600 ? `${Math.floor(seconds / 3600)}h ${Math.floor(seconds % 3600 / 60)}m` : `${Math.floor(seconds / 60)}m ${Math.floor(seconds % 60)}s`;
let config: Config;
let snapshot: Snapshot | undefined;
let ws: WebSocket | undefined;
let sequence = 0;
let lastNotice = '';
let noticeTimer: ReturnType<typeof setTimeout>;
let inputElapsed = 0;
let walkTo: { x: number; z: number } | undefined;
let pendingAction: { op: string; target: string } | undefined;
let requestedClose = false;
const keys = new Set<string>();
let view: WorldView;
async function api<T>(path: string, body?: unknown): Promise<T> {
const response = await fetch(path, { method: body === undefined ? 'GET' : 'POST', credentials: 'same-origin', headers: body === undefined ? {} : { 'Content-Type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) });
const result = await response.json();
if (!response.ok) throw new Error(result.error ?? `Request failed (${response.status})`);
return result as 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) {
if (ws?.readyState !== WebSocket.OPEN || !snapshot || snapshot.self.entity.state !== 'alive') return;
const intent: Intent = { op, target, x, z, seq: ++sequence };
ws.send(JSON.stringify(intent));
}
function selection(entity?: Entity) {
view.selected = entity; visible('target', !!entity);
if (entity) { $('target-name').textContent = entity.name; $('target-health').textContent = ['boss', 'sentinel', 'player'].includes(entity.kind) ? `${Math.ceil(entity.hp)} / ${Math.ceil(entity.maxHp)}` : pretty(entity.kind); }
}
function action(op: string) {
if (!snapshot) return;
const kinds = op === 'attack' ? ['boss', 'sentinel'] : ['tree', 'ore', 'herb', 'corpse'];
let target = view.selected;
if (!target || !kinds.includes(target.kind)) {
const p = snapshot.self.entity.position;
target = snapshot.entities.filter(e => kinds.includes(e.kind)).sort((a, b) => Math.hypot(a.position.x - p.x, a.position.z - p.z) - Math.hypot(b.position.x - p.x, b.position.z - p.z))[0];
}
if (!target) { notice('No target nearby.'); return; }
selection(target);
pendingAction = { op: target.kind === 'corpse' ? 'loot' : op, target: target.id };
walkTo = target.position;
}
function connect() {
requestedClose = false; sequence = 0;
const ending = $<HTMLDialogElement>('ending'); ending.close();
ws = new WebSocket(`${location.protocol === 'https:' ? 'wss:' : 'ws:'}//${location.host}/ws`);
ws.onopen = () => { $('connection-status').textContent = 'Connected'; $('connection-dot').parentElement!.classList.remove('offline'); };
ws.onmessage = event => {
const value = JSON.parse(event.data) as Snapshot;
if (value.type !== 'snapshot' || value.version !== 1) { ws?.close(); notice('Client and server versions do not match.'); return; }
snapshot = value; view.update(value); updateHUD(value);
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 () => {
$('connection-status').textContent = 'Disconnected'; $('connection-dot').parentElement!.classList.add('offline'); keys.clear(); walkTo = undefined;
if (requestedClose || $<HTMLDialogElement>('ending').open) return;
let detail = 'The connection ended. Your character state is held by the server.';
try { const me = await api<{ character?: Character }>('/api/me'); if (me.character?.entity.state === 'dead') { showEnding('A life, remembered.', 'This character is permanently dead.', false); return; } if (me.character?.remainingSeconds === 0) detail = 'Daily play time is complete. Return after 00:00 UTC.'; } catch { detail = 'Your session ended. Sign in again to continue.'; }
showEnding('Connection interrupted.', detail, false); visible('reconnect', true);
};
}
function showEnding(title: string, detail: string, survivor: boolean) {
keys.clear(); walkTo = undefined; pendingAction = undefined;
$('ending-title').textContent = title; $('ending-detail').textContent = detail;
$('ending-eyebrow').textContent = survivor ? 'WORLD SURVIVED' : 'JOURNEY PAUSED';
if (snapshot?.self.entity.state === 'dead') $('ending-eyebrow').textContent = 'JOURNEY ENDED';
const destinations = $('destinations'); destinations.replaceChildren();
if (survivor) for (const destination of config.worlds.filter(w => w.id !== config.worldId)) {
const link = document.createElement('a'); link.href = destination.url; link.textContent = `Travel to ${destination.id}`; link.rel = 'noopener'; destinations.append(link);
}
if (survivor && destinations.children.length === 0) { const p = document.createElement('p'); p.textContent = 'Your passage is saved. No destination world is open yet.'; destinations.append(p); }
visible('reconnect', false);
$<HTMLDialogElement>('ending').show();
}
function inventory(c: Character) {
const parent = $('inventory-items'); parent.replaceChildren();
for (const [item, count] of Object.entries(c.inventory).filter(([, n]) => n > 0)) {
const div = document.createElement('div'); div.className = 'item';
const text = document.createElement('span'); text.textContent = pretty(item);
const quantity = document.createElement('b'); quantity.textContent = String(count);
div.append(text, quantity); parent.append(div);
}
const recipes = $('recipes'); recipes.replaceChildren();
for (const [name, recipe] of Object.entries(config.recipes)) {
const row = document.createElement('div'); row.className = 'recipe';
const label = document.createElement('div'), title = document.createElement('strong'), cost = document.createElement('small');
title.textContent = pretty(name); cost.textContent = Object.entries(recipe.Inputs).map(([k, n]) => `${n} ${pretty(k)}`).join(' + '); label.append(title, cost);
const button = document.createElement('button'); button.textContent = 'Craft'; button.title = `Craft ${name}`; button.disabled = Object.entries(recipe.Inputs).some(([item, count]) => (c.inventory[item] ?? 0) < count); button.onclick = () => send('craft', name);
row.append(label, button); recipes.append(row);
}
const skills = $('skills'); skills.replaceChildren();
for (const skill of ['gathering', 'crafting', 'combat']) { const label = document.createElement('span'); label.textContent = pretty(skill); const amount = document.createElement('b'); amount.textContent = `${c.skills[skill] ?? 0} XP`; label.append(amount); skills.append(label); }
}
function minimap(s: Snapshot) {
const canvas = $<HTMLCanvasElement>('minimap'), ctx = canvas.getContext('2d')!;
const p = s.self.entity.position, radius = s.world.radius;
ctx.clearRect(0, 0, 140, 140); ctx.save(); ctx.beginPath(); ctx.arc(70, 70, 66, 0, Math.PI * 2); ctx.clip();
ctx.fillStyle = '#263c30'; ctx.fillRect(0, 0, 140, 140);
ctx.strokeStyle = '#77916a50'; ctx.lineWidth = 1;
for (let i = 6; i < 140; i += 16) { ctx.beginPath(); ctx.moveTo(i, 0); ctx.lineTo(i, 140); ctx.stroke(); ctx.beginPath(); ctx.moveTo(0, i); ctx.lineTo(140, i); ctx.stroke(); }
ctx.strokeStyle = s.world.phase === 'cataclysm' ? '#e18a8a' : '#aebc92'; ctx.lineWidth = 2; ctx.beginPath(); ctx.arc(70, 70, 62 * s.world.safeRadius / radius, 0, Math.PI * 2); ctx.stroke();
if (s.world.phase === 'cataclysm') { ctx.fillStyle = '#ed7963'; ctx.fillRect(67, 67, 6, 6); }
ctx.fillStyle = '#ecedbd'; ctx.beginPath(); ctx.arc(70 + p.x / radius * 62, 70 + p.z / radius * 62, 3, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = '#d4debf'; ctx.font = '9px sans-serif'; ctx.fillText('N', 67, 15); ctx.restore();
}
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);
$('character-name').textContent = c.entity.name;
$('health-number').textContent = `${Math.max(0, Math.ceil(c.entity.hp))} / ${Math.ceil(c.entity.maxHp)}`;
$('health-fill').style.width = `${Math.max(0, c.entity.hp / c.entity.maxHp * 100)}%`;
$('play-time').textContent = `${time(c.remainingSeconds)} left today`;
$('kills').textContent = `${c.kills} kills`;
$('bandage-count').textContent = String(c.inventory.bandage ?? 0);
$<HTMLButtonElement>('heal').disabled = !c.inventory.bandage || c.entity.hp >= c.entity.maxHp;
$<HTMLButtonElement>('keystone').disabled = !c.hasKeystone;
$('world-name').textContent = `${w.id} / ${w.online} online`;
$('phase-label').textContent = w.phase === 'gathering' ? 'THE GATHERING' : w.phase === 'cataclysm' ? 'THE UNRAVELING' : w.phase === 'won' ? 'WORLD SURVIVED' : 'WORLD LOST';
$('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)}`;
$('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);
selection(view.selected); minimap(s);
if (s.message && s.message !== lastNotice) { notice(s.message); lastNotice = s.message; }
}
async function boot() {
createIcons({ icons: { Crosshair, Settings2, X, Flame, LogOut, Hourglass, Swords, Pickaxe, HeartPulse, Gem, Backpack, ChevronUp, ChevronDown, ChevronLeft, ChevronRight, ArrowRight, RefreshCw } });
view = new WorldView($<HTMLCanvasElement>('world'));
view.start(dt => {
inputElapsed += dt;
if (!snapshot || ws?.readyState !== WebSocket.OPEN || $<HTMLDialogElement>('ending').open) return;
let x = Number(keys.has('d') || keys.has('arrowright')) - Number(keys.has('a') || keys.has('arrowleft'));
let z = Number(keys.has('s') || keys.has('arrowdown')) - Number(keys.has('w') || keys.has('arrowup'));
if (x || z) { walkTo = undefined; pendingAction = undefined; }
if (walkTo) {
const p = snapshot.self.entity.position, dx = walkTo.x - p.x, dz = walkTo.z - p.z, distance = Math.hypot(dx, dz);
const target = snapshot.entities.find(e => e.id === pendingAction?.target);
const range = pendingAction ? pendingAction.op === 'attack' ? config.attackRange + (target?.kind === 'boss' ? 3 : -0.5) : config.gatherRange - 0.5 : 0.8;
if (distance <= range) { if (pendingAction) send(pendingAction.op, pendingAction.target); walkTo = undefined; pendingAction = undefined; }
else { x = dx / distance; z = dz / distance; }
}
view.moving = !!(x || z);
if (inputElapsed >= 0.05) { send('move', '', x, z); inputElapsed = 0; }
});
const [loadedConfig, chunks] = await Promise.all([api<Config>('/api/config'), api<Chunk[]>('/api/preview'), view.load()]);
config = loadedConfig;
$<HTMLInputElement>('zoom').value = String(view.distance);
view.addChunks(chunks); view.updateEntities(chunks.flatMap(c => c.resources));
$('connection-status').textContent = 'World online';
visible('dev-boss', config.development);
let me: { character: Character | null } | undefined;
try { me = await api('/api/me'); } catch { if (config.development) { await api('/auth/dev', {}); me = await api('/api/me'); } }
if (!me && !config.development) { visible('join-form', false); visible('login', true); }
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 {
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);
}
}
$<HTMLFormElement>('join-form').onsubmit = async event => {
event.preventDefault(); const button = $<HTMLButtonElement>('join'); button.disabled = true;
try { await api('/api/join', { name: $<HTMLInputElement>('name').value, passage: '' }); $<HTMLDialogElement>('arrival').close(); connect(); }
catch (e) { $('arrival-error').textContent = (e as Error).message; }
finally { button.disabled = false; }
};
for (const id of ['inventory', 'settings']) { $(`${id}-toggle`).onclick = () => { visible(id, $(id).hidden); visible('movement', $('inventory').hidden && $('settings').hidden && !!snapshot); if (id === 'inventory' && snapshot) inventory(snapshot.self); }; }
document.querySelectorAll<HTMLButtonElement>('[data-close]').forEach(button => button.onclick = () => visible(button.dataset.close!, false));
$('attack').onclick = () => action('attack'); $('gather').onclick = () => action('gather'); $('heal').onclick = () => send('heal'); $('keystone').onclick = () => send('return');
$('target-boss').onclick = () => { selection(snapshot?.entities.find(e => e.id === 'boss')); walkTo = { x: 0, z: 0 }; pendingAction = { op: 'attack', target: 'boss' }; };
$('dev-boss').onclick = () => void api('/api/dev/boss', {}).catch(e => notice(e.message));
$('reconnect').onclick = () => location.reload();
$('logout').onclick = async () => { requestedClose = true; await api('/auth/logout', {}); ws?.close(); location.reload(); };
$<HTMLSelectElement>('quality').onchange = event => view.quality((event.target as HTMLSelectElement).value === 'high');
$<HTMLInputElement>('zoom').oninput = event => { view.distance = Number((event.target as HTMLInputElement).value); view.resize(); };
window.addEventListener('keydown', event => {
if ((event.target as HTMLElement).matches('input,select,textarea') || $<HTMLDialogElement>('arrival').open) return;
const key = event.key.toLowerCase();
if (['w', 'a', 's', 'd', 'arrowup', 'arrowdown', 'arrowleft', 'arrowright', ' '].includes(key)) event.preventDefault();
keys.add(key); if (event.repeat) return;
if (key === 'e') action('gather'); if (key === ' ') action('attack'); if (key === 'i') $('inventory-toggle').click(); if (key === 'escape') { visible('inventory', false); visible('settings', false); selection(); walkTo = undefined; }
});
window.addEventListener('keyup', event => keys.delete(event.key.toLowerCase()));
window.addEventListener('blur', () => { keys.clear(); walkTo = undefined; send('move'); });
document.addEventListener('visibilitychange', () => { if (document.hidden) { keys.clear(); walkTo = undefined; send('move'); } });
const movements: Record<string, string> = { up: 'w', down: 's', left: 'a', right: 'd' };
document.querySelectorAll<HTMLButtonElement>('[data-move]').forEach(button => {
const key = movements[button.dataset.move!];
button.onpointerdown = event => { button.setPointerCapture(event.pointerId); keys.add(key); };
button.onpointerup = button.onpointercancel = () => keys.delete(key);
});
view.canvas.addEventListener('pointerdown', event => {
if (!snapshot || $<HTMLDialogElement>('ending').open || event.button !== 0) return;
const hit = view.pick(event.clientX, event.clientY);
if (hit.entity) { selection(hit.entity); action(['boss', 'sentinel'].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; } }, configurable: true });
}
boot().catch(error => { console.error(error); $('arrival-error').textContent = `Unable to enter the world: ${error.message}`; $('connection-status').textContent = 'Unavailable'; });