Build playable Aeternalis foundation and GitOps deployment pipeline
This commit is contained in:
@@ -0,0 +1,10 @@
|
||||
.git
|
||||
.local
|
||||
.tools
|
||||
node_modules
|
||||
client/dist
|
||||
assets
|
||||
test-results
|
||||
playwright-report
|
||||
*.log
|
||||
*.exe
|
||||
@@ -0,0 +1,6 @@
|
||||
* text=auto eol=lf
|
||||
*.ps1 text eol=crlf
|
||||
*.glb binary
|
||||
*.blend binary
|
||||
*.png binary
|
||||
*.exe binary
|
||||
@@ -0,0 +1,82 @@
|
||||
name: Verify, publish, and promote
|
||||
on:
|
||||
push:
|
||||
branches: [master, main]
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
verify:
|
||||
runs-on: ubuntu-latest
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:17-alpine
|
||||
env:
|
||||
POSTGRES_USER: aeternalis
|
||||
POSTGRES_PASSWORD: ci-test-only
|
||||
POSTGRES_DB: aeternalis_test
|
||||
options: >-
|
||||
--health-cmd "pg_isready -U aeternalis -d aeternalis_test"
|
||||
--health-interval 5s --health-timeout 5s --health-retries 10
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with: { node-version: "24", cache: npm }
|
||||
- uses: actions/setup-go@v5
|
||||
with: { go-version-file: server/go.mod, cache-dependency-path: server/go.sum }
|
||||
- run: npm ci --no-fund
|
||||
- run: npm run test:contracts && npm run check && npm run build
|
||||
- name: Go tests, race detector, and PostgreSQL integration
|
||||
working-directory: server
|
||||
env:
|
||||
TEST_DATABASE_URL: postgres://aeternalis:ci-test-only@postgres:5432/aeternalis_test?sslmode=disable
|
||||
run: go test -race -count=1 ./...
|
||||
- name: Go static analysis
|
||||
working-directory: server
|
||||
run: go vet ./...
|
||||
- run: npx playwright install --with-deps chromium
|
||||
- run: npm run test:e2e
|
||||
- uses: azure/setup-helm@v4.3.0
|
||||
- run: helm lint deploy/chart && helm template aeternalis deploy/chart > /tmp/aeternalis.yaml
|
||||
|
||||
publish:
|
||||
if: gitea.event_name == 'push'
|
||||
needs: verify
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
digest: ${{ steps.build.outputs.digest }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: docker/setup-buildx-action@v3
|
||||
- uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ vars.HARBOR_HOST }}
|
||||
username: ${{ secrets.HARBOR_USERNAME }}
|
||||
password: ${{ secrets.HARBOR_PASSWORD }}
|
||||
- uses: docker/build-push-action@v6
|
||||
id: build
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
tags: ${{ vars.HARBOR_HOST }}/${{ vars.HARBOR_PROJECT }}/aeternalis:${{ gitea.sha }}
|
||||
provenance: true
|
||||
sbom: true
|
||||
|
||||
promote:
|
||||
if: gitea.event_name == 'push' && vars.GITOPS_REPOSITORY != ''
|
||||
needs: publish
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with: { node-version: "24" }
|
||||
- run: npm ci --no-fund
|
||||
- name: Update GitOps image digest
|
||||
env:
|
||||
GITOPS_REPOSITORY: ${{ vars.GITOPS_REPOSITORY }}
|
||||
GITOPS_BRANCH: ${{ vars.GITOPS_BRANCH }}
|
||||
GITOPS_VALUES_FILE: ${{ vars.GITOPS_VALUES_FILE }}
|
||||
GITOPS_USERNAME: ${{ secrets.GITOPS_USERNAME }}
|
||||
GITOPS_TOKEN: ${{ secrets.GITOPS_TOKEN }}
|
||||
IMAGE_REPOSITORY: ${{ vars.HARBOR_HOST }}/${{ vars.HARBOR_PROJECT }}/aeternalis
|
||||
IMAGE_DIGEST: ${{ needs.publish.outputs.digest }}
|
||||
run: node tools/promote-gitops.mjs
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
node_modules/
|
||||
client/dist/
|
||||
.local/
|
||||
.tools/
|
||||
*.exe
|
||||
*.log
|
||||
test-results/
|
||||
playwright-report/
|
||||
.env
|
||||
!*.example
|
||||
@@ -0,0 +1,10 @@
|
||||
# Aeternalis
|
||||
|
||||
Read `planning/VISION.md` and `docs/ARCHITECTURE.md` before changing systems.
|
||||
Go owns gameplay; the browser sends intents only. One process owns one world.
|
||||
Never weaken permanent-death, daily-time-limit, or survivor-transfer invariants.
|
||||
Protocol bindings are generated from `schemas/protocol.json` with `npm run generate`.
|
||||
Game tuning lives in `server/content/balance.yaml`. Tests must cover lifecycle changes.
|
||||
Run `npm run check`, `npm run build`, and `go test ./...` in `server`.
|
||||
Production must require PostgreSQL and OIDC. Development auth is loopback-only.
|
||||
Do not increase the documented tested capacity without a representative load test.
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
FROM node:24-bookworm-slim AS client
|
||||
WORKDIR /src
|
||||
COPY package*.json ./
|
||||
RUN npm ci --no-fund
|
||||
COPY schemas ./schemas
|
||||
COPY tools/generate-protocol.mjs ./tools/generate-protocol.mjs
|
||||
COPY client ./client
|
||||
COPY server/internal/protocol ./server/internal/protocol
|
||||
RUN npm run test:contracts && npm run check && npm run build
|
||||
|
||||
FROM golang:1.27.1-bookworm AS server
|
||||
WORKDIR /src
|
||||
COPY server/go.mod server/go.sum ./
|
||||
RUN go mod download
|
||||
COPY server ./
|
||||
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /world ./cmd/world
|
||||
|
||||
FROM gcr.io/distroless/static-debian12:nonroot
|
||||
COPY --from=server /world /world
|
||||
COPY --from=client /src/client/dist /client
|
||||
ENV APP_ENV=production LISTEN_ADDR=0.0.0.0:8080 CLIENT_DIR=/client
|
||||
USER 65532:65532
|
||||
EXPOSE 8080
|
||||
ENTRYPOINT ["/world"]
|
||||
@@ -0,0 +1,113 @@
|
||||
# Aeternalis
|
||||
|
||||
A playable browser survival RPG foundation: an authoritative Go world server,
|
||||
Three.js terrain and GLB models, persistent one-life characters, and weekly worlds.
|
||||
|
||||
**Status: local prototype, not a production MMO or a verified 2,000-player server.**
|
||||
The review, architecture, deployment instructions, and remaining work are in
|
||||
`docs/ARCHITECTURE.md`, `docs/DEPLOYMENT.md`, and `docs/ROADMAP.md`.
|
||||
|
||||
## Run locally
|
||||
|
||||
Requirements: Node.js 24 and Go 1.26+ (tested with Go 1.27.1).
|
||||
On Windows without Go, `powershell -File tools/bootstrap-go.ps1` downloads a
|
||||
checksum-verified, project-local toolchain.
|
||||
|
||||
```sh
|
||||
npm ci
|
||||
npm run build
|
||||
node tools/dev-server.mjs
|
||||
```
|
||||
|
||||
Open **http://127.0.0.1:18080**. Guest authentication is available only in
|
||||
development, on an explicit loopback listen address. Production fails closed
|
||||
without PostgreSQL and an HTTPS OIDC configuration.
|
||||
|
||||
The delivered Windows build can also be started without installing Go:
|
||||
|
||||
```powershell
|
||||
powershell -File tools/start-local.ps1 -UseExisting
|
||||
```
|
||||
|
||||
That command starts a hidden background process and prints its PID. Stop your
|
||||
specific local process with `Stop-Process -Id <printed-pid>`. Local state lives in
|
||||
`.local/aeternalis.db`; restarting preserves characters, world age, and death.
|
||||
Deleting this development database is an explicit reset, not part of startup.
|
||||
|
||||
## Play
|
||||
|
||||
- Move with WASD/arrows, click the terrain, or use touch direction controls.
|
||||
- Click resources/enemies to approach and gather/attack. The toolbar also chooses
|
||||
the nearest suitable target. E gathers, Space attacks, I opens inventory.
|
||||
- Gather wood, ore, and herbs. Craft a spear or bandages in inventory.
|
||||
- The Harbinger appears after seven days. In loopback development, Display
|
||||
settings includes **Awaken Harbinger** for testing the event immediately.
|
||||
- During the boss event the safe world radius shrinks toward the center. The
|
||||
boundary deals damage; complete collapse kills remaining characters, including
|
||||
offline and daily-capped characters. Killing the boss freezes survivor eligibility.
|
||||
- Survivors sign into a different configured world with the same identity, then
|
||||
choose **Continue as ...**. An atomic passage redemption preserves identity,
|
||||
inventory, skills, kills, and daily play-time usage.
|
||||
|
||||
PvP, damage-priority corpse looting, body-part damage, full skills/stats,
|
||||
leaderboards, and an admin center are not implemented. Corpse looting currently
|
||||
has no priority lock because PvP is not enabled.
|
||||
|
||||
## Multiple local worlds
|
||||
|
||||
Start independent worlds against the same SQLite database. Every process needs a
|
||||
unique world ID and port. A completed world ID must never be recycled for a new
|
||||
season. Seeds and balance are stored when a world is first created.
|
||||
|
||||
```powershell
|
||||
$env:WORLD_DIRECTORY = '[{"id":"world-001","url":"http://127.0.0.1:18080"},{"id":"world-002","url":"http://127.0.0.1:18081"}]'
|
||||
powershell -File tools/start-local.ps1 -WorldId world-001 -Port 18080
|
||||
powershell -File tools/start-local.ps1 -WorldId world-002 -Port 18081 -Seed 829312
|
||||
```
|
||||
|
||||
Loopback cookies are shared across these two ports, so the same local guest can
|
||||
redeem a passage. Production worlds use OIDC issuer + subject for stable identity
|
||||
and separate secure host cookies. Never use dev identity for public servers.
|
||||
|
||||
## Validate
|
||||
|
||||
```sh
|
||||
npm run test:contracts
|
||||
npm run check
|
||||
npm run build
|
||||
# In server/:
|
||||
go test ./...
|
||||
go vet ./...
|
||||
# At the repository root:
|
||||
npx playwright install chromium
|
||||
npm run test:e2e
|
||||
helm lint deploy/chart
|
||||
helm template aeternalis deploy/chart
|
||||
```
|
||||
|
||||
When Go is local, use `.tools/go/bin/go.exe` from the root or
|
||||
`../.tools/go/bin/go.exe` from `server/`. Go tests use a temporary SQLite database.
|
||||
Set `TEST_DATABASE_URL` to an expendable PostgreSQL test database to run the same
|
||||
storage suite on PostgreSQL; CI provides one. Linux CI also runs `go test -race`.
|
||||
The browser suite starts and stops its own server on port 18089 with a fresh DB.
|
||||
On Windows, `PLAYWRIGHT_CHANNEL=msedge` can use installed Edge without downloading
|
||||
Chromium. Screenshots and traces are written to `test-results/`.
|
||||
|
||||
For client hot reload, run the server with `PUBLIC_URL=http://127.0.0.1:5175`,
|
||||
then run `npm run dev` and open port 5175. Origin checking intentionally rejects
|
||||
requests from other origins.
|
||||
|
||||
## Layout
|
||||
|
||||
| Path | Responsibility |
|
||||
|---|---|
|
||||
| `planning/VISION.md` | Original user vision; new boss rule in `IMPLEMENTATION-NOTES.md` |
|
||||
| `server/internal/game` | Terrain, authoritative simulation, lifecycle |
|
||||
| `server/internal/store` | World ownership, snapshots, sessions, atomic passages |
|
||||
| `server/internal/transport` | HTTP, OIDC, origin checks, WebSocket intent validation |
|
||||
| `schemas/protocol.json` | Generated Go/TypeScript wire contracts |
|
||||
| `server/content/balance.yaml` | Validated balance and recipe data |
|
||||
| `client/` | Full-screen browser game and mobile controls |
|
||||
| `tools/create-models.py` | Original temporary Blender models |
|
||||
| `deploy/chart/` | Five independent world deployments, services, TLS ingress |
|
||||
| `.gitea/workflows/build.yaml` | Tests, Harbor image publication, optional GitOps promotion |
|
||||
@@ -0,0 +1,7 @@
|
||||
# Temporary art
|
||||
|
||||
All six GLB models are original procedural placeholder models generated with
|
||||
Blender by `tools/create-models.py`. No third-party model or texture inputs.
|
||||
Rebuild with Blender 4.3+: `blender --background --python tools/create-models.py`.
|
||||
The final Harbinger scene is preserved in `harbinger.blend`.
|
||||
These are rigid meshes; production rigs, animations, LODs, and material art remain.
|
||||
Binary file not shown.
@@ -0,0 +1,5 @@
|
||||
# Browser client
|
||||
|
||||
Three.js presentation and intent input only. Do not decide damage, inventory,
|
||||
death, transfer eligibility, or play-time limits here. Consume generated contracts.
|
||||
Dispose chunk GPU resources on eviction. Keep the world full-screen on mobile.
|
||||
@@ -0,0 +1,35 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||
<meta name="theme-color" content="#172725" />
|
||||
<title>Aeternalis</title>
|
||||
<link rel="icon" href="data:," />
|
||||
</head>
|
||||
<body>
|
||||
<canvas id="world" aria-label="Aeternalis 3D world"></canvas>
|
||||
<div id="hud">
|
||||
<header class="topbar">
|
||||
<div class="brand"><span class="brand-mark">A</span><div><strong>AETERNALIS</strong><span id="world-name">The First Reach</span></div></div>
|
||||
<div class="compass"><span>W</span><span>NW</span><b>N</b><span>NE</span><span>E</span></div>
|
||||
<div class="connection"><i id="connection-dot"></i><span id="connection-status">Connecting</span><button id="settings-toggle" class="icon" title="Display settings" aria-label="Display settings"><i data-lucide="settings-2"></i></button></div>
|
||||
</header>
|
||||
<section id="season" class="season"><div><span id="phase-label">THE GATHERING</span><strong id="season-clock">7d 00h</strong></div><span id="season-detail">Until the Harbinger</span><div class="thin-track"><i id="season-progress"></i></div></section>
|
||||
<section id="boss-bar" class="boss-bar" hidden><button id="target-boss" title="Target Harbinger" aria-label="Target Harbinger"><i data-lucide="crosshair"></i> THE HARBINGER</button><div class="bar"><i id="boss-health"></i></div><small id="boss-count"></small></section>
|
||||
<aside id="settings" class="panel settings" hidden><div class="panel-title"><h2>Display</h2><button data-close="settings" class="icon" title="Close" aria-label="Close display settings"><i data-lucide="x"></i></button></div><label>Detail <select id="quality"><option value="high">High</option><option value="low">Low</option></select></label><label>Camera distance <input id="zoom" type="range" min="30" max="100" value="62" /></label><button id="dev-boss" hidden><i data-lucide="flame"></i> Awaken Harbinger</button><button id="logout"><i data-lucide="log-out"></i> Sign out</button></aside>
|
||||
<aside id="inventory" class="panel inventory" hidden><div class="panel-title"><h2>Inventory</h2><button data-close="inventory" class="icon" title="Close" aria-label="Close inventory"><i data-lucide="x"></i></button></div><div id="inventory-items" class="inventory-items"></div><h3>Crafting</h3><div id="recipes"></div><h3>Skills</h3><div id="skills" class="skills"></div></aside>
|
||||
<div id="target" class="target" hidden><span id="target-name"></span><span id="target-health"></span></div>
|
||||
<div id="notice" role="status" class="notice" hidden></div>
|
||||
<footer class="bottom" id="game-controls" hidden>
|
||||
<section class="vitals"><div><strong id="character-name">Traveler</strong><span id="health-number">100 / 100</span></div><div class="bar"><i id="health-fill"></i></div><div class="vital-detail"><span><i data-lucide="hourglass"></i><span id="play-time">2h left today</span></span><span id="kills">0 kills</span></div></section>
|
||||
<nav class="actions" aria-label="Actions"><button id="attack" title="Attack" aria-label="Attack"><i data-lucide="swords"></i></button><button id="gather" title="Gather" aria-label="Gather"><i data-lucide="pickaxe"></i></button><button id="heal" title="Use bandage" aria-label="Use bandage"><i data-lucide="heart-pulse"></i><small id="bandage-count">0</small></button><button id="keystone" title="Return with keystone" aria-label="Return with keystone"><i data-lucide="gem"></i></button><span></span><button id="inventory-toggle" title="Inventory and crafting" aria-label="Inventory and crafting"><i data-lucide="backpack"></i></button></nav>
|
||||
<section class="location"><canvas id="minimap" width="140" height="140" aria-label="World map"></canvas><span id="coordinates">0, 0</span><small id="chunk-count">9 chunks</small></section>
|
||||
</footer>
|
||||
<nav id="movement" class="movement" aria-label="Movement" hidden><button data-move="up" aria-label="Move north"><i data-lucide="chevron-up"></i></button><button data-move="left" aria-label="Move west"><i data-lucide="chevron-left"></i></button><button data-move="down" aria-label="Move south"><i data-lucide="chevron-down"></i></button><button data-move="right" aria-label="Move east"><i data-lucide="chevron-right"></i></button></nav>
|
||||
</div>
|
||||
<dialog id="arrival" open><div class="eyebrow">THE FIRST REACH</div><h1>Aeternalis</h1><p id="arrival-status">One life. A world on borrowed time.</p><form id="join-form"><label for="name">Character name</label><input id="name" name="name" autocomplete="nickname" minlength="2" maxlength="24" placeholder="Traveler" required value="Traveler" /><button id="join" type="submit">Enter world <i data-lucide="arrow-right"></i></button></form><a id="login" class="command" href="/auth/login" hidden>Sign in <i data-lucide="arrow-right"></i></a><div id="passages"></div><p id="arrival-error" class="error" role="alert"></p></dialog>
|
||||
<dialog id="ending"><div class="eyebrow" id="ending-eyebrow">JOURNEY ENDED</div><h1 id="ending-title">Your story remains.</h1><p id="ending-detail"></p><div id="destinations"></div><button id="reconnect" hidden>Reconnect <i data-lucide="refresh-cw"></i></button></dialog>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,79 @@
|
||||
// Code generated from schemas/protocol.json. DO NOT EDIT.
|
||||
export interface Protocol {
|
||||
intent: Intent;
|
||||
snapshot: Snapshot;
|
||||
}
|
||||
|
||||
export interface Intent {
|
||||
op: string;
|
||||
seq: number;
|
||||
target: string;
|
||||
x: number;
|
||||
z: number;
|
||||
}
|
||||
|
||||
export interface Snapshot {
|
||||
chunkKeys: string[];
|
||||
chunks: Chunk[];
|
||||
entities: Entity[];
|
||||
message: string;
|
||||
self: Character;
|
||||
tick: number;
|
||||
type: string;
|
||||
unavailableResources: string[];
|
||||
version: number;
|
||||
world: WorldInfo;
|
||||
}
|
||||
|
||||
export interface Chunk {
|
||||
biome: string;
|
||||
heights: number[];
|
||||
key: string;
|
||||
resolution: number;
|
||||
resources: Entity[];
|
||||
size: number;
|
||||
x: number;
|
||||
z: number;
|
||||
}
|
||||
|
||||
export interface Entity {
|
||||
hp: number;
|
||||
id: string;
|
||||
kind: string;
|
||||
maxHp: number;
|
||||
name: string;
|
||||
position: Vec3;
|
||||
state: string;
|
||||
}
|
||||
|
||||
export interface Vec3 {
|
||||
x: number;
|
||||
y: number;
|
||||
z: number;
|
||||
}
|
||||
|
||||
export interface Character {
|
||||
ack: number;
|
||||
entity: Entity;
|
||||
hasKeystone: boolean;
|
||||
inventory: { [key: string]: number };
|
||||
kills: number;
|
||||
playedSeconds: number;
|
||||
remainingSeconds: number;
|
||||
skills: { [key: string]: number };
|
||||
}
|
||||
|
||||
export interface WorldInfo {
|
||||
ageSeconds: number;
|
||||
bossHp: number;
|
||||
bossInSeconds: number;
|
||||
bossMaxHp: number;
|
||||
capacity: number;
|
||||
collapseInSeconds: number;
|
||||
id: string;
|
||||
online: number;
|
||||
phase: string;
|
||||
radius: number;
|
||||
safeRadius: number;
|
||||
seed: number;
|
||||
}
|
||||
@@ -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'; });
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,234 @@
|
||||
import * as T from 'three';
|
||||
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
|
||||
import type { Chunk, Entity, Snapshot, Vec3 } from './generated';
|
||||
|
||||
type Batch = { parts: T.InstancedMesh[]; entities: Entity[] };
|
||||
export class WorldView {
|
||||
readonly renderer: T.WebGLRenderer;
|
||||
readonly scene = new T.Scene();
|
||||
readonly camera = new T.OrthographicCamera(-60, 60, 40, -40, 0.1, 1400);
|
||||
readonly chunks = new Map<string, { data: Chunk; mesh: T.Mesh }>();
|
||||
readonly batches = new Map<string, Batch>();
|
||||
readonly focus = new T.Vector3(0, 0, 0);
|
||||
readonly position = new T.Vector3();
|
||||
readonly aim = new T.Vector3();
|
||||
readonly ring: T.Mesh;
|
||||
readonly selection: T.Mesh;
|
||||
readonly storm: T.Mesh;
|
||||
readonly sun: T.DirectionalLight;
|
||||
readonly models = new Map<string, T.Group>();
|
||||
player?: T.Group;
|
||||
snapshot?: Snapshot;
|
||||
selected?: Entity;
|
||||
distance = 46;
|
||||
frames = 0;
|
||||
moving = false;
|
||||
private highQuality = true;
|
||||
private initialized = false;
|
||||
private clock = new T.Clock();
|
||||
private matrix = new T.Matrix4();
|
||||
private dummy = new T.Object3D();
|
||||
private ray = new T.Raycaster();
|
||||
private onFrame: (dt: number) => void = () => {};
|
||||
constructor(readonly canvas: HTMLCanvasElement) {
|
||||
this.renderer = new T.WebGLRenderer({ canvas, antialias: true, powerPreference: 'high-performance' });
|
||||
this.renderer.setPixelRatio(Math.min(devicePixelRatio, 1.5));
|
||||
this.renderer.shadowMap.enabled = true;
|
||||
this.renderer.shadowMap.type = T.PCFSoftShadowMap;
|
||||
this.renderer.toneMapping = T.ACESFilmicToneMapping;
|
||||
this.renderer.toneMappingExposure = 1.0;
|
||||
this.scene.background = new T.Color('#b9ccd0');
|
||||
this.scene.fog = new T.Fog('#b9ccd0', 200, 650);
|
||||
this.scene.add(new T.HemisphereLight('#e9f4f2', '#475c3d', 1.35));
|
||||
this.sun = new T.DirectionalLight('#fff0d8', 2.3);
|
||||
this.sun.position.set(-60, 100, 45);
|
||||
this.sun.castShadow = true;
|
||||
this.sun.shadow.mapSize.set(2048, 2048);
|
||||
Object.assign(this.sun.shadow.camera, { left: -100, right: 100, top: 100, bottom: -100, near: 1, far: 300 });
|
||||
this.sun.shadow.bias = -0.0003;
|
||||
this.sun.shadow.normalBias = 0.15;
|
||||
this.scene.add(this.sun, this.sun.target);
|
||||
this.ring = new T.Mesh(new T.RingGeometry(1.35, 1.5, 48), new T.MeshBasicMaterial({ color: '#ebefc1', side: T.DoubleSide, depthWrite: false }));
|
||||
this.ring.rotation.x = -Math.PI / 2;
|
||||
this.scene.add(this.ring);
|
||||
this.selection = new T.Mesh(new T.RingGeometry(2.1, 2.24, 40), new T.MeshBasicMaterial({ color: '#f1d595', side: T.DoubleSide, depthWrite: false }));
|
||||
this.selection.rotation.x = -Math.PI / 2;
|
||||
this.selection.visible = false;
|
||||
this.scene.add(this.selection);
|
||||
this.storm = new T.Mesh(new T.CylinderGeometry(1, 1, 36, 160, 1, true), new T.MeshBasicMaterial({ color: '#ce4f65', transparent: true, opacity: 0.27, side: T.DoubleSide, depthWrite: false }));
|
||||
this.storm.visible = false;
|
||||
this.scene.add(this.storm);
|
||||
window.addEventListener('resize', () => this.resize());
|
||||
this.resize();
|
||||
}
|
||||
async load() {
|
||||
const loader = new GLTFLoader();
|
||||
await Promise.all(['tree', 'ore', 'herb', 'player', 'sentinel', 'boss'].map(async kind => {
|
||||
const gltf = await loader.loadAsync(`/models/${kind}.glb`);
|
||||
gltf.scene.updateMatrixWorld(true);
|
||||
this.models.set(kind, gltf.scene);
|
||||
if (kind === 'player') return;
|
||||
const batch: Batch = { parts: [], entities: [] };
|
||||
gltf.scene.traverse(child => {
|
||||
if (!(child instanceof T.Mesh)) return;
|
||||
const geometry = child.geometry.clone().applyMatrix4(child.matrixWorld);
|
||||
const mesh = new T.InstancedMesh(geometry, child.material, kind === 'boss' ? 1 : 2048);
|
||||
mesh.count = 0;
|
||||
mesh.instanceMatrix.setUsage(T.DynamicDrawUsage);
|
||||
mesh.castShadow = true;
|
||||
mesh.receiveShadow = true;
|
||||
mesh.userData.kind = kind;
|
||||
this.scene.add(mesh);
|
||||
batch.parts.push(mesh);
|
||||
});
|
||||
this.batches.set(kind, batch);
|
||||
}));
|
||||
this.player = this.models.get('player')!.clone(true);
|
||||
this.player.traverse(o => { if (o instanceof T.Mesh) { o.castShadow = true; o.receiveShadow = true; } });
|
||||
this.scene.add(this.player);
|
||||
// Players share rigid placeholder geometry until animated LOD assets are available.
|
||||
const template = this.models.get('player')!;
|
||||
const peers: Batch = { parts: [], entities: [] };
|
||||
template.traverse(child => {
|
||||
if (!(child instanceof T.Mesh)) return;
|
||||
const mesh = new T.InstancedMesh(child.geometry.clone().applyMatrix4(child.matrixWorld), child.material, 2048);
|
||||
mesh.count = 0; mesh.castShadow = true; mesh.userData.kind = 'player';
|
||||
this.scene.add(mesh); peers.parts.push(mesh);
|
||||
});
|
||||
this.batches.set('player', peers);
|
||||
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: [] });
|
||||
}
|
||||
resize() {
|
||||
const width = innerWidth, height = innerHeight, aspect = width / height;
|
||||
this.renderer.setSize(width, height, false);
|
||||
const size = this.distance * (width < 800 ? 0.7 : 0.65);
|
||||
this.camera.left = -size * aspect; this.camera.right = size * aspect;
|
||||
this.camera.top = size; this.camera.bottom = -size;
|
||||
this.camera.updateProjectionMatrix();
|
||||
}
|
||||
quality(high: boolean) {
|
||||
this.highQuality = high; this.renderer.shadowMap.enabled = high;
|
||||
this.renderer.setPixelRatio(Math.min(devicePixelRatio, high ? 1.5 : 1));
|
||||
this.resize();
|
||||
}
|
||||
addChunks(chunks: Chunk[], keys?: string[]) {
|
||||
const keep = new Set(keys ?? chunks.map(c => c.key));
|
||||
for (const [key, chunk] of this.chunks) {
|
||||
if (keep.has(key)) continue;
|
||||
this.scene.remove(chunk.mesh); chunk.mesh.geometry.dispose();
|
||||
(chunk.mesh.material as T.Material).dispose(); this.chunks.delete(key);
|
||||
}
|
||||
for (const chunk of chunks) {
|
||||
if (this.chunks.has(chunk.key)) continue;
|
||||
const n = chunk.resolution, step = chunk.size / n;
|
||||
const positions: number[] = [], colors: number[] = [], indices: number[] = [];
|
||||
const green = new T.Color('#425e3e'), light = new T.Color('#748058'), stone = new T.Color('#829092');
|
||||
for (let z = 0; z <= n; z++) for (let x = 0; x <= n; x++) {
|
||||
const wx = chunk.x * chunk.size + x * step, wz = chunk.z * chunk.size + z * step;
|
||||
const h = chunk.heights[z * (n + 1) + x];
|
||||
positions.push(wx, h, wz);
|
||||
const noise = (Math.sin(wx * 0.072) * Math.cos(wz * 0.052) + 1) / 2;
|
||||
const patch = Math.max(0, Math.sin(wx * 0.018 + wz * 0.012) * Math.cos(wz * 0.025) - 0.22);
|
||||
const color = green.clone().lerp(light, noise * 0.6).lerp(stone, Math.min(0.9, Math.max(0, (h - 5) / 10) + patch));
|
||||
if (Math.hypot(wx, wz) < 16) color.lerp(new T.Color('#97a07d'), 0.5);
|
||||
colors.push(color.r, color.g, color.b);
|
||||
}
|
||||
for (let z = 0; z < n; z++) for (let x = 0; x < n; x++) {
|
||||
const a = z * (n + 1) + x, b = a + 1, c = a + n + 1, d = c + 1;
|
||||
indices.push(a, c, b, b, c, d);
|
||||
}
|
||||
const geometry = new T.BufferGeometry();
|
||||
geometry.setAttribute('position', new T.Float32BufferAttribute(positions, 3));
|
||||
geometry.setAttribute('color', new T.Float32BufferAttribute(colors, 3));
|
||||
geometry.setIndex(indices); geometry.computeVertexNormals();
|
||||
const mesh = new T.Mesh(geometry, new T.MeshStandardMaterial({ vertexColors: true, roughness: 1, flatShading: true }));
|
||||
mesh.receiveShadow = true;
|
||||
this.scene.add(mesh); this.chunks.set(chunk.key, { data: chunk, mesh });
|
||||
}
|
||||
}
|
||||
height(x: number, z: number) {
|
||||
const chunk = this.chunks.get(`${Math.floor(x / 128)}:${Math.floor(z / 128)}`)?.data;
|
||||
if (!chunk) return this.position.y;
|
||||
const gx = (x - chunk.x * chunk.size) / chunk.size * chunk.resolution;
|
||||
const gz = (z - chunk.z * chunk.size) / chunk.size * chunk.resolution;
|
||||
const ix = Math.min(chunk.resolution - 1, Math.floor(gx)), iz = Math.min(chunk.resolution - 1, Math.floor(gz));
|
||||
const fx = gx - ix, fz = gz - iz, n = chunk.resolution + 1, i = iz * n + ix;
|
||||
const [a, b, c, d] = [chunk.heights[i], chunk.heights[i + 1], chunk.heights[i + n], chunk.heights[i + n + 1]];
|
||||
return fx + fz <= 1 ? a + (b - a) * fx + (c - a) * fz : d + (c - d) * (1 - fx) + (b - d) * (1 - fz);
|
||||
}
|
||||
updateEntities(entities: Entity[]) {
|
||||
for (const batch of this.batches.values()) batch.entities = [];
|
||||
for (const entity of entities) this.batches.get(entity.kind)?.entities.push(entity);
|
||||
for (const batch of this.batches.values()) {
|
||||
const count = Math.min(2048, batch.entities.length);
|
||||
for (let i = 0; i < count; i++) {
|
||||
const e = batch.entities[i];
|
||||
this.dummy.position.set(e.position.x, e.position.y, e.position.z);
|
||||
const variation = e.id.split('').reduce((n, c) => n + c.charCodeAt(0), 0);
|
||||
this.dummy.rotation.set(0, e.kind === 'tree' || e.kind === 'ore' ? variation : 0, 0);
|
||||
const scale = e.kind === 'tree' ? 0.85 + (variation % 6) * 0.07 : 1;
|
||||
this.dummy.scale.setScalar(scale); this.dummy.updateMatrix();
|
||||
for (const mesh of batch.parts) mesh.setMatrixAt(i, this.dummy.matrix);
|
||||
}
|
||||
for (const mesh of batch.parts) { mesh.count = count; mesh.instanceMatrix.needsUpdate = true; mesh.computeBoundingSphere(); }
|
||||
}
|
||||
}
|
||||
update(snapshot: Snapshot) {
|
||||
this.snapshot = snapshot;
|
||||
this.addChunks(snapshot.chunks, snapshot.chunkKeys);
|
||||
const unavailable = new Set(snapshot.unavailableResources);
|
||||
const resources = [...this.chunks.values()].flatMap(c => c.data.resources).filter(r => !unavailable.has(r.id));
|
||||
snapshot.entities = [...snapshot.entities, ...resources];
|
||||
this.updateEntities(snapshot.entities);
|
||||
const p = snapshot.self.entity.position;
|
||||
this.aim.set(p.x, p.y, p.z);
|
||||
if (!this.initialized || this.position.distanceTo(this.aim) > 20) { this.position.copy(this.aim); this.focus.copy(this.aim); this.initialized = true; }
|
||||
this.storm.visible = snapshot.world.phase === 'cataclysm';
|
||||
this.storm.scale.set(snapshot.world.safeRadius, 1, snapshot.world.safeRadius);
|
||||
const danger = snapshot.world.phase === 'cataclysm';
|
||||
(this.scene.background as T.Color).set(danger ? '#c19f9e' : '#b9ccd0');
|
||||
(this.scene.fog as T.Fog).color.copy(this.scene.background as T.Color);
|
||||
if (this.selected) this.selected = snapshot.entities.find(e => e.id === this.selected!.id);
|
||||
}
|
||||
pick(clientX: number, clientY: number): { entity?: Entity; point?: T.Vector3 } {
|
||||
const rect = this.canvas.getBoundingClientRect();
|
||||
this.ray.setFromCamera(new T.Vector2((clientX - rect.left) / rect.width * 2 - 1, -(clientY - rect.top) / rect.height * 2 + 1), this.camera);
|
||||
const objects: T.Object3D[] = [];
|
||||
for (const batch of this.batches.values()) objects.push(...batch.parts);
|
||||
const hit = this.ray.intersectObjects(objects, false)[0];
|
||||
if (hit?.instanceId !== undefined) {
|
||||
const batch = this.batches.get(hit.object.userData.kind);
|
||||
return { entity: batch?.entities[hit.instanceId] };
|
||||
}
|
||||
return { point: this.ray.intersectObjects([...this.chunks.values()].map(c => c.mesh), false)[0]?.point };
|
||||
}
|
||||
start(onFrame: (dt: number) => void) {
|
||||
this.onFrame = onFrame;
|
||||
this.renderer.setAnimationLoop(() => {
|
||||
const dt = Math.min(this.clock.getDelta(), 0.05);
|
||||
this.onFrame(dt);
|
||||
// Presentation interpolation follows server positions; it never changes authoritative movement.
|
||||
this.position.lerp(this.aim, 1 - Math.exp(-14 * dt));
|
||||
this.focus.lerp(this.position, 1 - Math.exp(-8 * dt));
|
||||
this.camera.position.copy(this.focus).add(new T.Vector3(0, 85, 80));
|
||||
this.camera.lookAt(this.focus);
|
||||
if (this.player) {
|
||||
this.player.position.copy(this.position);
|
||||
const direction = this.aim.clone().sub(this.position);
|
||||
if (direction.lengthSq() > 0.002) this.player.rotation.y = Math.atan2(-direction.x, -direction.z);
|
||||
this.player.position.y += this.moving ? Math.sin(this.clock.elapsedTime * 15) * 0.09 : 0;
|
||||
}
|
||||
this.ring.position.copy(this.position); this.ring.position.y += 0.08;
|
||||
this.selection.visible = !!this.selected;
|
||||
if (this.selected) this.selection.position.set(this.selected.position.x, this.selected.position.y + 0.1, this.selected.position.z);
|
||||
if (this.highQuality) {
|
||||
this.sun.position.copy(this.focus).add(new T.Vector3(-60, 100, 45));
|
||||
this.sun.target.position.copy(this.focus);
|
||||
}
|
||||
this.renderer.render(this.scene, this.camera); this.frames++;
|
||||
});
|
||||
}
|
||||
diagnostics() { return { frames: this.frames, chunks: this.chunks.size, drawCalls: this.renderer.info.render.calls, triangles: this.renderer.info.render.triangles, models: this.models.size, position: this.position.toArray() }; }
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022", "module": "ESNext", "moduleResolution": "Bundler",
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"], "strict": true,
|
||||
"noEmit": true, "skipLibCheck": true, "allowImportingTsExtensions": true,
|
||||
"types": ["vite/client"]
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { defineConfig } from 'vite';
|
||||
|
||||
export default defineConfig({
|
||||
root: 'client',
|
||||
build: { outDir: 'dist', target: 'es2022', chunkSizeWarningLimit: 650 },
|
||||
server: {
|
||||
port: 5175, strictPort: true,
|
||||
proxy: { '/api': 'http://127.0.0.1:18080', '/auth': 'http://127.0.0.1:18080', '/ws': { target: 'ws://127.0.0.1:18080', ws: true } },
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
apiVersion: argoproj.io/v1alpha1
|
||||
kind: Application
|
||||
metadata:
|
||||
name: aeternalis
|
||||
namespace: argocd
|
||||
spec:
|
||||
project: default
|
||||
sources:
|
||||
- repoURL: https://gitea.example.invalid/games/aeternalis.git
|
||||
targetRevision: master
|
||||
path: deploy/chart
|
||||
helm:
|
||||
valueFiles: [$values/apps/aeternalis/values.yaml]
|
||||
- repoURL: https://gitea.example.invalid/infra/gitops.git
|
||||
targetRevision: main
|
||||
ref: values
|
||||
destination:
|
||||
server: https://kubernetes.default.svc
|
||||
namespace: aeternalis
|
||||
syncPolicy:
|
||||
automated: { prune: false, selfHeal: true }
|
||||
syncOptions: [CreateNamespace=true]
|
||||
@@ -0,0 +1,6 @@
|
||||
apiVersion: v2
|
||||
name: aeternalis
|
||||
description: Independent authoritative Aeternalis worlds
|
||||
type: application
|
||||
version: 0.1.0
|
||||
appVersion: 0.1.0
|
||||
@@ -0,0 +1,28 @@
|
||||
{{- if .Values.networkPolicy.enabled }}
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: NetworkPolicy
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-worlds
|
||||
spec:
|
||||
podSelector:
|
||||
matchLabels: { app.kubernetes.io/name: aeternalis, app.kubernetes.io/instance: {{ .Release.Name | quote }} }
|
||||
policyTypes: [Ingress, Egress]
|
||||
ingress:
|
||||
- from:
|
||||
- namespaceSelector:
|
||||
matchLabels: { kubernetes.io/metadata.name: {{ .Values.networkPolicy.ingressNamespace | quote }} }
|
||||
ports: [{ protocol: TCP, port: 8080 }]
|
||||
egress:
|
||||
- to:
|
||||
- namespaceSelector:
|
||||
matchLabels: { kubernetes.io/metadata.name: {{ .Values.networkPolicy.dnsNamespace | quote }} }
|
||||
ports: [{ protocol: UDP, port: 53 }, { protocol: TCP, port: 53 }]
|
||||
{{- range .Values.networkPolicy.databaseCIDRs }}
|
||||
- to: [{ ipBlock: { cidr: {{ . | quote }} } }]
|
||||
ports: [{ protocol: TCP, port: 5432 }]
|
||||
{{- end }}
|
||||
{{- range .Values.networkPolicy.identityCIDRs }}
|
||||
- to: [{ ipBlock: { cidr: {{ . | quote }} } }]
|
||||
ports: [{ protocol: TCP, port: 443 }]
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
@@ -0,0 +1,83 @@
|
||||
{{- $root := . -}}
|
||||
{{- $directory := list -}}
|
||||
{{- range .Values.worlds -}}
|
||||
{{- $directory = append $directory (dict "id" .id "url" (printf "https://%s" .host)) -}}
|
||||
{{- end -}}
|
||||
{{- range .Values.worlds }}
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: {{ $root.Release.Name }}-{{ .id }}
|
||||
labels: { app.kubernetes.io/name: aeternalis, app.kubernetes.io/instance: {{ $root.Release.Name | quote }}, aeternalis.world: {{ .id | quote }} }
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: { type: Recreate }
|
||||
revisionHistoryLimit: 3
|
||||
selector:
|
||||
matchLabels: { app.kubernetes.io/instance: {{ $root.Release.Name | quote }}, aeternalis.world: {{ .id | quote }} }
|
||||
template:
|
||||
metadata:
|
||||
labels: { app.kubernetes.io/name: aeternalis, app.kubernetes.io/instance: {{ $root.Release.Name | quote }}, aeternalis.world: {{ .id | quote }} }
|
||||
spec:
|
||||
automountServiceAccountToken: false
|
||||
terminationGracePeriodSeconds: 30
|
||||
imagePullSecrets: {{ $root.Values.imagePullSecrets | toJson }}
|
||||
securityContext:
|
||||
runAsNonRoot: true
|
||||
runAsUser: 65532
|
||||
runAsGroup: 65532
|
||||
seccompProfile: { type: RuntimeDefault }
|
||||
containers:
|
||||
- name: world
|
||||
image: {{ if $root.Values.image.digest }}{{ printf "%s@%s" $root.Values.image.repository $root.Values.image.digest | quote }}{{ else }}{{ printf "%s:%s" $root.Values.image.repository $root.Values.image.tag | quote }}{{ end }}
|
||||
imagePullPolicy: IfNotPresent
|
||||
ports: [{ name: http, containerPort: 8080 }]
|
||||
securityContext:
|
||||
readOnlyRootFilesystem: true
|
||||
allowPrivilegeEscalation: false
|
||||
capabilities: { drop: [ALL] }
|
||||
env:
|
||||
- { name: APP_ENV, value: production }
|
||||
- { name: LISTEN_ADDR, value: "0.0.0.0:8080" }
|
||||
- { name: WORLD_ID, value: {{ .id | quote }} }
|
||||
- { name: WORLD_SEED, value: {{ .seed | quote }} }
|
||||
- { name: PUBLIC_URL, value: {{ printf "https://%s" .host | quote }} }
|
||||
- { name: WORLD_DIRECTORY, value: {{ $directory | toJson | quote }} }
|
||||
envFrom:
|
||||
- secretRef: { name: {{ $root.Values.existingSecret | quote }} }
|
||||
resources: {{ $root.Values.resources | toJson }}
|
||||
startupProbe: { httpGet: { path: /readyz, port: http }, periodSeconds: 5, failureThreshold: 24 }
|
||||
readinessProbe: { httpGet: { path: /readyz, port: http }, periodSeconds: 3, failureThreshold: 2 }
|
||||
livenessProbe: { httpGet: { path: /healthz, port: http }, periodSeconds: 10, failureThreshold: 3 }
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: {{ $root.Release.Name }}-{{ .id }}
|
||||
spec:
|
||||
selector: { app.kubernetes.io/instance: {{ $root.Release.Name | quote }}, aeternalis.world: {{ .id | quote }} }
|
||||
ports: [{ name: http, port: 8080, targetPort: http }]
|
||||
---
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: Ingress
|
||||
metadata:
|
||||
name: {{ $root.Release.Name }}-{{ .id }}
|
||||
annotations:
|
||||
nginx.ingress.kubernetes.io/proxy-read-timeout: "3600"
|
||||
nginx.ingress.kubernetes.io/proxy-send-timeout: "3600"
|
||||
nginx.ingress.kubernetes.io/proxy-body-size: "8k"
|
||||
nginx.ingress.kubernetes.io/limit-rps: "10"
|
||||
nginx.ingress.kubernetes.io/ssl-redirect: "true"
|
||||
spec:
|
||||
ingressClassName: {{ $root.Values.ingress.className | quote }}
|
||||
tls: [{ hosts: [{{ .host | quote }}], secretName: {{ $root.Values.ingress.tlsSecret | quote }} }]
|
||||
rules:
|
||||
- host: {{ .host | quote }}
|
||||
http:
|
||||
paths:
|
||||
- path: /
|
||||
pathType: Prefix
|
||||
backend:
|
||||
service: { name: {{ $root.Release.Name }}-{{ .id }}, port: { name: http } }
|
||||
{{- end }}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"type": "object",
|
||||
"required": ["worlds", "existingSecret", "image"],
|
||||
"properties": {
|
||||
"worlds": {"type": "array", "minItems": 1, "items": {"type": "object", "required": ["id", "seed", "host"], "properties": {"id": {"type": "string", "pattern": "^[a-z][a-z0-9-]{0,30}$"}, "seed": {"type": "string", "pattern": "^[0-9]{1,15}$"}, "host": {"type": "string", "minLength": 1}}}},
|
||||
"existingSecret": {"type": "string", "minLength": 1},
|
||||
"image": {"type": "object", "required": ["repository", "tag", "digest"], "properties": {"repository": {"type": "string", "minLength": 1}, "tag": {"type": "string", "minLength": 1}, "digest": {"type": "string", "pattern": "^(sha256:[a-f0-9]{64})?$"}}}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
image:
|
||||
repository: harbor.example.invalid/games/aeternalis
|
||||
tag: bootstrap
|
||||
digest: ""
|
||||
imagePullSecrets:
|
||||
- name: harbor-pull
|
||||
existingSecret: aeternalis-runtime
|
||||
ingress:
|
||||
className: nginx
|
||||
tlsSecret: aeternalis-tls
|
||||
worlds:
|
||||
- id: world-001
|
||||
seed: "734291"
|
||||
host: world-001.aeternalis.example.invalid
|
||||
- id: world-002
|
||||
seed: "829312"
|
||||
host: world-002.aeternalis.example.invalid
|
||||
- id: world-003
|
||||
seed: "942731"
|
||||
host: world-003.aeternalis.example.invalid
|
||||
- id: world-004
|
||||
seed: "1037412"
|
||||
host: world-004.aeternalis.example.invalid
|
||||
- id: world-005
|
||||
seed: "1123491"
|
||||
host: world-005.aeternalis.example.invalid
|
||||
resources:
|
||||
requests: { cpu: "500m", memory: "256Mi" }
|
||||
limits: { cpu: "2", memory: "1Gi" }
|
||||
networkPolicy:
|
||||
enabled: true
|
||||
ingressNamespace: ingress-nginx
|
||||
# Explicitly set actual database and OIDC provider IP ranges before deployment.
|
||||
databaseCIDRs: []
|
||||
identityCIDRs: []
|
||||
# Kube-dns defaults; adjust for clusters using NodeLocal DNSCache.
|
||||
dnsNamespace: kube-system
|
||||
@@ -0,0 +1,116 @@
|
||||
# Architecture and vision review
|
||||
|
||||
Reviewed 2026-09-05 against `C:/Dev/aeternalis/planning/VISION.md` and the earlier
|
||||
RPGTheory design notes. The new weekly boss rule is authoritative over the older
|
||||
uncertain session-ending description.
|
||||
|
||||
## Assessment
|
||||
|
||||
The vision has a coherent distinguishing loop: players invest in a single life,
|
||||
cooperate against a closing deadline, and earn passage to a new world. The browser
|
||||
is a reasonable first client. Chunk subscriptions and GPU instancing address some
|
||||
client costs, but do not prove that thousands of players can gather around one boss.
|
||||
Changing to a native client would not remove simulation, bandwidth, or persistence
|
||||
bottlenecks. Measure before changing platforms.
|
||||
|
||||
The highest-risk requirements are:
|
||||
|
||||
1. **Death and transfers must remain correct after retries, crashes, and redeploys.**
|
||||
A duplicated survivor or resurrected character undermines the one-life premise.
|
||||
2. **One world is explicitly one server instance.** Kubernetes adds world capacity
|
||||
by adding independent owners; replicating the same world deployment does not
|
||||
share its simulation. A crowded final boss bypasses the benefit of small AOIs.
|
||||
3. **Nine 128-unit chunks are a subscription rule, not a complete scaling plan.**
|
||||
Entity density, bytes/update, allocation rate, AI work, and client draw cost need
|
||||
separate budgets and load measurements.
|
||||
4. **Two hours per day and a destructive weekly event interact.** The prototype
|
||||
protects a capped character from enemies in a central safe zone, but does not
|
||||
exempt it from final world collapse or grant passage before the boss dies.
|
||||
Offline-world survival is an explicit provisional rule requiring playtesting.
|
||||
5. **Five worlds opened together also reach their deadlines together.** Operators
|
||||
need to open fresh destinations before survivors transfer. There is no automatic
|
||||
Kubernetes world allocator in this slice.
|
||||
|
||||
## Implemented boundaries
|
||||
|
||||
One Go process owns one world, with a serial simulation protected by one lock.
|
||||
Clients submit bounded intents. The server determines speed, terrain height,
|
||||
range, cooldown, inventory changes, damage, death, play-time, and passage eligibility.
|
||||
Movement is interpolated on the client; full prediction/reconciliation is deferred.
|
||||
No rigid-body physics is claimed: this is heightfield movement in open terrain.
|
||||
|
||||
The simulation ticks at 20 Hz; snapshots are sent at 5 Hz. Coordinates use X/Z
|
||||
chunk indices and Y height. Terrain has a vertical coordinate but is a 2.5D
|
||||
heightfield, **not** a volumetric 128x128x128 voxel world. Overhangs, caves, stacked
|
||||
chunks, and fully destructible voxel terrain require another generator/version.
|
||||
Destruction currently means a shrinking hazardous boundary, not terrain deformation.
|
||||
|
||||
OpenSimplex supplies seeded noise. A versioned generator produces chunk meshes and
|
||||
resources only as needed. Mesh height and server collision height share a triangle
|
||||
split. A connection subscribes to current chunk + eight neighbors. Unchanged
|
||||
terrain and static resource transforms are not resent; resource availability IDs
|
||||
and dynamic entities are filtered by this area. GPU terrain is disposed
|
||||
on eviction. Repeated GLB meshes use instancing; camera frustum culling is separate
|
||||
from network interest. The server retains mutation deltas across chunk eviction.
|
||||
|
||||
The finite circular world, 48-unit spawn separation, 100-character capacity,
|
||||
combat numbers, terrain details, mob scaling, and respawn periods are provisional
|
||||
defaults. They are not newly confirmed design decisions. Balance is validated and
|
||||
persisted with the world; editing YAML affects newly created world IDs only.
|
||||
|
||||
## Durability and ownership
|
||||
|
||||
Development uses SQLite WAL. Production requires PostgreSQL with TLS certificate
|
||||
verification. Both use the same storage tests and transaction behavior.
|
||||
|
||||
The `worlds` row has an expiring owner token and a monotonically increasing
|
||||
revision. Every save atomically checks owner, lease expiry using database time,
|
||||
and expected revision. A competing process cannot acquire an unexpired lease,
|
||||
and a previous owner cannot write after replacement. Lease renewal accompanies
|
||||
regular saves; a stopped/crashed process releases or expires after 30 seconds.
|
||||
|
||||
World snapshots are saved every second and on material gameplay changes before
|
||||
the next client snapshot. Victory creates survivor passage records in that same
|
||||
transaction. A destination saves its imported character and marks the passage
|
||||
redeemed in one transaction. Later victories can issue a new passage for the same
|
||||
character ID; old source servers cannot overwrite it. Account identity is checked
|
||||
at redemption, and the destination rejects duplicate accounts/characters.
|
||||
|
||||
On storage failure the process freezes and fails readiness/liveness, closes its
|
||||
sockets, and must restart/reload durable state. This avoids continuing after an
|
||||
ambiguous commit. Default shutdown allows 10 seconds to save and release ownership.
|
||||
Treat backup/restore as an explicit administrative operation: restoring an old
|
||||
database can reverse deaths and transfers, so production needs a restoration policy.
|
||||
|
||||
**Prototype durability limit:** an abrupt crash can roll back up to one second of
|
||||
position and daily play usage. Gameplay mutations are acknowledged after a save;
|
||||
unacknowledged inputs can disappear. Whole-world JSON checkpoints occur under the
|
||||
simulation lock and are deliberately a simple first implementation. Before public
|
||||
permadeath or large worlds, replace this with a durable event log, asynchronous
|
||||
checkpoints, versioned migrations, and crash/latency fault injection.
|
||||
|
||||
## Security scope
|
||||
|
||||
- Production login: OIDC verification (issuer, audience, signature, expiry), PKCE,
|
||||
state and nonce binding, and opaque server-side sessions.
|
||||
- Secure, HttpOnly, SameSite cookies. No client-controlled identity or progression.
|
||||
- Explicit same-origin checks on mutations and WebSockets; no permissive CORS.
|
||||
- Strict JSON parsing, small input limits, sequence checks, HTTP/WS rate limits,
|
||||
action validation, movement timeout, and bounded slow-consumer queues.
|
||||
- CSP, no framing, MIME sniff protection, HSTS in production, and no token logging.
|
||||
- A non-root, read-only runtime container with all capabilities dropped, no service
|
||||
account token, health probes, TLS ingress, and limited network egress.
|
||||
|
||||
The application limiter uses the real TCP peer address, **not untrusted forwarded
|
||||
headers**. Behind ingress this may group many users into one bucket. Configure
|
||||
trusted-proxy-aware rate limiting before public load; the chart's ingress rate
|
||||
limit is an additional layer. OIDC provider callbacks and JWKS refresh, TLS, network
|
||||
policies, actual ingress behavior, backups, secret rotation, and dependency scanning
|
||||
must be tested on the real cluster. This code is not a completed security audit.
|
||||
|
||||
## Source references
|
||||
|
||||
- [Three.js instanced rendering](https://threejs.org/docs/pages/InstancedMesh.html)
|
||||
- [Three.js object-count optimization](https://threejs.org/manual/en/optimize-lots-of-objects.html)
|
||||
- [Kubernetes security contexts](https://kubernetes.io/docs/tasks/configure-pod-container/security-context/)
|
||||
- [Gitea Actions runner setup](https://docs.gitea.com/usage/actions/quickstart/)
|
||||
@@ -0,0 +1,106 @@
|
||||
# Kubernetes and Gitea deployment
|
||||
|
||||
The chart and workflow are provided for configuration and cluster validation.
|
||||
No image has been published, no GitOps repository has been modified, and no
|
||||
cluster resources have been applied by this implementation session.
|
||||
|
||||
## Runtime prerequisites
|
||||
|
||||
- PostgreSQL database shared by all worlds, with verified TLS. The runtime needs
|
||||
table/index creation for initial bootstrap, then reads and writes in its own
|
||||
database. A separate migration job and reduced DDL privileges are follow-up work.
|
||||
- An OIDC provider/client with exact callbacks for each world:
|
||||
`https://<world-host>/auth/callback`. Use one client accepting these registered
|
||||
callbacks or extend the chart to use per-world credentials. Never use wildcards.
|
||||
- Harbor registry project and a pull-only robot credential for Kubernetes.
|
||||
- An ingress controller that supports WebSocket upgrades and preserves Host,
|
||||
certificates covering all world hosts, working DNS, and NetworkPolicy enforcement.
|
||||
- ArgoCD with read access to the application and GitOps repositories.
|
||||
|
||||
Create the runtime secret through your existing secret manager (e.g. External
|
||||
Secrets or sealed secrets). Do not put actual secret values into this repository.
|
||||
The named secret `aeternalis-runtime` must contain:
|
||||
|
||||
| Key | Value |
|
||||
|---|---|
|
||||
| `DATABASE_URL` | `postgres://user:password@db.example/db?sslmode=verify-full` |
|
||||
| `OIDC_ISSUER` | Exact HTTPS issuer URL |
|
||||
| `OIDC_CLIENT_ID` | Registered client ID |
|
||||
| `OIDC_CLIENT_SECRET` | Client secret, if required by your provider |
|
||||
|
||||
Certificates from the image's system CA bundle are trusted. Mount a custom CA and
|
||||
configure the PostgreSQL/HTTPS clients if your infrastructure uses a private CA;
|
||||
that mounting is site-specific and not included in the sample chart.
|
||||
|
||||
Configure `deploy/chart/values.yaml` (prefer an external GitOps values file):
|
||||
|
||||
1. Set image repository, pull secret, runtime secret, TLS secret, and actual hosts.
|
||||
2. Set `networkPolicy.databaseCIDRs` and `identityCIDRs` to the actual permitted
|
||||
destinations. Empty lists deny these connections, so the server will not start
|
||||
until the allowlists match. Adjust DNS rules for NodeLocal DNSCache if used.
|
||||
3. Adjust requests/limits after measuring on cluster hardware. Defaults are initial
|
||||
allocations, not a capacity guarantee.
|
||||
4. Render and inspect with `helm lint` and `helm template`; validate against the
|
||||
target cluster version using your normal dry-run pipeline.
|
||||
|
||||
## Gitea setup
|
||||
|
||||
Enable Actions in the repository. Use a runner with the `ubuntu-latest` label,
|
||||
Node/Go setup support, service-container networking, and Docker build capability.
|
||||
The publication runner should be trusted; do not expose a privileged Docker socket
|
||||
to untrusted pull-request jobs. The verify job has no deployment credentials.
|
||||
Action references use upstream version tags; mirror/pin these to reviewed commits
|
||||
under your organization's supply-chain policy before production use.
|
||||
|
||||
Set repository variables:
|
||||
|
||||
| Variable | Example |
|
||||
|---|---|
|
||||
| `HARBOR_HOST` | `harbor.your-domain` (no scheme) |
|
||||
| `HARBOR_PROJECT` | `games` |
|
||||
| `GITOPS_REPOSITORY` | `https://gitea.your-domain/infra/gitops.git` |
|
||||
| `GITOPS_BRANCH` | `main` |
|
||||
| `GITOPS_VALUES_FILE` | `apps/aeternalis/values.yaml` |
|
||||
|
||||
Set repository secrets `HARBOR_USERNAME`, `HARBOR_PASSWORD`, `GITOPS_USERNAME`,
|
||||
and `GITOPS_TOKEN`. Use a Harbor project-scoped push robot and a token restricted
|
||||
to the intended GitOps repository. An empty `GITOPS_REPOSITORY` skips promotion.
|
||||
Harbor publication still requires its own variables/secrets.
|
||||
|
||||
On a push to `master` or `main`, CI verifies generated contracts, TypeScript,
|
||||
production client build, Go tests with the race detector, real PostgreSQL storage
|
||||
integration, browser tests, Go vet, and Helm rendering. It builds/publishes an image
|
||||
tagged with the commit SHA, then updates the GitOps values to the image's immutable
|
||||
digest. ArgoCD reconciles that change. No kubeconfig is handed to CI.
|
||||
|
||||
Copy and configure `deploy/argocd-application.example.yaml`. It uses ArgoCD's
|
||||
multiple-source Application support: chart from the app repository, values from
|
||||
the GitOps repository. Pruning is disabled in the example to avoid silently
|
||||
deleting worlds when editing the list. Monitor promotion failures; concurrent
|
||||
GitOps commits are rejected by a normal non-force push and must be retried.
|
||||
|
||||
## Add worlds and retire seasons
|
||||
|
||||
Each world gets a distinct Deployment, Service, hostname, ID, seed, and database
|
||||
row. `replicas: 1` and `Recreate` are intentional. An expiring DB lease also fences
|
||||
duplicate processes. Increasing replicas does not increase one world's capacity.
|
||||
|
||||
To add capacity, append a world entry with a never-used ID and fresh seed, register
|
||||
its OIDC callback and DNS/TLS, and sync ArgoCD. Open destination worlds before the
|
||||
current cohort wins; five worlds launched together have the same deadline.
|
||||
The world directory is supplied to every client, and passages are visible to the
|
||||
same account after signing into a destination.
|
||||
|
||||
Retire a finished world's workload only after confirming its persisted outcome and
|
||||
passages. Keep its database row and passage history. Never reuse its ID: restarted
|
||||
IDs restore their old state. Rolling the code back does not roll the database back.
|
||||
Balance/seed changes do not mutate a running saved world's rules.
|
||||
|
||||
## Before public access
|
||||
|
||||
Run a real OIDC login and cross-host survivor transfer, restart/kill a pod during
|
||||
combat and victory, simulate database failure, validate NetworkPolicy and TLS,
|
||||
and test peak boss crowding. Add observability and alerting, versioned migrations,
|
||||
durable event recording, abuse controls, account-level cap policy if chosen, and
|
||||
an operational backup/restore procedure. The current prototype is suitable for
|
||||
controlled development playtests after deployment validation.
|
||||
@@ -0,0 +1,64 @@
|
||||
# Implementation status and next work
|
||||
|
||||
## Playable in this slice
|
||||
|
||||
- Browser 3D scene, original Blender placeholder GLBs, instanced resource meshes,
|
||||
desktop/touch controls, target selection, inventory, recipes, skills display.
|
||||
- Seeded streamed heightfield chunks, negative coordinates, seamless borders,
|
||||
server-authoritative terrain height, 3x3 subscriptions, client chunk eviction.
|
||||
- Persistent character identity and starting kit; gathering, spear/bandage crafting,
|
||||
XP counters, basic melee, healing, roaming/respawning zone-confined enemies.
|
||||
- Seven-day boss deadline, development trigger, shrinking danger boundary,
|
||||
permanent death, corpses, frozen victory, account-bound atomic survivor passages.
|
||||
- Two-hour daily character cap, safe relocation, HP floor, logout, next-day keystone.
|
||||
- SQLite local persistence, PostgreSQL production adapter, exclusive world leases,
|
||||
strict intents, OIDC, secure cookies, origin checks, bounded sockets/rate limits.
|
||||
- Gitea verification/publication/GitOps workflow, Dockerfile, five-world Helm chart,
|
||||
TLS ingress, probes, pod security, network policy, ArgoCD example.
|
||||
|
||||
## Deliberate gaps
|
||||
|
||||
- **2,000 players in one world:** unverified. Default is 100 admitted characters per
|
||||
world. Current snapshot construction and enemy searches scan world collections;
|
||||
whole-world persistence can stall ticks. Do not raise capacity based on unit tests.
|
||||
- **Procedural volume/destruction:** current terrain is a heightfield. The storm
|
||||
destroys playable space; it does not erode individual terrain cells or structures.
|
||||
- **Permadeath durability:** last second of movement/time can roll back on abrupt
|
||||
crash; public permadeath needs event persistence and failure injection.
|
||||
- **PvP and corpse priority:** disabled/unimplemented. Corpse items can currently be
|
||||
looted by nearby living players. The highest-damage-attacker lock and close-to-
|
||||
release rule must ship together with PvP, not be inferred from PvE behavior.
|
||||
- **Stats/body parts/dynamic skills:** XP counters exist, not the complete formula,
|
||||
emergent-skill, multi-limb damage, or level/stat allocation systems.
|
||||
- **Progression:** gathering/crafting content is intentionally small. Fishing,
|
||||
alchemy stations, smithing, buildable structures, loot tables, and hunger are absent.
|
||||
- **Operations:** no admin center, chat/moderation, leaderboards, account management,
|
||||
automatic world provisioning, observability dashboard, or migration framework.
|
||||
- **Art:** rigid placeholders; no rigged locomotion, attack telegraphs, audio, or LODs.
|
||||
- **Networking:** interpolated movement without prediction; full entity snapshots
|
||||
at 5 Hz, not packed/delta entity replication; no proven large-crowd behavior.
|
||||
|
||||
## Next milestones
|
||||
|
||||
1. Playtest the small loop and decide offline/capped survival during the final boss,
|
||||
return timing, boss telegraphs, and whether peers cooperate or can attack each other.
|
||||
2. Add a durable event log, versioned database migrations, transfer race/failure
|
||||
stress tests, and restart recovery. Prove PostgreSQL and OIDC on the real cluster.
|
||||
3. Add chunk-indexed entity lookups, network byte/tick/allocation telemetry, and
|
||||
incremental entity replication. Load-test spread populations and a concentrated
|
||||
boss arena at 50, 100, 250, 500, and then higher only as measurements allow.
|
||||
4. Build proper enemy telegraphs, animation/LOD pipeline, collision/navigation, and
|
||||
client prediction. Compare browser frame time on actual target hardware.
|
||||
5. Implement the full progression and PvP/loot rules with focused tests. Add admin
|
||||
inspection, leaderboard persistence, account controls, and moderation.
|
||||
6. Automate lifecycle-aware world provisioning once transfers and retirement are
|
||||
proven operationally. Keep world creation out of untrusted client requests.
|
||||
|
||||
## Open design questions retained
|
||||
|
||||
The original unresolved good-karma source, exact spawn separation, node dimensions,
|
||||
full starting gear, and mob scaling policy remain open. This build uses configurable
|
||||
placeholders (world-age mob scaling resets with each new world). New clarification:
|
||||
the boss spawns after seven days and slowly destroys the world until defeated or
|
||||
until no survivors remain. Collapse duration, damage behavior, offline safety,
|
||||
and the fresh-world opening cadence still need design approval through playtesting.
|
||||
@@ -0,0 +1,61 @@
|
||||
# Verification performed
|
||||
|
||||
Local checks on Windows, 2026-09-05. Node 24.13.0, Go 1.27.1, Blender 4.3.2,
|
||||
Helm 3.18.6, and headless Microsoft Edge driven by Playwright.
|
||||
|
||||
## Passing checks
|
||||
|
||||
- Generated Go/TypeScript contract drift check, TypeScript strict checking, and
|
||||
production Vite build. Main JavaScript: 600.22 KB, 156.65 KB gzip estimate.
|
||||
- Go tests: deterministic terrain and seams, movement bounds/replay rejection,
|
||||
chunk interest, gathering/crafting, permanent death across restart, daily cap,
|
||||
real wall-time accounting under lag, keystone safety, boss victory/collapse,
|
||||
offline survivors, transfer progress preservation, resource replication.
|
||||
- Storage tests: exclusive ownership, stale-owner rejection, durable passages,
|
||||
cross-account denial, duplicate redemption rejection, simultaneous redemption
|
||||
at two destinations, later-world passages, session revocation.
|
||||
- HTTP/WebSocket tests: origin rejection, HttpOnly sessions, unknown JSON fields,
|
||||
initial chunk delivery, private identity exclusion, malformed socket input.
|
||||
- `go vet ./...`.
|
||||
- Four Playwright tests: desktop rendering/movement/gather/reconnect; mobile
|
||||
portrait and landscape controls/layout; HTTP security behavior; boss rendering
|
||||
and actual server-authoritative boss damage. Canvas pixel variation, loaded
|
||||
models, triangle counts, and progressing render frames were checked.
|
||||
- Desktop, mobile, landscape, and boss screenshots visually inspected.
|
||||
- Helm lint and rendering: five distinct Deployments/Services/Ingresses plus a
|
||||
NetworkPolicy. No cluster resources were applied.
|
||||
|
||||
## Initial concurrency measurement
|
||||
|
||||
`go run ./cmd/load -url http://127.0.0.1:18090 -clients 20 -duration 15s`
|
||||
|
||||
Twenty authenticated WebSocket clients on an isolated local development world,
|
||||
with periodic movement/idle intents and snapshot reads. Join setup is excluded
|
||||
from the throughput window. This is a short connection/replication smoke test,
|
||||
not a long-duration soak, active combat workload, mobile hardware benchmark, or
|
||||
large final-boss crowd test.
|
||||
|
||||
| Measurement | Before static-resource optimization | After |
|
||||
|---|---:|---:|
|
||||
| Concurrent clients | 20 | 20 |
|
||||
| Measurement duration | 15 seconds | 15 seconds |
|
||||
| Delivered snapshots | 1,500 | 1,500 |
|
||||
| Outgoing application payload | 7,548.5 KiB/s | 560.3 KiB/s |
|
||||
| p95 interval between snapshots | 206.9 ms | 203.0 ms |
|
||||
| Unexpected disconnections | 0 | 0 |
|
||||
|
||||
The target snapshot interval is 200 ms. Sending static resource transforms once
|
||||
per chunk reduced measured outgoing payload by about 92.6%. Figures exclude TCP,
|
||||
WebSocket, and TLS framing. CPU/RAM/GPU saturation and 2,000 players remain unproven.
|
||||
|
||||
## Not executed locally
|
||||
|
||||
- Docker image build/runtime: Docker Desktop's Linux daemon was not running.
|
||||
- PostgreSQL-backed tests: no test database was configured locally; the workflow
|
||||
provides a PostgreSQL service and runs the same storage lifecycle suite there.
|
||||
- Go race detector: no local C toolchain was available; the Linux CI job runs it.
|
||||
- Real OIDC-provider login, cross-host production transfer, TLS ingress, network
|
||||
policy enforcement, image publication, ArgoCD sync, and Kubernetes rollout.
|
||||
|
||||
The Playwright Chromium download timed out; all browser tests ran successfully
|
||||
using installed Edge instead. CI is configured to install Chromium.
|
||||
Generated
+1629
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"name": "aeternalis",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"generate": "node tools/generate-protocol.mjs",
|
||||
"check": "tsc --noEmit -p client/tsconfig.json",
|
||||
"build": "vite build --config client/vite.config.ts",
|
||||
"dev": "vite --config client/vite.config.ts --host 127.0.0.1",
|
||||
"test:e2e": "playwright test",
|
||||
"test:contracts": "node tools/generate-protocol.mjs --check"
|
||||
},
|
||||
"dependencies": {
|
||||
"three": "^0.180.0",
|
||||
"lucide": "^0.468.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@playwright/test": "^1.55.0",
|
||||
"@types/three": "^0.180.0",
|
||||
"typescript": "^5.9.2",
|
||||
"vite": "^7.1.0",
|
||||
"quicktype-core": "^23.2.6",
|
||||
"yaml": "^2.8.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
# September 2026 implementation notes
|
||||
|
||||
The original `VISION.md` remains the user-authored planning source. This addendum
|
||||
records the new explicit requirement and the boundary of the first implementation.
|
||||
|
||||
## Confirmed addition
|
||||
|
||||
After one real-world week, a boss spawns and slowly destroys the world. When the
|
||||
boss dies, living characters may move to a new server/world. A dead character is
|
||||
permanently finished. Production deployment should run on Kubernetes and use a
|
||||
Gitea workflow compatible with Harbor and ArgoCD. The client is browser-first,
|
||||
with platform changes considered only after real performance measurements.
|
||||
|
||||
## Implemented interpretation for playtesting
|
||||
|
||||
The deadline is seven days by default. A shrinking circular hazard represents
|
||||
world destruction over a configurable period. Victory grants persistent passage
|
||||
to eligible survivors; complete collapse kills everyone still assigned to the
|
||||
world. A character and its inventory/skills retain identity across successful
|
||||
passages. A passage is bound to its account and can be redeemed only once per
|
||||
successful world. Daily play usage carries forward with the character.
|
||||
|
||||
These choices remain provisional: 30-minute destruction duration, hazard damage,
|
||||
offline exposure, safe-zone behavior during the event, finite world radius,
|
||||
48-unit spawn separation, and mob scaling. The current generated chunks are
|
||||
heightfields; volumetric terrain and terrain deformation are not implemented.
|
||||
|
||||
The full assessment, delivered scope, and follow-up work are documented under
|
||||
`docs/`. No 2,000-player, security-audit, or live Kubernetes deployment claim is made.
|
||||
@@ -0,0 +1,11 @@
|
||||
import { defineConfig } from '@playwright/test';
|
||||
|
||||
export default defineConfig({
|
||||
testDir: './tests', timeout: 45000, workers: 1, fullyParallel: false,
|
||||
use: { baseURL: 'http://127.0.0.1:18089', browserName: 'chromium', channel: process.env.PLAYWRIGHT_CHANNEL || undefined, headless: true, screenshot: 'only-on-failure', trace: 'retain-on-failure', launchOptions: { args: ['--use-angle=swiftshader', '--enable-unsafe-swiftshader'] } },
|
||||
webServer: {
|
||||
command: 'node tools/dev-server.mjs', url: 'http://127.0.0.1:18089/readyz',
|
||||
timeout: 180000, reuseExistingServer: false,
|
||||
env: { PORT: '18089', E2E: 'true', WORLD_ID: 'e2e', DEV_SEASON_SECONDS: '3600' },
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,4 @@
|
||||
# Shared contracts
|
||||
|
||||
Edit protocol.json, then run `npm run generate`. Generated Go and TypeScript must
|
||||
be committed together. Inputs additionally need semantic validation on the server.
|
||||
@@ -0,0 +1,82 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "Protocol",
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"intent": {"$ref": "#/definitions/Intent"},
|
||||
"snapshot": {"$ref": "#/definitions/Snapshot"}
|
||||
},
|
||||
"required": ["intent", "snapshot"],
|
||||
"definitions": {
|
||||
"Vec3": {
|
||||
"type": "object", "additionalProperties": false,
|
||||
"properties": {"x": {"type": "number"}, "y": {"type": "number"}, "z": {"type": "number"}},
|
||||
"required": ["x", "y", "z"]
|
||||
},
|
||||
"Intent": {
|
||||
"type": "object", "additionalProperties": false,
|
||||
"properties": {
|
||||
"op": {"type": "string"}, "seq": {"type": "integer"},
|
||||
"x": {"type": "number"}, "z": {"type": "number"}, "target": {"type": "string"}
|
||||
},
|
||||
"required": ["op", "seq", "x", "z", "target"]
|
||||
},
|
||||
"Entity": {
|
||||
"type": "object", "additionalProperties": false,
|
||||
"properties": {
|
||||
"id": {"type": "string"}, "kind": {"type": "string"}, "name": {"type": "string"},
|
||||
"position": {"$ref": "#/definitions/Vec3"},
|
||||
"hp": {"type": "number"}, "maxHp": {"type": "number"},
|
||||
"state": {"type": "string"}
|
||||
},
|
||||
"required": ["id", "kind", "name", "position", "hp", "maxHp", "state"]
|
||||
},
|
||||
"Character": {
|
||||
"type": "object", "additionalProperties": false,
|
||||
"properties": {
|
||||
"entity": {"$ref": "#/definitions/Entity"},
|
||||
"inventory": {"type": "object", "additionalProperties": {"type": "integer"}},
|
||||
"skills": {"type": "object", "additionalProperties": {"type": "integer"}},
|
||||
"playedSeconds": {"type": "number"}, "remainingSeconds": {"type": "number"},
|
||||
"kills": {"type": "integer"}, "ack": {"type": "integer"},
|
||||
"hasKeystone": {"type": "boolean"}
|
||||
},
|
||||
"required": ["entity", "inventory", "skills", "playedSeconds", "remainingSeconds", "kills", "ack", "hasKeystone"]
|
||||
},
|
||||
"Chunk": {
|
||||
"type": "object", "additionalProperties": false,
|
||||
"properties": {
|
||||
"key": {"type": "string"}, "x": {"type": "integer"}, "z": {"type": "integer"},
|
||||
"size": {"type": "number"}, "resolution": {"type": "integer"},
|
||||
"heights": {"type": "array", "items": {"type": "number"}},
|
||||
"biome": {"type": "string"}, "resources": {"type": "array", "items": {"$ref": "#/definitions/Entity"}}
|
||||
},
|
||||
"required": ["key", "x", "z", "size", "resolution", "heights", "biome", "resources"]
|
||||
},
|
||||
"WorldInfo": {
|
||||
"type": "object", "additionalProperties": false,
|
||||
"properties": {
|
||||
"id": {"type": "string"}, "seed": {"type": "integer"}, "phase": {"type": "string"},
|
||||
"ageSeconds": {"type": "number"}, "bossInSeconds": {"type": "number"},
|
||||
"collapseInSeconds": {"type": "number"}, "safeRadius": {"type": "number"},
|
||||
"radius": {"type": "number"}, "online": {"type": "integer"}, "capacity": {"type": "integer"},
|
||||
"bossHp": {"type": "number"}, "bossMaxHp": {"type": "number"}
|
||||
},
|
||||
"required": ["id", "seed", "phase", "ageSeconds", "bossInSeconds", "collapseInSeconds", "safeRadius", "radius", "online", "capacity", "bossHp", "bossMaxHp"]
|
||||
},
|
||||
"Snapshot": {
|
||||
"type": "object", "additionalProperties": false,
|
||||
"properties": {
|
||||
"type": {"type": "string"}, "version": {"type": "integer"}, "tick": {"type": "integer"},
|
||||
"world": {"$ref": "#/definitions/WorldInfo"}, "self": {"$ref": "#/definitions/Character"},
|
||||
"entities": {"type": "array", "items": {"$ref": "#/definitions/Entity"}},
|
||||
"chunks": {"type": "array", "items": {"$ref": "#/definitions/Chunk"}},
|
||||
"chunkKeys": {"type": "array", "items": {"type": "string"}},
|
||||
"unavailableResources": {"type": "array", "items": {"type": "string"}},
|
||||
"message": {"type": "string"}
|
||||
},
|
||||
"required": ["type", "version", "tick", "world", "self", "entities", "chunks", "chunkKeys", "unavailableResources", "message"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
# Authoritative server
|
||||
|
||||
`internal/game` is deterministic simulation, with no HTTP or database dependency.
|
||||
`internal/store` owns durable snapshots, exclusive ownership, and atomic transfers.
|
||||
`internal/transport` authenticates and validates requests before intents reach game.
|
||||
Keep all balance values in `content/balance.yaml`. Test lifecycle and auth boundaries.
|
||||
@@ -0,0 +1,143 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"github.com/coder/websocket"
|
||||
)
|
||||
|
||||
func main() {
|
||||
base := flag.String("url", "http://127.0.0.1:18080", "loopback development world")
|
||||
clients := flag.Int("clients", 20, "concurrent clients (1-100)")
|
||||
duration := flag.Duration("duration", 20*time.Second, "measurement duration after connections")
|
||||
flag.Parse()
|
||||
u, err := url.Parse(*base)
|
||||
if err != nil || net.ParseIP(u.Hostname()) == nil || !net.ParseIP(u.Hostname()).IsLoopback() {
|
||||
panic("load tool only targets explicit loopback development servers")
|
||||
}
|
||||
if *clients < 1 || *clients > 100 {
|
||||
panic("clients must be 1-100")
|
||||
}
|
||||
var received, frames, failures atomic.Int64
|
||||
var mu sync.Mutex
|
||||
intervals := []float64{}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
var readers, writers sync.WaitGroup
|
||||
client := &http.Client{Timeout: 5 * time.Second}
|
||||
post := func(path, body string, cookie *http.Cookie) (*http.Response, error) {
|
||||
req, _ := http.NewRequestWithContext(ctx, "POST", *base+path, strings.NewReader(body))
|
||||
req.Header.Set("Origin", *base)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if cookie != nil {
|
||||
req.AddCookie(cookie)
|
||||
}
|
||||
return client.Do(req)
|
||||
}
|
||||
for i := 0; i < *clients; i++ {
|
||||
r, err := post("/auth/dev", "{}", nil)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
cookies := r.Cookies()
|
||||
io.Copy(io.Discard, r.Body)
|
||||
r.Body.Close()
|
||||
if r.StatusCode != 200 || len(cookies) == 0 {
|
||||
panic(fmt.Sprintf("auth status %d", r.StatusCode))
|
||||
}
|
||||
r, err = post("/api/join", fmt.Sprintf(`{"name":"Load %d","passage":""}`, i), cookies[0])
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
data, _ := io.ReadAll(r.Body)
|
||||
r.Body.Close()
|
||||
if r.StatusCode != 200 {
|
||||
panic(fmt.Sprintf("join %d %s", r.StatusCode, data))
|
||||
}
|
||||
conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(*base, "http")+"/ws", &websocket.DialOptions{HTTPHeader: http.Header{"Origin": []string{*base}, "Cookie": []string{cookies[0].String()}}})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
conn.SetReadLimit(4 << 20)
|
||||
readers.Add(1)
|
||||
go func() {
|
||||
defer readers.Done()
|
||||
defer conn.CloseNow()
|
||||
last := time.Time{}
|
||||
for {
|
||||
_, data, err := conn.Read(ctx)
|
||||
if err != nil {
|
||||
if ctx.Err() == nil {
|
||||
failures.Add(1)
|
||||
}
|
||||
return
|
||||
}
|
||||
now := time.Now()
|
||||
if !last.IsZero() {
|
||||
mu.Lock()
|
||||
intervals = append(intervals, now.Sub(last).Seconds()*1000)
|
||||
mu.Unlock()
|
||||
}
|
||||
last = now
|
||||
received.Add(int64(len(data)))
|
||||
frames.Add(1)
|
||||
if !bytes.Contains(data, []byte(`"type":"snapshot"`)) {
|
||||
failures.Add(1)
|
||||
}
|
||||
}
|
||||
}()
|
||||
writers.Add(1)
|
||||
go func() {
|
||||
defer writers.Done()
|
||||
ticker := time.NewTicker(50 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
seq := int64(0)
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
seq++
|
||||
data, _ := json.Marshal(p.Intent{Op: "move", Seq: seq})
|
||||
writeCtx, stop := context.WithTimeout(ctx, time.Second)
|
||||
err := conn.Write(writeCtx, websocket.MessageText, data)
|
||||
stop()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
time.Sleep(400 * time.Millisecond)
|
||||
}
|
||||
baselineBytes, baselineFrames := received.Load(), frames.Load()
|
||||
start := time.Now()
|
||||
time.Sleep(*duration)
|
||||
elapsed := time.Since(start).Seconds()
|
||||
cancel()
|
||||
readers.Wait()
|
||||
writers.Wait()
|
||||
sort.Float64s(intervals)
|
||||
p95 := float64(0)
|
||||
if len(intervals) > 0 {
|
||||
p95 = intervals[int(float64(len(intervals)-1)*.95)]
|
||||
}
|
||||
fmt.Printf("clients=%d duration=%.1fs snapshots=%d payload_KiB_per_second=%.1f p95_snapshot_interval_ms=%.1f disconnects=%d\n", *clients, elapsed, frames.Load()-baselineFrames, float64(received.Load()-baselineBytes)/1024/elapsed, p95, failures.Load())
|
||||
if failures.Load() > 0 {
|
||||
panic("unexpected client disconnects")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"aeternalis/server/content"
|
||||
"aeternalis/server/internal/game"
|
||||
"aeternalis/server/internal/store"
|
||||
"aeternalis/server/internal/transport"
|
||||
)
|
||||
|
||||
func env(k, def string) string {
|
||||
if v := os.Getenv(k); v != "" {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
func run() error {
|
||||
dev := env("APP_ENV", "production") == "development"
|
||||
listen := env("LISTEN_ADDR", "127.0.0.1:18080")
|
||||
base := env("PUBLIC_URL", "http://127.0.0.1:18080")
|
||||
if dev {
|
||||
host, _, err := net.SplitHostPort(listen)
|
||||
if err != nil || net.ParseIP(host) == nil || !net.ParseIP(host).IsLoopback() {
|
||||
return errors.New("development auth requires an explicit loopback listen address")
|
||||
}
|
||||
u, err := url.Parse(base)
|
||||
if err != nil || net.ParseIP(u.Hostname()) == nil || !net.ParseIP(u.Hostname()).IsLoopback() {
|
||||
return errors.New("development PUBLIC_URL must be loopback")
|
||||
}
|
||||
}
|
||||
if !dev && os.Getenv("DATABASE_URL") == "" {
|
||||
return errors.New("production requires DATABASE_URL")
|
||||
}
|
||||
dsn := env("DATABASE_URL", "file:../.local/aeternalis.db")
|
||||
if !dev && !(strings.HasPrefix(dsn, "postgres://") || strings.HasPrefix(dsn, "postgresql://")) {
|
||||
return errors.New("production requires PostgreSQL")
|
||||
}
|
||||
if !dev {
|
||||
u, err := url.Parse(dsn)
|
||||
if err != nil || u.Query().Get("sslmode") != "verify-full" {
|
||||
return errors.New("production DATABASE_URL requires sslmode=verify-full")
|
||||
}
|
||||
}
|
||||
if dev && strings.HasPrefix(dsn, "file:") {
|
||||
path := strings.Split(strings.TrimPrefix(dsn, "file:"), "?")[0]
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
b, err := content.Load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if dev {
|
||||
for key, dest := range map[string]*float64{"DEV_SEASON_SECONDS": &b.SeasonSeconds, "DEV_COLLAPSE_SECONDS": &b.CollapseSeconds, "DEV_DAILY_SECONDS": &b.DailyPlaySeconds} {
|
||||
if raw := os.Getenv(key); raw != "" {
|
||||
value, err := strconv.ParseFloat(raw, 64)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*dest = value
|
||||
}
|
||||
}
|
||||
}
|
||||
if err = b.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
seed, err := strconv.ParseInt(env("WORLD_SEED", "734291"), 10, 64)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
id := env("WORLD_ID", "world-001")
|
||||
if len(id) > 64 || strings.ContainsAny(id, "/\\ \t\n") {
|
||||
return errors.New("invalid WORLD_ID")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
db, err := store.Open(ctx, dsn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer db.Close()
|
||||
w := game.New(id, seed, time.Now().UTC(), b)
|
||||
lease, raw, err := db.Acquire(ctx, w)
|
||||
if err != nil {
|
||||
return fmt.Errorf("acquire world: %w", err)
|
||||
}
|
||||
released := false
|
||||
defer func() {
|
||||
if !released {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
_ = lease.Release(ctx)
|
||||
}
|
||||
}()
|
||||
if err = json.Unmarshal(raw, w); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = w.Restore(time.Now().UTC()); err != nil {
|
||||
return err
|
||||
}
|
||||
auth, err := transport.NewAuth(ctx, db, dev, base, os.Getenv("OIDC_ISSUER"), os.Getenv("OIDC_CLIENT_ID"), os.Getenv("OIDC_CLIENT_SECRET"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
worlds := []transport.Destination{}
|
||||
if raw := os.Getenv("WORLD_DIRECTORY"); raw != "" {
|
||||
if err = json.Unmarshal([]byte(raw), &worlds); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, dest := range worlds {
|
||||
u, err := url.Parse(dest.URL)
|
||||
if err != nil || u.Host == "" || (!dev && u.Scheme != "https") || u.User != nil {
|
||||
return errors.New("invalid WORLD_DIRECTORY URL")
|
||||
}
|
||||
}
|
||||
}
|
||||
svc := transport.NewService(w, lease)
|
||||
handler := transport.NewHTTP(svc, auth, env("CLIENT_DIR", "../client/dist"), worlds).Handler()
|
||||
server := &http.Server{Addr: listen, Handler: handler, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second, WriteTimeout: 15 * time.Second, IdleTimeout: 60 * time.Second, MaxHeaderBytes: 16384}
|
||||
runtimeCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
go svc.Run(runtimeCtx)
|
||||
errorsCh := make(chan error, 1)
|
||||
go func() {
|
||||
slog.Info("world listening", "url", base, "world", id, "development", dev)
|
||||
errorsCh <- server.ListenAndServe()
|
||||
}()
|
||||
select {
|
||||
case <-runtimeCtx.Done():
|
||||
case err = <-errorsCh:
|
||||
if !errors.Is(err, http.ErrServerClosed) {
|
||||
return err
|
||||
}
|
||||
}
|
||||
stop()
|
||||
shutdown, cancelShutdown := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancelShutdown()
|
||||
err = svc.Stop(shutdown)
|
||||
released = true
|
||||
httpErr := server.Shutdown(shutdown)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return httpErr
|
||||
}
|
||||
func main() {
|
||||
if err := run(); err != nil {
|
||||
slog.Error("world stopped", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
version: 1
|
||||
tickHz: 20
|
||||
snapshotHz: 5
|
||||
chunkSize: 128
|
||||
terrainResolution: 16
|
||||
worldRadius: 1024
|
||||
maxPlayers: 100
|
||||
spawnSeparation: 48
|
||||
seasonSeconds: 604800
|
||||
collapseSeconds: 1800
|
||||
dailyPlaySeconds: 7200
|
||||
playerHp: 100
|
||||
playerSpeed: 12
|
||||
attackRange: 6
|
||||
attackCooldown: 0.7
|
||||
playerDamage: 18
|
||||
spearDamage: 32
|
||||
gatherRange: 7
|
||||
gatherCooldown: 0.6
|
||||
bossHp: 1200
|
||||
bossDamage: 18
|
||||
bossRange: 12
|
||||
bossCooldown: 2
|
||||
stormDamagePerSecond: 15
|
||||
mobHp: 54
|
||||
mobDamage: 6
|
||||
mobSpeed: 4
|
||||
mobAggroRange: 24
|
||||
mobAttackRange: 3
|
||||
mobCooldown: 1.8
|
||||
mobRespawnSeconds: 40
|
||||
mobScalePerDay: 0.1
|
||||
resourcesPerChunk: 48
|
||||
resourceRespawnSeconds: 120
|
||||
skillXpPerAction: 1
|
||||
startingKit:
|
||||
knife: 1
|
||||
axe: 1
|
||||
flint_and_steel: 1
|
||||
fishing_pole: 1
|
||||
recipes:
|
||||
spear:
|
||||
inputs: { wood: 3, ore: 2 }
|
||||
outputs: { spear: 1 }
|
||||
bandage:
|
||||
inputs: { herb: 2 }
|
||||
outputs: { bandage: 1 }
|
||||
bandageHealing: 35
|
||||
@@ -0,0 +1,117 @@
|
||||
package content
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
_ "embed"
|
||||
"fmt"
|
||||
"math"
|
||||
"reflect"
|
||||
|
||||
"go.yaml.in/yaml/v3"
|
||||
)
|
||||
|
||||
//go:embed balance.yaml
|
||||
var balance []byte
|
||||
|
||||
type Recipe struct {
|
||||
Inputs map[string]int64 `yaml:"inputs"`
|
||||
Outputs map[string]int64 `yaml:"outputs"`
|
||||
}
|
||||
|
||||
type Balance struct {
|
||||
Version int `yaml:"version"`
|
||||
TickHz int `yaml:"tickHz"`
|
||||
SnapshotHz int `yaml:"snapshotHz"`
|
||||
ChunkSize float64 `yaml:"chunkSize"`
|
||||
TerrainResolution int `yaml:"terrainResolution"`
|
||||
WorldRadius float64 `yaml:"worldRadius"`
|
||||
MaxPlayers int `yaml:"maxPlayers"`
|
||||
SpawnSeparation float64 `yaml:"spawnSeparation"`
|
||||
SeasonSeconds float64 `yaml:"seasonSeconds"`
|
||||
CollapseSeconds float64 `yaml:"collapseSeconds"`
|
||||
DailyPlaySeconds float64 `yaml:"dailyPlaySeconds"`
|
||||
PlayerHp float64 `yaml:"playerHp"`
|
||||
PlayerSpeed float64 `yaml:"playerSpeed"`
|
||||
AttackRange float64 `yaml:"attackRange"`
|
||||
AttackCooldown float64 `yaml:"attackCooldown"`
|
||||
PlayerDamage float64 `yaml:"playerDamage"`
|
||||
SpearDamage float64 `yaml:"spearDamage"`
|
||||
GatherRange float64 `yaml:"gatherRange"`
|
||||
GatherCooldown float64 `yaml:"gatherCooldown"`
|
||||
BossHp float64 `yaml:"bossHp"`
|
||||
BossDamage float64 `yaml:"bossDamage"`
|
||||
BossRange float64 `yaml:"bossRange"`
|
||||
BossCooldown float64 `yaml:"bossCooldown"`
|
||||
StormDamagePerSecond float64 `yaml:"stormDamagePerSecond"`
|
||||
MobHp float64 `yaml:"mobHp"`
|
||||
MobDamage float64 `yaml:"mobDamage"`
|
||||
MobSpeed float64 `yaml:"mobSpeed"`
|
||||
MobAggroRange float64 `yaml:"mobAggroRange"`
|
||||
MobAttackRange float64 `yaml:"mobAttackRange"`
|
||||
MobCooldown float64 `yaml:"mobCooldown"`
|
||||
MobRespawnSeconds float64 `yaml:"mobRespawnSeconds"`
|
||||
MobScalePerDay float64 `yaml:"mobScalePerDay"`
|
||||
ResourcesPerChunk int `yaml:"resourcesPerChunk"`
|
||||
ResourceRespawnSeconds float64 `yaml:"resourceRespawnSeconds"`
|
||||
SkillXpPerAction int64 `yaml:"skillXpPerAction"`
|
||||
StartingKit map[string]int64 `yaml:"startingKit"`
|
||||
Recipes map[string]Recipe `yaml:"recipes"`
|
||||
BandageHealing float64 `yaml:"bandageHealing"`
|
||||
}
|
||||
|
||||
func Load() (Balance, error) { return Parse(balance) }
|
||||
func Parse(data []byte) (Balance, error) {
|
||||
var b Balance
|
||||
d := yaml.NewDecoder(bytes.NewReader(data))
|
||||
d.KnownFields(true)
|
||||
if err := d.Decode(&b); err != nil {
|
||||
return b, err
|
||||
}
|
||||
return b, b.Validate()
|
||||
}
|
||||
func (b Balance) Validate() error {
|
||||
v := reflect.ValueOf(b)
|
||||
for i := 0; i < v.NumField(); i++ {
|
||||
f := v.Field(i)
|
||||
n := float64(1)
|
||||
switch f.Kind() {
|
||||
case reflect.Int, reflect.Int64:
|
||||
n = float64(f.Int())
|
||||
case reflect.Float64:
|
||||
n = f.Float()
|
||||
}
|
||||
if n <= 0 || math.IsNaN(n) || math.IsInf(n, 0) {
|
||||
return fmt.Errorf("%s must be finite and positive", v.Type().Field(i).Name)
|
||||
}
|
||||
}
|
||||
if b.TickHz > 60 || b.SnapshotHz > b.TickHz || b.TickHz%b.SnapshotHz != 0 || b.TerrainResolution > 64 || b.ResourcesPerChunk > 128 || b.MaxPlayers > 2000 || b.WorldRadius < b.ChunkSize*2 {
|
||||
return fmt.Errorf("invalid capacity, terrain, or tick configuration")
|
||||
}
|
||||
known := map[string]bool{"knife": true, "axe": true, "flint_and_steel": true, "fishing_pole": true, "wood": true, "ore": true, "herb": true, "spear": true, "bandage": true}
|
||||
check := func(items map[string]int64) error {
|
||||
if len(items) == 0 {
|
||||
return fmt.Errorf("empty item list")
|
||||
}
|
||||
for k, n := range items {
|
||||
if !known[k] || n < 1 || n > 1000 {
|
||||
return fmt.Errorf("invalid item %q quantity %d", k, n)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err := check(b.StartingKit); err != nil {
|
||||
return err
|
||||
}
|
||||
for name, r := range b.Recipes {
|
||||
if !known[name] {
|
||||
return fmt.Errorf("unknown recipe %q", name)
|
||||
}
|
||||
if err := check(r.Inputs); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := check(r.Outputs); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package content
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestBalanceValidation(t *testing.T) {
|
||||
b, err := Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b.PlayerSpeed = -1
|
||||
if b.Validate() == nil {
|
||||
t.Fatal("negative speed accepted")
|
||||
}
|
||||
if _, err = Parse([]byte("unexpected: 1")); err == nil {
|
||||
t.Fatal("unknown content key accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
module aeternalis/server
|
||||
|
||||
go 1.26.0
|
||||
|
||||
require (
|
||||
github.com/coder/websocket v1.8.15
|
||||
github.com/coreos/go-oidc/v3 v3.21.0
|
||||
github.com/jackc/pgx/v5 v5.10.0
|
||||
github.com/ojrac/opensimplex-go v1.0.2
|
||||
go.yaml.in/yaml/v3 v3.0.5
|
||||
golang.org/x/oauth2 v0.36.0
|
||||
modernc.org/sqlite v1.58.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/go-jose/go-jose/v4 v4.1.4 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/mattn/go-isatty v0.0.24 // indirect
|
||||
github.com/ncruces/go-strftime v1.0.0 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
golang.org/x/sync v0.22.0 // indirect
|
||||
golang.org/x/sys v0.47.0 // indirect
|
||||
golang.org/x/text v0.29.0 // indirect
|
||||
modernc.org/libc v1.75.6 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
modernc.org/memory v1.12.1 // indirect
|
||||
)
|
||||
@@ -0,0 +1,86 @@
|
||||
github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA=
|
||||
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
|
||||
github.com/coreos/go-oidc/v3 v3.21.0 h1:wZo4Q9Pum8dYEj0eMUPrqR+kvuGkeUplbLpNCkBqoWM=
|
||||
github.com/coreos/go-oidc/v3 v3.21.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA=
|
||||
github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
|
||||
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo=
|
||||
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0=
|
||||
github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
|
||||
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
|
||||
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
|
||||
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||
github.com/ojrac/opensimplex-go v1.0.2 h1:l4vs0D+JCakcu5OV0kJ99oEaWJfggSc9jiLpxaWvSzs=
|
||||
github.com/ojrac/opensimplex-go v1.0.2/go.mod h1:NwbXFFbXcdGgIFdiA7/REME+7n/lOf1TuEbLiZYOWnM=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk=
|
||||
golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=
|
||||
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
|
||||
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
|
||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
|
||||
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
|
||||
golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE=
|
||||
golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
modernc.org/cc/v4 v4.29.2 h1:h6+9ciCnPKutf4I03CvheAvDLX7+IHlqR6Iy6J+cgd8=
|
||||
modernc.org/cc/v4 v4.29.2/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
|
||||
modernc.org/ccgo/v4 v4.35.0 h1:F+TUsmw09QxLzmi3aeYYGxjAXarmZaKgj3mKQHNaA8w=
|
||||
modernc.org/ccgo/v4 v4.35.0/go.mod h1:qrVGs9S3Sr2Ztcg9ve+kTAYMp5a3YvWjo+SoN06kJ5I=
|
||||
modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
|
||||
modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
|
||||
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
|
||||
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
|
||||
modernc.org/gc/v3 v3.1.5 h1:21ldfPfRYE31Tb7B3mwAK8gy1AxP4+dKjrOQPfqakoc=
|
||||
modernc.org/gc/v3 v3.1.5/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
|
||||
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
|
||||
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
|
||||
modernc.org/libc v1.75.6 h1:yKk8qo+Di4gkmvRboK8ocCqH22FiUCR6jRy2OwtCRus=
|
||||
modernc.org/libc v1.75.6/go.mod h1:bO5o2ztHxBb2rjz0PgdHN0sSMw57CgxGFLZ3Qd/QpVQ=
|
||||
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
||||
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
|
||||
modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g=
|
||||
modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
|
||||
modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=
|
||||
modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
|
||||
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
|
||||
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
|
||||
modernc.org/sqlite v1.58.0 h1:38u40/bwkfM7f0Myhosl+SEMltSDxnGdQf8o6Kjmys0=
|
||||
modernc.org/sqlite v1.58.0/go.mod h1:rsD2CckafgObKC4DhBlGBf+RiHxkc3hINGt1Xw32tVY=
|
||||
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
|
||||
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
|
||||
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
|
||||
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
|
||||
@@ -0,0 +1,69 @@
|
||||
package game
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"math/rand/v2"
|
||||
|
||||
"aeternalis/server/content"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"github.com/ojrac/opensimplex-go"
|
||||
)
|
||||
|
||||
const GeneratorVersion = 1
|
||||
|
||||
type Terrain struct {
|
||||
Seed int64
|
||||
B content.Balance
|
||||
noise opensimplex.Noise
|
||||
}
|
||||
|
||||
func NewTerrain(seed int64, b content.Balance) *Terrain {
|
||||
return &Terrain{seed, b, opensimplex.New(seed)}
|
||||
}
|
||||
func (t *Terrain) rawHeight(x, z float64) float64 {
|
||||
// A low, flat arrival clearing blends into broad hills and fine detail.
|
||||
d := math.Min(1, math.Hypot(x, z)/55)
|
||||
return (t.noise.Eval2(x/220, z/220)*17 + t.noise.Eval2(x/55, z/55)*3) * d
|
||||
}
|
||||
func ChunkCoord(v, size float64) int { return int(math.Floor(v / size)) }
|
||||
func Key(x, z int) string { return fmt.Sprintf("%d:%d", x, z) }
|
||||
|
||||
// Height uses the same triangle split as the transmitted terrain mesh.
|
||||
func (t *Terrain) Height(x, z float64) float64 {
|
||||
step := t.B.ChunkSize / float64(t.B.TerrainResolution)
|
||||
ix, iz := math.Floor(x/step), math.Floor(z/step)
|
||||
fx, fz := x/step-ix, z/step-iz
|
||||
a, b := t.rawHeight(ix*step, iz*step), t.rawHeight((ix+1)*step, iz*step)
|
||||
c, d := t.rawHeight(ix*step, (iz+1)*step), t.rawHeight((ix+1)*step, (iz+1)*step)
|
||||
if fx+fz <= 1 {
|
||||
return a + (b-a)*fx + (c-a)*fz
|
||||
}
|
||||
return d + (c-d)*(1-fx) + (b-d)*(1-fz)
|
||||
}
|
||||
func (t *Terrain) Position(x, z float64) p.Vec3 { return p.Vec3{X: x, Y: t.Height(x, z), Z: z} }
|
||||
func (t *Terrain) Chunk(x, z int) p.Chunk {
|
||||
c := p.Chunk{Key: Key(x, z), X: int64(x), Z: int64(z), Size: t.B.ChunkSize, Resolution: int64(t.B.TerrainResolution), Biome: "highlands", Heights: []float64{}, Resources: []p.Entity{}}
|
||||
for iz := 0; iz <= t.B.TerrainResolution; iz++ {
|
||||
for ix := 0; ix <= t.B.TerrainResolution; ix++ {
|
||||
c.Heights = append(c.Heights, t.rawHeight(float64(x)*c.Size+float64(ix)*c.Size/float64(c.Resolution), float64(z)*c.Size+float64(iz)*c.Size/float64(c.Resolution)))
|
||||
}
|
||||
}
|
||||
rng := rand.New(rand.NewPCG(uint64(t.Seed)^uint64(int64(x)*73856093), uint64(int64(z)*19349663)^0xa341316c))
|
||||
kinds := []string{"tree", "ore", "herb"}
|
||||
for i := 0; i < t.B.ResourcesPerChunk; i++ {
|
||||
px, pz := (float64(x)+0.08+rng.Float64()*0.84)*c.Size, (float64(z)+0.08+rng.Float64()*0.84)*c.Size
|
||||
if math.Hypot(px, pz) > t.B.WorldRadius || math.Hypot(px, pz) < 10 {
|
||||
continue
|
||||
}
|
||||
kind := kinds[i%len(kinds)]
|
||||
c.Resources = append(c.Resources, p.Entity{ID: fmt.Sprintf("r:%d:%d:%d", x, z, i), Kind: kind, Name: kind, Position: t.Position(px, pz), HP: 1, MaxHP: 1, State: "available"})
|
||||
}
|
||||
// Arrival resources make the first crafting loop reachable without aimless travel.
|
||||
if x == 0 && z == 0 {
|
||||
for i, k := range kinds {
|
||||
c.Resources = append(c.Resources, p.Entity{ID: "arrival:" + k, Kind: k, Name: k, Position: t.Position(12+float64(i)*5, 12), HP: 1, MaxHP: 1, State: "available"})
|
||||
}
|
||||
}
|
||||
return c
|
||||
}
|
||||
@@ -0,0 +1,648 @@
|
||||
package game
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"aeternalis/server/content"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
)
|
||||
|
||||
type Character struct {
|
||||
View p.Character `json:"view"`
|
||||
Account string `json:"account"`
|
||||
Day string `json:"day"`
|
||||
DailySeconds float64 `json:"dailySeconds"`
|
||||
ReturnPosition *p.Vec3 `json:"returnPosition,omitempty"`
|
||||
Sheltered bool `json:"sheltered"`
|
||||
LastAttack float64 `json:"lastAttack"`
|
||||
LastGather float64 `json:"lastGather"`
|
||||
Online bool `json:"-"`
|
||||
MoveX float64 `json:"-"`
|
||||
MoveZ float64 `json:"-"`
|
||||
LastMove time.Time `json:"-"`
|
||||
Message string `json:"-"`
|
||||
}
|
||||
type Corpse struct {
|
||||
Entity p.Entity `json:"entity"`
|
||||
Inventory map[string]int64 `json:"inventory"`
|
||||
}
|
||||
type Mob struct {
|
||||
Entity p.Entity `json:"entity"`
|
||||
HomeX int `json:"homeX"`
|
||||
HomeZ int `json:"homeZ"`
|
||||
LastAttack float64 `json:"lastAttack"`
|
||||
RespawnAt float64 `json:"respawnAt"`
|
||||
}
|
||||
type World struct {
|
||||
Version int `json:"version"`
|
||||
ID string `json:"id"`
|
||||
Seed int64 `json:"seed"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
EndedAt *time.Time `json:"endedAt,omitempty"`
|
||||
Phase string `json:"phase"`
|
||||
Tick int64 `json:"tick"`
|
||||
BossHP float64 `json:"bossHp"`
|
||||
BossLastAttack float64 `json:"bossLastAttack"`
|
||||
Characters map[string]*Character `json:"characters"`
|
||||
Corpses map[string]*Corpse `json:"corpses"`
|
||||
Depleted map[string]float64 `json:"depleted"`
|
||||
Mobs map[string]*Mob `json:"mobs"`
|
||||
Balance content.Balance `json:"balance"`
|
||||
terrain *Terrain
|
||||
chunks map[string]p.Chunk
|
||||
now time.Time
|
||||
dirty bool
|
||||
}
|
||||
|
||||
func ID() string {
|
||||
var b [16]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return hex.EncodeToString(b[:])
|
||||
}
|
||||
func New(id string, seed int64, now time.Time, b content.Balance) *World {
|
||||
w := &World{Version: GeneratorVersion, ID: id, Seed: seed, CreatedAt: now, Phase: "gathering", BossHP: b.BossHp, Characters: map[string]*Character{}, Corpses: map[string]*Corpse{}, Depleted: map[string]float64{}, Mobs: map[string]*Mob{}, Balance: b}
|
||||
_ = w.Restore(now)
|
||||
return w
|
||||
}
|
||||
func (w *World) Restore(now time.Time) error {
|
||||
if w.Version != GeneratorVersion {
|
||||
return errors.New("unsupported persisted generator version")
|
||||
}
|
||||
if err := w.Balance.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
if w.Characters == nil || w.Mobs == nil || w.Corpses == nil || w.Depleted == nil {
|
||||
return errors.New("invalid world snapshot")
|
||||
}
|
||||
w.terrain = NewTerrain(w.Seed, w.Balance)
|
||||
w.chunks = map[string]p.Chunk{}
|
||||
w.now = now
|
||||
for _, c := range w.Characters {
|
||||
c.Online = false
|
||||
c.MoveX = 0
|
||||
c.MoveZ = 0
|
||||
c.View.ACK = 0
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (w *World) Age() float64 {
|
||||
now := w.now
|
||||
if w.EndedAt != nil {
|
||||
now = *w.EndedAt
|
||||
}
|
||||
return math.Max(0, now.Sub(w.CreatedAt).Seconds())
|
||||
}
|
||||
func (w *World) Dirty() bool { return w.dirty }
|
||||
func (w *World) Saved() { w.dirty = false }
|
||||
func (w *World) SafeRadius() float64 {
|
||||
if w.Phase == "gathering" {
|
||||
return w.Balance.WorldRadius
|
||||
}
|
||||
if w.Phase == "lost" {
|
||||
return 0
|
||||
}
|
||||
return math.Max(0, w.Balance.WorldRadius*(1-(w.Age()-w.Balance.SeasonSeconds)/w.Balance.CollapseSeconds))
|
||||
}
|
||||
func (w *World) Info() p.WorldInfo {
|
||||
online := int64(0)
|
||||
for _, c := range w.Characters {
|
||||
if c.Online {
|
||||
online++
|
||||
}
|
||||
}
|
||||
return p.WorldInfo{ID: w.ID, Seed: w.Seed, Phase: w.Phase, AgeSeconds: w.Age(), BossInSeconds: math.Max(0, w.Balance.SeasonSeconds-w.Age()), CollapseInSeconds: math.Max(0, w.Balance.SeasonSeconds+w.Balance.CollapseSeconds-w.Age()), SafeRadius: w.SafeRadius(), Radius: w.Balance.WorldRadius, Online: online, Capacity: int64(w.Balance.MaxPlayers), BossHP: w.BossHP, BossMaxHP: w.Balance.BossHp}
|
||||
}
|
||||
func (w *World) ForAccount(account string) *Character {
|
||||
for _, c := range w.Characters {
|
||||
if c.Account == account {
|
||||
return c
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (w *World) spawn(exclude string) (p.Vec3, error) {
|
||||
for i := 0; i < 4096; i++ {
|
||||
radius := math.Sqrt(float64(i)) * w.Balance.SpawnSeparation * 0.6
|
||||
angle := float64(i) * 2.399963229728653
|
||||
pos := w.terrain.Position(math.Cos(angle)*radius, math.Sin(angle)*radius)
|
||||
if radius > w.Balance.WorldRadius-32 {
|
||||
break
|
||||
}
|
||||
clear := true
|
||||
for id, c := range w.Characters {
|
||||
if id != exclude && c.View.Entity.State != "dead" && distance(pos, c.View.Entity.Position) < w.Balance.SpawnSeparation {
|
||||
clear = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if clear {
|
||||
return pos, nil
|
||||
}
|
||||
}
|
||||
return p.Vec3{}, errors.New("no separated spawn available")
|
||||
}
|
||||
func (w *World) Join(account, name string) (*Character, error) {
|
||||
if c := w.ForAccount(account); c != nil {
|
||||
return c, nil
|
||||
}
|
||||
if w.Phase != "gathering" {
|
||||
return nil, errors.New("this world is closed to new arrivals")
|
||||
}
|
||||
if len(w.Characters) >= w.Balance.MaxPlayers {
|
||||
return nil, errors.New("world capacity reached")
|
||||
}
|
||||
pos, err := w.spawn("")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c := &Character{Account: account, Day: w.now.UTC().Format(time.DateOnly), View: p.Character{Entity: p.Entity{ID: ID(), Kind: "player", Name: name, Position: pos, HP: w.Balance.PlayerHp, MaxHP: w.Balance.PlayerHp, State: "alive"}, Inventory: map[string]int64{}, Skills: map[string]int64{}, RemainingSeconds: w.Balance.DailyPlaySeconds}}
|
||||
for k, v := range w.Balance.StartingKit {
|
||||
c.View.Inventory[k] = v
|
||||
}
|
||||
w.Characters[c.View.Entity.ID] = c
|
||||
w.dirty = true
|
||||
return c, nil
|
||||
}
|
||||
func (w *World) Import(c *Character) error {
|
||||
if w.Phase != "gathering" || w.ForAccount(c.Account) != nil || len(w.Characters) >= w.Balance.MaxPlayers {
|
||||
return errors.New("destination cannot accept character")
|
||||
}
|
||||
if c.View.Entity.State != "eligible" || c.View.Entity.HP <= 0 {
|
||||
return errors.New("character is not a living survivor")
|
||||
}
|
||||
pos, err := w.spawn("")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.View.Entity.Position = pos
|
||||
c.View.Entity.State = "alive"
|
||||
c.Online = false
|
||||
c.MoveX = 0
|
||||
c.MoveZ = 0
|
||||
c.View.ACK = 0
|
||||
c.LastAttack = 0
|
||||
c.LastGather = 0
|
||||
c.ReturnPosition = nil
|
||||
c.Sheltered = false
|
||||
c.View.HasKeystone = false
|
||||
w.resetDay(c)
|
||||
w.Characters[c.View.Entity.ID] = c
|
||||
w.dirty = true
|
||||
return nil
|
||||
}
|
||||
func (w *World) resetDay(c *Character) {
|
||||
day := w.now.UTC().Format(time.DateOnly)
|
||||
if c.Day != day {
|
||||
c.Day = day
|
||||
c.DailySeconds = 0
|
||||
w.dirty = true
|
||||
}
|
||||
c.View.RemainingSeconds = math.Max(0, w.Balance.DailyPlaySeconds-c.DailySeconds)
|
||||
}
|
||||
func (w *World) Connect(id string) error {
|
||||
c := w.Characters[id]
|
||||
if c == nil {
|
||||
return errors.New("character not found")
|
||||
}
|
||||
w.resetDay(c)
|
||||
if c.View.Entity.State == "dead" {
|
||||
return errors.New("this character has died permanently")
|
||||
}
|
||||
if c.View.RemainingSeconds <= 0 {
|
||||
return errors.New("daily play limit reached; resets at 00:00 UTC")
|
||||
}
|
||||
if c.Online {
|
||||
return errors.New("character already connected")
|
||||
}
|
||||
c.Online = true
|
||||
c.View.ACK = 0
|
||||
c.MoveX = 0
|
||||
c.MoveZ = 0
|
||||
return nil
|
||||
}
|
||||
func (w *World) Disconnect(id string) {
|
||||
if c := w.Characters[id]; c != nil {
|
||||
c.Online = false
|
||||
c.MoveX = 0
|
||||
c.MoveZ = 0
|
||||
}
|
||||
}
|
||||
func distance(a, b p.Vec3) float64 { return math.Hypot(a.X-b.X, a.Z-b.Z) }
|
||||
func (w *World) chunk(x, z int) p.Chunk {
|
||||
key := Key(x, z)
|
||||
if c, ok := w.chunks[key]; ok {
|
||||
return c
|
||||
}
|
||||
c := w.terrain.Chunk(x, z)
|
||||
w.chunks[key] = c
|
||||
return c
|
||||
}
|
||||
func (w *World) neighbors(pos p.Vec3) []p.Chunk {
|
||||
x, z := ChunkCoord(pos.X, w.Balance.ChunkSize), ChunkCoord(pos.Z, w.Balance.ChunkSize)
|
||||
chunks := make([]p.Chunk, 0, 9)
|
||||
for dz := -1; dz <= 1; dz++ {
|
||||
for dx := -1; dx <= 1; dx++ {
|
||||
chunks = append(chunks, w.chunk(x+dx, z+dz))
|
||||
}
|
||||
}
|
||||
return chunks
|
||||
}
|
||||
func (w *World) Intent(id string, i p.Intent) error {
|
||||
c := w.Characters[id]
|
||||
if c == nil || !c.Online || c.View.Entity.State != "alive" || w.Phase == "won" || w.Phase == "lost" {
|
||||
return errors.New("character cannot act")
|
||||
}
|
||||
if i.Seq <= c.View.ACK || i.Seq > c.View.ACK+10000 {
|
||||
return errors.New("invalid input sequence")
|
||||
}
|
||||
if math.IsNaN(i.X) || math.IsNaN(i.Z) || math.IsInf(i.X, 0) || math.IsInf(i.Z, 0) || math.Abs(i.X) > 1 || math.Abs(i.Z) > 1 || len(i.Target) > 100 {
|
||||
return errors.New("invalid intent")
|
||||
}
|
||||
c.View.ACK = i.Seq
|
||||
if c.Sheltered && ((i.Op == "move" && (i.X != 0 || i.Z != 0)) || (i.Op != "move" && i.Op != "heal")) {
|
||||
c.Sheltered = false
|
||||
w.dirty = true
|
||||
}
|
||||
switch i.Op {
|
||||
case "move":
|
||||
n := math.Max(1, math.Hypot(i.X, i.Z))
|
||||
c.MoveX = i.X / n
|
||||
c.MoveZ = i.Z / n
|
||||
c.LastMove = w.now
|
||||
return nil
|
||||
case "gather":
|
||||
return w.gather(c, i.Target)
|
||||
case "craft":
|
||||
return w.craft(c, i.Target)
|
||||
case "attack":
|
||||
return w.attack(c, i.Target)
|
||||
case "heal":
|
||||
if c.View.Inventory["bandage"] < 1 || c.View.Entity.HP >= c.View.Entity.MaxHP {
|
||||
return errors.New("no bandage needed or available")
|
||||
}
|
||||
c.View.Inventory["bandage"]--
|
||||
c.View.Entity.HP = math.Min(c.View.Entity.MaxHP, c.View.Entity.HP+w.Balance.BandageHealing)
|
||||
w.dirty = true
|
||||
case "return":
|
||||
if c.ReturnPosition == nil {
|
||||
return errors.New("no keystone destination")
|
||||
}
|
||||
if math.Hypot(c.ReturnPosition.X, c.ReturnPosition.Z) > w.SafeRadius() {
|
||||
return errors.New("keystone destination has been destroyed")
|
||||
}
|
||||
c.View.Entity.Position = *c.ReturnPosition
|
||||
c.ReturnPosition = nil
|
||||
c.View.HasKeystone = false
|
||||
w.dirty = true
|
||||
case "loot":
|
||||
corpse := w.Corpses[i.Target]
|
||||
if corpse == nil || distance(c.View.Entity.Position, corpse.Entity.Position) > w.Balance.GatherRange {
|
||||
return errors.New("corpse out of reach")
|
||||
}
|
||||
for k, v := range corpse.Inventory {
|
||||
c.View.Inventory[k] += v
|
||||
}
|
||||
delete(w.Corpses, i.Target)
|
||||
w.dirty = true
|
||||
default:
|
||||
return errors.New("unknown intent")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (w *World) gather(c *Character, target string) error {
|
||||
if w.Age()-c.LastGather < w.Balance.GatherCooldown {
|
||||
return errors.New("gathering cooldown")
|
||||
}
|
||||
if until := w.Depleted[target]; until > w.Age() {
|
||||
return errors.New("resource depleted")
|
||||
}
|
||||
for _, chunk := range w.neighbors(c.View.Entity.Position) {
|
||||
for _, r := range chunk.Resources {
|
||||
if r.ID != target {
|
||||
continue
|
||||
}
|
||||
if distance(c.View.Entity.Position, r.Position) > w.Balance.GatherRange {
|
||||
return errors.New("resource out of reach")
|
||||
}
|
||||
item := map[string]string{"tree": "wood", "ore": "ore", "herb": "herb"}[r.Kind]
|
||||
if item == "" {
|
||||
return errors.New("not gatherable")
|
||||
}
|
||||
c.View.Inventory[item]++
|
||||
c.View.Skills["gathering"] += w.Balance.SkillXpPerAction
|
||||
c.LastGather = w.Age()
|
||||
w.Depleted[target] = w.Age() + w.Balance.ResourceRespawnSeconds
|
||||
w.dirty = true
|
||||
c.Message = "Gathered " + item
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return errors.New("unknown resource")
|
||||
}
|
||||
func (w *World) craft(c *Character, name string) error {
|
||||
r, ok := w.Balance.Recipes[name]
|
||||
if !ok {
|
||||
return errors.New("unknown recipe")
|
||||
}
|
||||
for k, v := range r.Inputs {
|
||||
if c.View.Inventory[k] < v {
|
||||
return errors.New("missing crafting materials")
|
||||
}
|
||||
}
|
||||
for k, v := range r.Inputs {
|
||||
c.View.Inventory[k] -= v
|
||||
}
|
||||
for k, v := range r.Outputs {
|
||||
c.View.Inventory[k] += v
|
||||
}
|
||||
c.View.Skills["crafting"] += w.Balance.SkillXpPerAction
|
||||
c.Message = "Crafted " + name
|
||||
w.dirty = true
|
||||
return nil
|
||||
}
|
||||
func (w *World) attack(c *Character, target string) error {
|
||||
if w.Age()-c.LastAttack < w.Balance.AttackCooldown {
|
||||
return errors.New("attack cooldown")
|
||||
}
|
||||
damage := w.Balance.PlayerDamage
|
||||
if c.View.Inventory["spear"] > 0 {
|
||||
damage = w.Balance.SpearDamage
|
||||
}
|
||||
if target == "boss" {
|
||||
if w.Phase != "cataclysm" || distance(c.View.Entity.Position, w.terrain.Position(0, 0)) > w.Balance.AttackRange+4 {
|
||||
return errors.New("boss out of reach")
|
||||
}
|
||||
w.BossHP = math.Max(0, w.BossHP-damage)
|
||||
if w.BossHP == 0 {
|
||||
w.Phase = "won"
|
||||
ended := w.now
|
||||
w.EndedAt = &ended
|
||||
for _, survivor := range w.Characters {
|
||||
if survivor.View.Entity.State == "alive" {
|
||||
survivor.View.Entity.State = "eligible"
|
||||
survivor.MoveX = 0
|
||||
survivor.MoveZ = 0
|
||||
survivor.Message = "The world is saved. Passage is open."
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
m := w.Mobs[target]
|
||||
if m == nil || m.Entity.HP <= 0 || distance(c.View.Entity.Position, m.Entity.Position) > w.Balance.AttackRange {
|
||||
return errors.New("target out of reach")
|
||||
}
|
||||
m.Entity.HP = math.Max(0, m.Entity.HP-damage)
|
||||
if m.Entity.HP == 0 {
|
||||
m.Entity.State = "dead"
|
||||
m.RespawnAt = w.Age() + w.Balance.MobRespawnSeconds
|
||||
c.View.Kills++
|
||||
c.View.Inventory["herb"]++
|
||||
}
|
||||
}
|
||||
c.LastAttack = w.Age()
|
||||
c.View.Skills["combat"] += w.Balance.SkillXpPerAction
|
||||
w.dirty = true
|
||||
return nil
|
||||
}
|
||||
func (w *World) kill(c *Character, reason string) {
|
||||
if c.View.Entity.State != "alive" {
|
||||
return
|
||||
}
|
||||
e := c.View.Entity
|
||||
e.ID = "corpse:" + e.ID
|
||||
e.Kind = "corpse"
|
||||
e.State = "dead"
|
||||
e.HP = 0
|
||||
w.Corpses[e.ID] = &Corpse{Entity: e, Inventory: c.View.Inventory}
|
||||
c.View.Inventory = map[string]int64{}
|
||||
c.View.Entity.HP = 0
|
||||
c.View.Entity.State = "dead"
|
||||
c.MoveX = 0
|
||||
c.MoveZ = 0
|
||||
c.ReturnPosition = nil
|
||||
c.View.HasKeystone = false
|
||||
c.Message = reason
|
||||
w.dirty = true
|
||||
}
|
||||
func (w *World) Advance(now time.Time, dt float64) {
|
||||
playedDT := math.Max(0, dt)
|
||||
w.now = now
|
||||
w.Tick++
|
||||
dt = math.Max(0, math.Min(dt, 0.25))
|
||||
if w.Phase == "won" || w.Phase == "lost" {
|
||||
return
|
||||
}
|
||||
if w.Phase == "gathering" && w.Age() >= w.Balance.SeasonSeconds {
|
||||
w.Phase = "cataclysm"
|
||||
w.dirty = true
|
||||
}
|
||||
active := map[string]bool{}
|
||||
for _, c := range w.Characters {
|
||||
if c.View.Entity.State != "alive" {
|
||||
continue
|
||||
}
|
||||
w.resetDay(c)
|
||||
if c.Online {
|
||||
midnight := time.Date(now.UTC().Year(), now.UTC().Month(), now.UTC().Day(), 0, 0, 0, 0, time.UTC)
|
||||
c.DailySeconds += math.Min(playedDT, now.Sub(midnight).Seconds())
|
||||
c.View.PlayedSeconds += playedDT
|
||||
c.View.RemainingSeconds = math.Max(0, w.Balance.DailyPlaySeconds-c.DailySeconds)
|
||||
if c.View.RemainingSeconds <= 0 {
|
||||
pos := c.View.Entity.Position
|
||||
c.ReturnPosition = &pos
|
||||
c.Sheltered = true
|
||||
c.View.HasKeystone = true
|
||||
c.View.Entity.Position = w.terrain.Position(0, 0)
|
||||
c.View.Entity.HP = math.Min(c.View.Entity.MaxHP, math.Max(50, c.View.Entity.HP))
|
||||
c.Online = false
|
||||
c.MoveX = 0
|
||||
c.MoveZ = 0
|
||||
c.Message = "Daily limit reached. Your keystone is ready for tomorrow."
|
||||
w.dirty = true
|
||||
}
|
||||
}
|
||||
if c.Online {
|
||||
if now.Sub(c.LastMove) > 250*time.Millisecond {
|
||||
c.MoveX = 0
|
||||
c.MoveZ = 0
|
||||
}
|
||||
pos := c.View.Entity.Position
|
||||
nx, nz := pos.X+c.MoveX*w.Balance.PlayerSpeed*dt, pos.Z+c.MoveZ*w.Balance.PlayerSpeed*dt
|
||||
if math.Hypot(nx, nz) < w.Balance.WorldRadius {
|
||||
c.View.Entity.Position = w.terrain.Position(nx, nz)
|
||||
}
|
||||
for _, ch := range w.neighbors(c.View.Entity.Position) {
|
||||
active[ch.Key] = true
|
||||
w.ensureMob(ch)
|
||||
}
|
||||
}
|
||||
if w.Phase == "cataclysm" && math.Hypot(c.View.Entity.Position.X, c.View.Entity.Position.Z) > w.SafeRadius() {
|
||||
c.View.Entity.HP -= w.Balance.StormDamagePerSecond * dt
|
||||
w.dirty = true
|
||||
}
|
||||
if c.View.Entity.HP <= 0 {
|
||||
w.kill(c, "The encroaching ruin claimed this character.")
|
||||
}
|
||||
}
|
||||
w.updateMobs(active, dt)
|
||||
if w.Phase == "cataclysm" {
|
||||
if w.Age()-w.BossLastAttack >= w.Balance.BossCooldown {
|
||||
for _, c := range w.Characters {
|
||||
if c.Online && !c.Sheltered && c.View.Entity.State == "alive" && distance(c.View.Entity.Position, w.terrain.Position(0, 0)) <= w.Balance.BossRange {
|
||||
c.View.Entity.HP -= w.Balance.BossDamage
|
||||
w.dirty = true
|
||||
if c.View.Entity.HP <= 0 {
|
||||
w.kill(c, "The Harbinger ended this character's journey.")
|
||||
}
|
||||
}
|
||||
}
|
||||
w.BossLastAttack = w.Age()
|
||||
}
|
||||
alive := 0
|
||||
for _, c := range w.Characters {
|
||||
if c.View.Entity.State == "alive" {
|
||||
alive++
|
||||
}
|
||||
}
|
||||
if w.SafeRadius() <= 0 || (len(w.Characters) > 0 && alive == 0) {
|
||||
for _, c := range w.Characters {
|
||||
w.kill(c, "The world has been destroyed.")
|
||||
}
|
||||
w.Phase = "lost"
|
||||
ended := w.now
|
||||
w.EndedAt = &ended
|
||||
w.dirty = true
|
||||
}
|
||||
}
|
||||
// Keep CPU/GPU working sets bounded to subscribed chunks. Persistent deltas survive eviction.
|
||||
for key := range w.chunks {
|
||||
if !active[key] {
|
||||
delete(w.chunks, key)
|
||||
}
|
||||
}
|
||||
for key, until := range w.Depleted {
|
||||
if until <= w.Age() {
|
||||
delete(w.Depleted, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
func (w *World) ensureMob(ch p.Chunk) {
|
||||
id := "m:" + ch.Key
|
||||
if _, ok := w.Mobs[id]; ok {
|
||||
return
|
||||
}
|
||||
x, z := (float64(ch.X)+0.55)*ch.Size, (float64(ch.Z)+0.55)*ch.Size
|
||||
if math.Hypot(x, z) > w.Balance.WorldRadius {
|
||||
return
|
||||
}
|
||||
hp := w.Balance.MobHp * (1 + w.Age()/86400*w.Balance.MobScalePerDay)
|
||||
w.Mobs[id] = &Mob{Entity: p.Entity{ID: id, Kind: "sentinel", Name: "Ash sentinel", Position: w.terrain.Position(x, z), HP: hp, MaxHP: hp, State: "alive"}, HomeX: int(ch.X), HomeZ: int(ch.Z)}
|
||||
}
|
||||
func (w *World) updateMobs(active map[string]bool, dt float64) {
|
||||
for id, m := range w.Mobs {
|
||||
key := Key(m.HomeX, m.HomeZ)
|
||||
if !active[key] {
|
||||
if m.Entity.HP == m.Entity.MaxHP || (m.Entity.HP <= 0 && w.Age() >= m.RespawnAt) {
|
||||
delete(w.Mobs, id)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if m.Entity.HP <= 0 {
|
||||
if w.Age() >= m.RespawnAt {
|
||||
m.Entity.HP = w.Balance.MobHp * (1 + w.Age()/86400*w.Balance.MobScalePerDay)
|
||||
m.Entity.MaxHP = m.Entity.HP
|
||||
m.Entity.State = "alive"
|
||||
}
|
||||
continue
|
||||
}
|
||||
var target *Character
|
||||
nearest := w.Balance.MobAggroRange
|
||||
for _, c := range w.Characters {
|
||||
if !c.Online || c.View.Entity.State != "alive" || c.Sheltered {
|
||||
continue
|
||||
}
|
||||
d := distance(c.View.Entity.Position, m.Entity.Position)
|
||||
if d < nearest {
|
||||
nearest = d
|
||||
target = c
|
||||
}
|
||||
}
|
||||
if target == nil {
|
||||
continue
|
||||
}
|
||||
if nearest <= w.Balance.MobAttackRange {
|
||||
if w.Age()-m.LastAttack >= w.Balance.MobCooldown {
|
||||
target.View.Entity.HP -= w.Balance.MobDamage * (1 + w.Age()/86400*w.Balance.MobScalePerDay)
|
||||
m.LastAttack = w.Age()
|
||||
w.dirty = true
|
||||
if target.View.Entity.HP <= 0 {
|
||||
w.kill(target, "An ash sentinel ended this character's journey.")
|
||||
}
|
||||
}
|
||||
} else {
|
||||
pos, to := m.Entity.Position, target.View.Entity.Position
|
||||
step := math.Min(nearest, w.Balance.MobSpeed*dt)
|
||||
x, z := pos.X+(to.X-pos.X)/nearest*step, pos.Z+(to.Z-pos.Z)/nearest*step
|
||||
if ChunkCoord(x, w.Balance.ChunkSize) == m.HomeX && ChunkCoord(z, w.Balance.ChunkSize) == m.HomeZ {
|
||||
m.Entity.Position = w.terrain.Position(x, z)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
func (w *World) Snapshot(id string, known map[string]bool) p.Snapshot {
|
||||
c := w.Characters[id]
|
||||
s := p.Snapshot{Type: "snapshot", Version: 1, Tick: w.Tick, World: w.Info(), Self: c.View, Message: c.Message, Entities: []p.Entity{}, Chunks: []p.Chunk{}, ChunkKeys: []string{}, UnavailableResources: []string{}}
|
||||
allowed := map[string]bool{}
|
||||
for _, ch := range w.neighbors(c.View.Entity.Position) {
|
||||
allowed[ch.Key] = true
|
||||
s.ChunkKeys = append(s.ChunkKeys, ch.Key)
|
||||
if !known[ch.Key] {
|
||||
s.Chunks = append(s.Chunks, ch)
|
||||
}
|
||||
for _, r := range ch.Resources {
|
||||
if w.Depleted[r.ID] > w.Age() {
|
||||
s.UnavailableResources = append(s.UnavailableResources, r.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
visible := func(pos p.Vec3) bool {
|
||||
return allowed[Key(ChunkCoord(pos.X, w.Balance.ChunkSize), ChunkCoord(pos.Z, w.Balance.ChunkSize))]
|
||||
}
|
||||
for _, other := range w.Characters {
|
||||
if other.View.Entity.ID != id && other.Online && other.View.Entity.State != "dead" && visible(other.View.Entity.Position) {
|
||||
s.Entities = append(s.Entities, other.View.Entity)
|
||||
}
|
||||
}
|
||||
for _, m := range w.Mobs {
|
||||
if m.Entity.HP > 0 && visible(m.Entity.Position) {
|
||||
s.Entities = append(s.Entities, m.Entity)
|
||||
}
|
||||
}
|
||||
for _, corpse := range w.Corpses {
|
||||
if visible(corpse.Entity.Position) {
|
||||
s.Entities = append(s.Entities, corpse.Entity)
|
||||
}
|
||||
}
|
||||
if w.Phase == "cataclysm" && visible(w.terrain.Position(0, 0)) {
|
||||
s.Entities = append(s.Entities, p.Entity{ID: "boss", Kind: "boss", Name: "The Harbinger", HP: w.BossHP, MaxHP: w.Balance.BossHp, Position: w.terrain.Position(0, 0), State: "alive"})
|
||||
}
|
||||
sort.Slice(s.Entities, func(i, j int) bool { return s.Entities[i].ID < s.Entities[j].ID })
|
||||
return s
|
||||
}
|
||||
func (w *World) TriggerBoss() error {
|
||||
if w.Phase != "gathering" {
|
||||
return fmt.Errorf("boss event already started")
|
||||
}
|
||||
w.CreatedAt = w.now.Add(-time.Duration(w.Balance.SeasonSeconds * float64(time.Second)))
|
||||
w.Phase = "cataclysm"
|
||||
w.dirty = true
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
package game
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"math"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"aeternalis/server/content"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
)
|
||||
|
||||
func fixture(t *testing.T) (*World, *Character) {
|
||||
t.Helper()
|
||||
b, err := content.Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
w := New("test", 123, time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC), b)
|
||||
c, err := w.Join("account", "Traveler")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = w.Connect(c.View.Entity.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return w, c
|
||||
}
|
||||
func TestTerrainDeterministicAndSeamless(t *testing.T) {
|
||||
b, _ := content.Load()
|
||||
a := NewTerrain(123, b)
|
||||
other := NewTerrain(456, b)
|
||||
if !reflect.DeepEqual(a.Chunk(-1, 0), NewTerrain(123, b).Chunk(-1, 0)) {
|
||||
t.Fatal("same seed changed")
|
||||
}
|
||||
if reflect.DeepEqual(a.Chunk(0, 0), other.Chunk(0, 0)) {
|
||||
t.Fatal("different seeds identical")
|
||||
}
|
||||
left, right := a.Chunk(-1, 0), a.Chunk(0, 0)
|
||||
n := b.TerrainResolution + 1
|
||||
for z := 0; z < n; z++ {
|
||||
if left.Heights[z*n+n-1] != right.Heights[z*n] {
|
||||
t.Fatal("chunk seam")
|
||||
}
|
||||
}
|
||||
if ChunkCoord(-0.1, 128) != -1 || ChunkCoord(-128, 128) != -1 {
|
||||
t.Fatal("negative coordinates")
|
||||
}
|
||||
for _, r := range left.Resources {
|
||||
if math.Abs(r.Position.Y-a.Height(r.Position.X, r.Position.Z)) > 1e-8 {
|
||||
t.Fatal("floating resource")
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestMovementAuthorityAndInterest(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
id := c.View.Entity.ID
|
||||
w.now = w.now.Add(time.Second)
|
||||
for _, intent := range []p.Intent{{Op: "move", Seq: 1, X: 2}, {Op: "move", Seq: 1, X: math.NaN()}, {Op: "move", Seq: 1, Z: math.Inf(1)}} {
|
||||
if w.Intent(id, intent) == nil {
|
||||
t.Fatal("invalid movement accepted")
|
||||
}
|
||||
}
|
||||
if err := w.Intent(id, p.Intent{Op: "move", Seq: 1, X: 1, Z: 1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := c.View.Entity.Position
|
||||
w.Advance(w.now.Add(50*time.Millisecond), 0.05)
|
||||
if got := distance(before, c.View.Entity.Position); math.Abs(got-w.Balance.PlayerSpeed*0.05) > 1e-8 {
|
||||
t.Fatalf("diagonal speed: %v", got)
|
||||
}
|
||||
if w.Intent(id, p.Intent{Op: "move", Seq: 1}) == nil {
|
||||
t.Fatal("replayed sequence")
|
||||
}
|
||||
s := w.Snapshot(id, map[string]bool{})
|
||||
if len(s.Chunks) != 9 || len(s.ChunkKeys) != 9 {
|
||||
t.Fatal("interest area not 3x3")
|
||||
}
|
||||
known := map[string]bool{}
|
||||
for _, key := range s.ChunkKeys {
|
||||
known[key] = true
|
||||
}
|
||||
if len(w.Snapshot(id, known).Chunks) != 0 {
|
||||
t.Fatal("resent known terrain")
|
||||
}
|
||||
far, _ := w.Join("far", "Far")
|
||||
far.View.Entity.Position = w.terrain.Position(700, 700)
|
||||
far.Online = true
|
||||
for _, e := range w.Snapshot(id, known).Entities {
|
||||
if e.ID == far.View.Entity.ID {
|
||||
t.Fatal("remote entity leaked outside interest")
|
||||
}
|
||||
}
|
||||
w.Advance(w.now.Add(time.Second), 0.05)
|
||||
if c.MoveX != 0 || c.MoveZ != 0 {
|
||||
t.Fatal("stale input did not stop")
|
||||
}
|
||||
}
|
||||
func TestGatherCraftAndPermanentDeath(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
id := c.View.Entity.ID
|
||||
w.now = w.now.Add(2 * time.Second)
|
||||
if w.Intent(id, p.Intent{Op: "gather", Seq: 1, Target: "arrival:ore"}) == nil {
|
||||
t.Fatal("remote gather accepted")
|
||||
}
|
||||
c.View.Entity.Position = w.terrain.Position(17, 12)
|
||||
if err := w.Intent(id, p.Intent{Op: "gather", Seq: 2, Target: "arrival:ore"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.View.Inventory["ore"] != 1 {
|
||||
t.Fatal("gather failed")
|
||||
}
|
||||
if w.Intent(id, p.Intent{Op: "gather", Seq: 3, Target: "arrival:ore"}) == nil {
|
||||
t.Fatal("double gather")
|
||||
}
|
||||
if w.Intent(id, p.Intent{Op: "craft", Seq: 4, Target: "spear"}) == nil {
|
||||
t.Fatal("free craft")
|
||||
}
|
||||
c.View.Inventory["wood"] = 3
|
||||
c.View.Inventory["ore"] = 2
|
||||
if err := w.Intent(id, p.Intent{Op: "craft", Seq: 5, Target: "spear"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.View.Inventory["spear"] != 1 || c.View.Inventory["wood"] != 0 || c.View.Inventory["ore"] != 0 {
|
||||
t.Fatal("recipe not atomic")
|
||||
}
|
||||
w.kill(c, "test death")
|
||||
w.Disconnect(id)
|
||||
if w.Connect(id) == nil {
|
||||
t.Fatal("dead character reconnected")
|
||||
}
|
||||
same, err := w.Join(c.Account, "Replacement")
|
||||
if err != nil || same.View.Entity.ID != id || same.View.Entity.State != "dead" {
|
||||
t.Fatal("death bypass by rejoining")
|
||||
}
|
||||
if len(c.View.Inventory) != 0 || w.Corpses["corpse:"+id].Inventory["spear"] != 1 {
|
||||
t.Fatal("corpse inventory")
|
||||
}
|
||||
raw, _ := json.Marshal(w)
|
||||
var restored World
|
||||
if err = json.Unmarshal(raw, &restored); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = restored.Restore(w.now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if restored.Connect(id) == nil {
|
||||
t.Fatal("restart resurrected character")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStaticResourcesAreNotReplicatedEverySnapshot(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
w.Depleted["arrival:ore"] = w.Age() + 60
|
||||
s := w.Snapshot(c.View.Entity.ID, map[string]bool{})
|
||||
if len(s.UnavailableResources) != 1 || s.UnavailableResources[0] != "arrival:ore" {
|
||||
t.Fatal("missing authoritative resource availability")
|
||||
}
|
||||
for _, e := range s.Entities {
|
||||
if e.Kind == "tree" || e.Kind == "ore" || e.Kind == "herb" {
|
||||
t.Fatal("static resource repeated in dynamic entity snapshot")
|
||||
}
|
||||
}
|
||||
resources := 0
|
||||
for _, ch := range s.Chunks {
|
||||
resources += len(ch.Resources)
|
||||
}
|
||||
if resources == 0 {
|
||||
t.Fatal("initial chunk does not carry resources")
|
||||
}
|
||||
}
|
||||
func TestDailyLimitAndKeystone(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
w.Balance.DailyPlaySeconds = 1
|
||||
c.DailySeconds = .9
|
||||
c.View.Entity.HP = 20
|
||||
c.View.Entity.Position = w.terrain.Position(40, 40)
|
||||
w.Advance(w.now.Add(200*time.Millisecond), .2)
|
||||
if c.Online || c.ReturnPosition == nil || !c.View.HasKeystone || c.View.Entity.HP != 50 || distance(c.View.Entity.Position, p.Vec3{}) != 0 {
|
||||
t.Fatalf("cap not enforced: %+v", c)
|
||||
}
|
||||
if w.Connect(c.View.Entity.ID) == nil {
|
||||
t.Fatal("same-day cap bypass")
|
||||
}
|
||||
w.now = w.now.Add(24 * time.Hour)
|
||||
if err := w.Connect(c.View.Entity.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "return", Seq: 1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.View.Entity.Position.X != 40 || c.ReturnPosition != nil || c.View.HasKeystone {
|
||||
t.Fatal("keystone failed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDailyBudgetUsesWallTimeDuringLag(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
w.Balance.DailyPlaySeconds = 2
|
||||
w.Advance(w.now.Add(3*time.Second), 3)
|
||||
if c.Online || c.View.RemainingSeconds != 0 {
|
||||
t.Fatal("simulation lag bypassed wall-clock play cap")
|
||||
}
|
||||
}
|
||||
|
||||
func TestKeystoneCannotGrantRoamingInvulnerability(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
c.Sheltered = true
|
||||
c.ReturnPosition = &p.Vec3{X: 40, Z: 40}
|
||||
if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "move", Seq: 1, X: 1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.Sheltered || c.ReturnPosition == nil {
|
||||
t.Fatal("leaving sanctuary must remove protection while preserving keystone")
|
||||
}
|
||||
}
|
||||
func TestBossVictoryAndCollapse(t *testing.T) {
|
||||
t.Run("victory includes offline survivors and excludes dead", func(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
dead, _ := w.Join("dead", "Dead")
|
||||
w.kill(dead, "test")
|
||||
offline, _ := w.Join("offline", "Offline")
|
||||
w.now = w.now.Add(time.Second)
|
||||
_ = w.TriggerBoss()
|
||||
w.BossHP = 1
|
||||
if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "attack", Seq: 1, Target: "boss"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w.Phase != "won" || c.View.Entity.State != "eligible" || offline.View.Entity.State != "eligible" || dead.View.Entity.State != "dead" {
|
||||
t.Fatal("incorrect survivor selection")
|
||||
}
|
||||
radius := w.SafeRadius()
|
||||
w.Advance(w.now.Add(20*24*time.Hour), .05)
|
||||
if w.SafeRadius() != radius {
|
||||
t.Fatal("world kept collapsing after boss death")
|
||||
}
|
||||
if c.View.Entity.State != "eligible" {
|
||||
t.Fatal("victory not terminal")
|
||||
}
|
||||
if w.Intent(c.View.Entity.ID, p.Intent{Op: "move", Seq: 2, X: 1}) == nil {
|
||||
t.Fatal("survivor mutated frozen world")
|
||||
}
|
||||
})
|
||||
t.Run("collapse kills offline and capped characters", func(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
c.Online = false
|
||||
c.ReturnPosition = &p.Vec3{X: 40}
|
||||
w.Advance(w.CreatedAt.Add(time.Duration((w.Balance.SeasonSeconds+w.Balance.CollapseSeconds+1)*float64(time.Second))), .05)
|
||||
if w.Phase != "lost" || c.View.Entity.State != "dead" {
|
||||
t.Fatal("world destruction bypass")
|
||||
}
|
||||
})
|
||||
t.Run("boss schedule survives downtime", func(t *testing.T) {
|
||||
w, _ := fixture(t)
|
||||
w.Advance(w.CreatedAt.Add(7*24*time.Hour+5*time.Minute), .05)
|
||||
if w.Phase != "cataclysm" || w.SafeRadius() >= w.Balance.WorldRadius {
|
||||
t.Fatal("deadline did not advance")
|
||||
}
|
||||
})
|
||||
}
|
||||
func TestSpawnAndTransferPreserveBudget(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
other, _ := w.Join("other", "Other")
|
||||
if distance(c.View.Entity.Position, other.View.Entity.Position) < w.Balance.SpawnSeparation {
|
||||
t.Fatal("spawns overlap")
|
||||
}
|
||||
c.View.Entity.State = "eligible"
|
||||
c.DailySeconds = 123
|
||||
c.View.PlayedSeconds = 456
|
||||
c.View.Skills["combat"] = 9
|
||||
c.View.Inventory["spear"] = 1
|
||||
next := New("next", 999, w.now, w.Balance)
|
||||
if err := next.Import(c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.DailySeconds != 123 || c.View.PlayedSeconds != 456 || c.View.Skills["combat"] != 9 || c.View.Inventory["spear"] != 1 {
|
||||
t.Fatal("transfer changed progress or budget")
|
||||
}
|
||||
if err := next.Import(c); err == nil {
|
||||
t.Fatal("duplicate import")
|
||||
}
|
||||
}
|
||||
func BenchmarkSnapshot100Players(b *testing.B) {
|
||||
balance, _ := content.Load()
|
||||
w := New("bench", 123, time.Now(), balance)
|
||||
ids := []string{}
|
||||
for i := 0; i < 100; i++ {
|
||||
c, err := w.Join(ID(), "Traveler")
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
c.Online = true
|
||||
ids = append(ids, c.View.Entity.ID)
|
||||
}
|
||||
w.Advance(time.Now(), .05)
|
||||
known := map[string]bool{}
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
s := w.Snapshot(ids[i%len(ids)], known)
|
||||
if _, err := json.Marshal(s); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
// Code generated from schemas/protocol.json. DO NOT EDIT.
|
||||
package protocol
|
||||
|
||||
type Protocol struct {
|
||||
Intent Intent `json:"intent"`
|
||||
Snapshot Snapshot `json:"snapshot"`
|
||||
}
|
||||
|
||||
type Intent struct {
|
||||
Op string `json:"op"`
|
||||
Seq int64 `json:"seq"`
|
||||
Target string `json:"target"`
|
||||
X float64 `json:"x"`
|
||||
Z float64 `json:"z"`
|
||||
}
|
||||
|
||||
type Snapshot struct {
|
||||
ChunkKeys []string `json:"chunkKeys"`
|
||||
Chunks []Chunk `json:"chunks"`
|
||||
Entities []Entity `json:"entities"`
|
||||
Message string `json:"message"`
|
||||
Self Character `json:"self"`
|
||||
Tick int64 `json:"tick"`
|
||||
Type string `json:"type"`
|
||||
UnavailableResources []string `json:"unavailableResources"`
|
||||
Version int64 `json:"version"`
|
||||
World WorldInfo `json:"world"`
|
||||
}
|
||||
|
||||
type Chunk struct {
|
||||
Biome string `json:"biome"`
|
||||
Heights []float64 `json:"heights"`
|
||||
Key string `json:"key"`
|
||||
Resolution int64 `json:"resolution"`
|
||||
Resources []Entity `json:"resources"`
|
||||
Size float64 `json:"size"`
|
||||
X int64 `json:"x"`
|
||||
Z int64 `json:"z"`
|
||||
}
|
||||
|
||||
type Entity struct {
|
||||
HP float64 `json:"hp"`
|
||||
ID string `json:"id"`
|
||||
Kind string `json:"kind"`
|
||||
MaxHP float64 `json:"maxHp"`
|
||||
Name string `json:"name"`
|
||||
Position Vec3 `json:"position"`
|
||||
State string `json:"state"`
|
||||
}
|
||||
|
||||
type Vec3 struct {
|
||||
X float64 `json:"x"`
|
||||
Y float64 `json:"y"`
|
||||
Z float64 `json:"z"`
|
||||
}
|
||||
|
||||
type Character struct {
|
||||
ACK int64 `json:"ack"`
|
||||
Entity Entity `json:"entity"`
|
||||
HasKeystone bool `json:"hasKeystone"`
|
||||
Inventory map[string]int64 `json:"inventory"`
|
||||
Kills int64 `json:"kills"`
|
||||
PlayedSeconds float64 `json:"playedSeconds"`
|
||||
RemainingSeconds float64 `json:"remainingSeconds"`
|
||||
Skills map[string]int64 `json:"skills"`
|
||||
}
|
||||
|
||||
type WorldInfo struct {
|
||||
AgeSeconds float64 `json:"ageSeconds"`
|
||||
BossHP float64 `json:"bossHp"`
|
||||
BossInSeconds float64 `json:"bossInSeconds"`
|
||||
BossMaxHP float64 `json:"bossMaxHp"`
|
||||
Capacity int64 `json:"capacity"`
|
||||
CollapseInSeconds float64 `json:"collapseInSeconds"`
|
||||
ID string `json:"id"`
|
||||
Online int64 `json:"online"`
|
||||
Phase string `json:"phase"`
|
||||
Radius float64 `json:"radius"`
|
||||
SafeRadius float64 `json:"safeRadius"`
|
||||
Seed int64 `json:"seed"`
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"aeternalis/server/internal/game"
|
||||
_ "github.com/jackc/pgx/v5/stdlib"
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
var ErrOwnership = errors.New("world ownership or revision lost")
|
||||
|
||||
type DB struct {
|
||||
sql *sql.DB
|
||||
postgres bool
|
||||
}
|
||||
type Lease struct {
|
||||
DB *DB
|
||||
WorldID string
|
||||
Owner string
|
||||
Revision int64
|
||||
}
|
||||
type Passage struct {
|
||||
CharacterID string `json:"characterId"`
|
||||
SourceWorld string `json:"sourceWorld"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
func Open(ctx context.Context, dsn string) (*DB, error) {
|
||||
postgres := strings.HasPrefix(dsn, "postgres://") || strings.HasPrefix(dsn, "postgresql://")
|
||||
driver := "sqlite"
|
||||
if postgres {
|
||||
driver = "pgx"
|
||||
}
|
||||
conn, err := sql.Open(driver, dsn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
conn.SetMaxOpenConns(8)
|
||||
if !postgres {
|
||||
conn.SetMaxOpenConns(1)
|
||||
}
|
||||
db := &DB{conn, postgres}
|
||||
if err = conn.PingContext(ctx); err != nil {
|
||||
conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
if !postgres {
|
||||
if _, err = conn.ExecContext(ctx, "PRAGMA journal_mode=WAL"); err != nil {
|
||||
conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
_, _ = conn.ExecContext(ctx, "PRAGMA busy_timeout=5000")
|
||||
}
|
||||
for _, stmt := range []string{
|
||||
`CREATE TABLE IF NOT EXISTS worlds(id TEXT PRIMARY KEY, owner TEXT NOT NULL, lease_until BIGINT NOT NULL, revision BIGINT NOT NULL, snapshot TEXT NOT NULL)`,
|
||||
`CREATE TABLE IF NOT EXISTS passages(character_id TEXT PRIMARY KEY, account_id TEXT NOT NULL, source_world TEXT NOT NULL, character TEXT NOT NULL, claimed_world TEXT)`,
|
||||
`CREATE INDEX IF NOT EXISTS passages_account ON passages(account_id)`,
|
||||
`CREATE TABLE IF NOT EXISTS sessions(token_hash TEXT PRIMARY KEY, account_id TEXT NOT NULL, expires BIGINT NOT NULL)`,
|
||||
`CREATE INDEX IF NOT EXISTS sessions_expiry ON sessions(expires)`,
|
||||
} {
|
||||
if _, err = conn.ExecContext(ctx, stmt); err != nil {
|
||||
conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return db, nil
|
||||
}
|
||||
func (d *DB) Close() error { return d.sql.Close() }
|
||||
func (d *DB) q(query string) string {
|
||||
if !d.postgres {
|
||||
return query
|
||||
}
|
||||
i := 0
|
||||
var b strings.Builder
|
||||
for _, c := range query {
|
||||
if c == '?' {
|
||||
i++
|
||||
fmt.Fprintf(&b, "$%d", i)
|
||||
} else {
|
||||
b.WriteRune(c)
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
func (d *DB) now() string {
|
||||
if d.postgres {
|
||||
return "CAST(EXTRACT(EPOCH FROM clock_timestamp()) AS BIGINT)"
|
||||
}
|
||||
return "unixepoch()"
|
||||
}
|
||||
func (d *DB) Acquire(ctx context.Context, w *game.World) (*Lease, []byte, error) {
|
||||
data, err := json.Marshal(w)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
tx, err := d.sql.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
_, err = tx.ExecContext(ctx, d.q(`INSERT INTO worlds(id,owner,lease_until,revision,snapshot) VALUES(?,'',0,0,?) ON CONFLICT(id) DO NOTHING`), w.ID, string(data))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
owner := game.ID()
|
||||
result, err := tx.ExecContext(ctx, d.q(`UPDATE worlds SET owner=?,lease_until=`+d.now()+`+30 WHERE id=? AND (owner='' OR lease_until<`+d.now()+`)`), owner, w.ID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
n, _ := result.RowsAffected()
|
||||
if n != 1 {
|
||||
return nil, nil, ErrOwnership
|
||||
}
|
||||
var snapshot string
|
||||
var revision int64
|
||||
if err = tx.QueryRowContext(ctx, d.q(`SELECT revision,snapshot FROM worlds WHERE id=?`), w.ID).Scan(&revision, &snapshot); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if err = tx.Commit(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return &Lease{d, w.ID, owner, revision}, []byte(snapshot), nil
|
||||
}
|
||||
func (l *Lease) Save(ctx context.Context, w *game.World, claimID string) error {
|
||||
data, err := json.Marshal(w)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d := l.DB
|
||||
tx, err := d.sql.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
result, err := tx.ExecContext(ctx, d.q(`UPDATE worlds SET snapshot=?,revision=revision+1,lease_until=`+d.now()+`+30 WHERE id=? AND owner=? AND revision=? AND lease_until>=`+d.now()), string(data), l.WorldID, l.Owner, l.Revision)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, _ := result.RowsAffected()
|
||||
if n != 1 {
|
||||
return ErrOwnership
|
||||
}
|
||||
if claimID != "" {
|
||||
c := w.Characters[claimID]
|
||||
if c == nil {
|
||||
return errors.New("claimed character absent from target")
|
||||
}
|
||||
result, err = tx.ExecContext(ctx, d.q(`UPDATE passages SET claimed_world=? WHERE character_id=? AND account_id=? AND claimed_world IS NULL AND source_world<>?`), w.ID, claimID, c.Account, w.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, _ = result.RowsAffected()
|
||||
if n != 1 {
|
||||
return errors.New("passage already redeemed or unavailable")
|
||||
}
|
||||
}
|
||||
if w.Phase == "won" {
|
||||
for _, c := range w.Characters {
|
||||
if c.View.Entity.State != "eligible" {
|
||||
continue
|
||||
}
|
||||
encoded, err := json.Marshal(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.ExecContext(ctx, d.q(`INSERT INTO passages(character_id,account_id,source_world,character) VALUES(?,?,?,?) ON CONFLICT(character_id) DO UPDATE SET source_world=excluded.source_world,character=excluded.character,claimed_world=NULL WHERE passages.claimed_world=excluded.source_world`), c.View.Entity.ID, c.Account, w.ID, string(encoded))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
if err = tx.Commit(); err != nil {
|
||||
return err
|
||||
}
|
||||
l.Revision++
|
||||
w.Saved()
|
||||
return nil
|
||||
}
|
||||
func (l *Lease) Release(ctx context.Context) error {
|
||||
_, err := l.DB.sql.ExecContext(ctx, l.DB.q(`UPDATE worlds SET owner='',lease_until=0 WHERE id=? AND owner=?`), l.WorldID, l.Owner)
|
||||
return err
|
||||
}
|
||||
func (d *DB) Passages(ctx context.Context, account string) ([]Passage, error) {
|
||||
rows, err := d.sql.QueryContext(ctx, d.q(`SELECT character_id,source_world,character FROM passages WHERE account_id=? AND claimed_world IS NULL`), account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []Passage{}
|
||||
for rows.Next() {
|
||||
var p Passage
|
||||
var raw string
|
||||
if err = rows.Scan(&p.CharacterID, &p.SourceWorld, &raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var c game.Character
|
||||
if err = json.Unmarshal([]byte(raw), &c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p.Name = c.View.Entity.Name
|
||||
out = append(out, p)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
func (d *DB) ReadPassage(ctx context.Context, id, account string) (*game.Character, error) {
|
||||
var raw string
|
||||
err := d.sql.QueryRowContext(ctx, d.q(`SELECT character FROM passages WHERE character_id=? AND account_id=? AND claimed_world IS NULL`), id, account).Scan(&raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var c game.Character
|
||||
if err = json.Unmarshal([]byte(raw), &c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &c, nil
|
||||
}
|
||||
func (d *DB) CreateSession(ctx context.Context, hash, account string) error {
|
||||
tx, err := d.sql.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if _, err = tx.ExecContext(ctx, `DELETE FROM sessions WHERE expires<`+d.now()); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, d.q(`INSERT INTO sessions(token_hash,account_id,expires) VALUES(?,?,`+d.now()+`+86400)`), hash, account); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
func (d *DB) Session(ctx context.Context, hash string) (string, error) {
|
||||
var account string
|
||||
err := d.sql.QueryRowContext(ctx, d.q(`SELECT account_id FROM sessions WHERE token_hash=? AND expires>`+d.now()), hash).Scan(&account)
|
||||
return account, err
|
||||
}
|
||||
func (d *DB) DeleteSession(ctx context.Context, hash string) error {
|
||||
_, err := d.sql.ExecContext(ctx, d.q(`DELETE FROM sessions WHERE token_hash=?`), hash)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"aeternalis/server/content"
|
||||
"aeternalis/server/internal/game"
|
||||
)
|
||||
|
||||
func TestStoreLifecycle(t *testing.T) {
|
||||
runStoreTests(t, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "world.db")))
|
||||
}
|
||||
|
||||
func TestConcurrentPassageRedemption(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db, err := Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "race.db")))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
b, _ := content.Load()
|
||||
now := time.Now().UTC()
|
||||
source := game.New("source", 1, now, b)
|
||||
lease, _, err := db.Acquire(ctx, source)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c, _ := source.Join("account", "Survivor")
|
||||
c.View.Entity.State = "eligible"
|
||||
source.Phase = "won"
|
||||
if err = lease.Save(ctx, source, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
targets := []*game.World{game.New("target-a", 2, now, b), game.New("target-b", 3, now, b)}
|
||||
leases := make([]*Lease, 2)
|
||||
for i, w := range targets {
|
||||
leases[i], _, err = db.Acquire(ctx, w)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
copy, err := db.ReadPassage(ctx, c.View.Entity.ID, c.Account)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = w.Import(copy); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
results := make(chan error, 2)
|
||||
for i := range targets {
|
||||
wg.Add(1)
|
||||
go func(i int) { defer wg.Done(); results <- leases[i].Save(ctx, targets[i], c.View.Entity.ID) }(i)
|
||||
}
|
||||
wg.Wait()
|
||||
close(results)
|
||||
successes := 0
|
||||
for err := range results {
|
||||
if err == nil {
|
||||
successes++
|
||||
}
|
||||
}
|
||||
if successes != 1 {
|
||||
t.Fatalf("expected one successful redemption, got %d", successes)
|
||||
}
|
||||
durableCopies := 0
|
||||
for _, w := range targets {
|
||||
var raw string
|
||||
if err := db.sql.QueryRowContext(ctx, db.q("SELECT snapshot FROM worlds WHERE id=?"), w.ID).Scan(&raw); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var restored game.World
|
||||
if err := json.Unmarshal([]byte(raw), &restored); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if restored.Characters[c.View.Entity.ID] != nil {
|
||||
durableCopies++
|
||||
}
|
||||
}
|
||||
if durableCopies != 1 {
|
||||
t.Fatal("failed redemption left a durable duplicate")
|
||||
}
|
||||
}
|
||||
func TestPostgresLifecycle(t *testing.T) {
|
||||
dsn := os.Getenv("TEST_DATABASE_URL")
|
||||
if dsn == "" {
|
||||
t.Skip("TEST_DATABASE_URL not configured")
|
||||
}
|
||||
runStoreTests(t, dsn)
|
||||
}
|
||||
func runStoreTests(t *testing.T, dsn string) {
|
||||
ctx := context.Background()
|
||||
db, err := Open(ctx, dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
balance, _ := content.Load()
|
||||
prefix := game.ID()
|
||||
now := time.Now().UTC()
|
||||
source := game.New(prefix+"-source", 123, now, balance)
|
||||
lease, _, err := db.Acquire(ctx, source)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err = db.Acquire(ctx, source); err == nil {
|
||||
t.Fatal("two simultaneous world owners")
|
||||
}
|
||||
c, _ := source.Join("account:"+prefix, "Traveler")
|
||||
c.View.Inventory["spear"] = 1
|
||||
c.DailySeconds = 123
|
||||
c.View.Entity.State = "eligible"
|
||||
source.Phase = "won"
|
||||
if err = lease.Save(ctx, source, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = lease.Save(ctx, source, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
passages, err := db.Passages(ctx, c.Account)
|
||||
if err != nil || len(passages) != 1 {
|
||||
t.Fatalf("idempotent survivor grant %v %v", passages, err)
|
||||
}
|
||||
if _, err = db.ReadPassage(ctx, c.View.Entity.ID, "attacker"); err == nil {
|
||||
t.Fatal("another account stole transfer")
|
||||
}
|
||||
target := game.New(prefix+"-target", 456, now, balance)
|
||||
targetLease, _, err := db.Acquire(ctx, target)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
survivor, err := db.ReadPassage(ctx, c.View.Entity.ID, c.Account)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = target.Import(survivor); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = targetLease.Save(ctx, target, c.View.Entity.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.ReadPassage(ctx, c.View.Entity.ID, c.Account); err == nil {
|
||||
t.Fatal("passage can be redeemed twice")
|
||||
}
|
||||
third := game.New(prefix+"-third", 789, now, balance)
|
||||
thirdLease, _, err := db.Acquire(ctx, third)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
copy := *survivor
|
||||
copy.View.Entity.State = "eligible"
|
||||
if err = third.Import(©); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = thirdLease.Save(ctx, third, c.View.Entity.ID); err == nil {
|
||||
t.Fatal("duplicate transfer committed")
|
||||
}
|
||||
if err = targetLease.Release(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
freshLease, raw, err := db.Acquire(ctx, target)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var restored game.World
|
||||
if err = json.Unmarshal(raw, &restored); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
loaded := restored.Characters[c.View.Entity.ID]
|
||||
if loaded == nil || loaded.DailySeconds != 123 || loaded.View.Inventory["spear"] != 1 {
|
||||
t.Fatal("transfer not durable")
|
||||
}
|
||||
if err = targetLease.Save(ctx, target, ""); err == nil {
|
||||
t.Fatal("stale owner wrote state")
|
||||
}
|
||||
// A subsequent victory grants a fresh passage for the same permanent character ID.
|
||||
loaded.View.Entity.State = "eligible"
|
||||
restored.Phase = "won"
|
||||
if err = freshLease.Save(ctx, &restored, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = lease.Save(ctx, source, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
passages, err = db.Passages(ctx, c.Account)
|
||||
if err != nil || len(passages) != 1 || passages[0].SourceWorld != target.ID {
|
||||
t.Fatal("old world overwrote next passage")
|
||||
}
|
||||
if err = db.CreateSession(ctx, "hash:"+prefix, c.Account); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if account, err := db.Session(ctx, "hash:"+prefix); err != nil || account != c.Account {
|
||||
t.Fatal("session roundtrip")
|
||||
}
|
||||
if err = db.DeleteSession(ctx, "hash:"+prefix); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Session(ctx, "hash:"+prefix); err == nil {
|
||||
t.Fatal("revoked session remains valid")
|
||||
}
|
||||
_ = lease.Release(ctx)
|
||||
_ = freshLease.Release(ctx)
|
||||
_ = thirdLease.Release(ctx)
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"aeternalis/server/internal/game"
|
||||
"aeternalis/server/internal/store"
|
||||
"github.com/coreos/go-oidc/v3/oidc"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
type Auth struct {
|
||||
db *store.DB
|
||||
dev bool
|
||||
base string
|
||||
oauth *oauth2.Config
|
||||
verifier *oidc.IDTokenVerifier
|
||||
mu sync.Mutex
|
||||
flows map[string]flow
|
||||
}
|
||||
type flow struct {
|
||||
verifier string
|
||||
expires time.Time
|
||||
}
|
||||
|
||||
func NewAuth(ctx context.Context, db *store.DB, dev bool, base, issuer, client, secret string) (*Auth, error) {
|
||||
a := &Auth{db: db, dev: dev, base: base, flows: map[string]flow{}}
|
||||
if dev {
|
||||
return a, nil
|
||||
}
|
||||
if !strings.HasPrefix(base, "https://") || !strings.HasPrefix(issuer, "https://") || client == "" {
|
||||
return nil, errors.New("production requires HTTPS PUBLIC_URL, OIDC_ISSUER, and OIDC_CLIENT_ID")
|
||||
}
|
||||
provider, err := oidc.NewProvider(ctx, issuer)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a.oauth = &oauth2.Config{ClientID: client, ClientSecret: secret, Endpoint: provider.Endpoint(), RedirectURL: base + "/auth/callback", Scopes: []string{oidc.ScopeOpenID}}
|
||||
a.verifier = provider.Verifier(&oidc.Config{ClientID: client})
|
||||
return a, nil
|
||||
}
|
||||
func hash(s string) string { b := sha256.Sum256([]byte(s)); return hex.EncodeToString(b[:]) }
|
||||
func (a *Auth) cookieName() string {
|
||||
if a.dev {
|
||||
return "aeternalis_session"
|
||||
}
|
||||
return "__Host-aeternalis_session"
|
||||
}
|
||||
func (a *Auth) account(r *http.Request) (string, error) {
|
||||
c, err := r.Cookie(a.cookieName())
|
||||
if err != nil || len(c.Value) != 64 {
|
||||
return "", errors.New("not authenticated")
|
||||
}
|
||||
return a.db.Session(r.Context(), hash(c.Value))
|
||||
}
|
||||
func (a *Auth) session(w http.ResponseWriter, r *http.Request, account string) error {
|
||||
token := game.ID() + game.ID()
|
||||
if err := a.db.CreateSession(r.Context(), hash(token), account); err != nil {
|
||||
return err
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{Name: a.cookieName(), Value: token, Path: "/", HttpOnly: true, Secure: !a.dev, SameSite: http.SameSiteLaxMode, MaxAge: 86400})
|
||||
return nil
|
||||
}
|
||||
func (a *Auth) login(w http.ResponseWriter, r *http.Request) {
|
||||
if a.dev {
|
||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
state := game.ID() + game.ID()
|
||||
v := oauth2.GenerateVerifier()
|
||||
a.mu.Lock()
|
||||
for key, f := range a.flows {
|
||||
if time.Now().After(f.expires) {
|
||||
delete(a.flows, key)
|
||||
}
|
||||
}
|
||||
if len(a.flows) >= 4096 {
|
||||
a.mu.Unlock()
|
||||
fail(w, 503, "login capacity reached")
|
||||
return
|
||||
}
|
||||
a.flows[state] = flow{v, time.Now().Add(10 * time.Minute)}
|
||||
a.mu.Unlock()
|
||||
http.SetCookie(w, &http.Cookie{Name: "__Host-aeternalis_login", Value: state, Path: "/", HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode, MaxAge: 600})
|
||||
http.Redirect(w, r, a.oauth.AuthCodeURL(state, oauth2.S256ChallengeOption(v), oidc.Nonce(state)), http.StatusSeeOther)
|
||||
}
|
||||
func (a *Auth) callback(w http.ResponseWriter, r *http.Request) {
|
||||
if a.dev {
|
||||
fail(w, 404, "not enabled")
|
||||
return
|
||||
}
|
||||
state := r.URL.Query().Get("state")
|
||||
cookie, err := r.Cookie("__Host-aeternalis_login")
|
||||
if err != nil || state == "" || cookie.Value != state {
|
||||
fail(w, 400, "invalid login state")
|
||||
return
|
||||
}
|
||||
a.mu.Lock()
|
||||
f, ok := a.flows[state]
|
||||
delete(a.flows, state)
|
||||
a.mu.Unlock()
|
||||
if !ok || time.Now().After(f.expires) {
|
||||
fail(w, 400, "login expired")
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
|
||||
defer cancel()
|
||||
token, err := a.oauth.Exchange(ctx, r.URL.Query().Get("code"), oauth2.VerifierOption(f.verifier))
|
||||
if err != nil {
|
||||
fail(w, 401, "login exchange failed")
|
||||
return
|
||||
}
|
||||
raw, ok := token.Extra("id_token").(string)
|
||||
if !ok {
|
||||
fail(w, 401, "identity token missing")
|
||||
return
|
||||
}
|
||||
identity, err := a.verifier.Verify(ctx, raw)
|
||||
if err != nil || identity.Nonce != state {
|
||||
fail(w, 401, "invalid identity token")
|
||||
return
|
||||
}
|
||||
if err = a.session(w, r, hash(identity.Issuer+"\x00"+identity.Subject)); err != nil {
|
||||
fail(w, 503, "session unavailable")
|
||||
return
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{Name: "__Host-aeternalis_login", Path: "/", HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode, MaxAge: -1})
|
||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||
}
|
||||
func validOrigin(r *http.Request, base string) bool {
|
||||
origin := r.Header.Get("Origin")
|
||||
if origin == "" {
|
||||
return false
|
||||
}
|
||||
expected, err := url.Parse(base)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
actual, err := url.Parse(origin)
|
||||
return err == nil && actual.Scheme == expected.Scheme && actual.Host == expected.Host && actual.Path == "" && actual.RawQuery == "" && actual.User == nil
|
||||
}
|
||||
@@ -0,0 +1,408 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"aeternalis/server/internal/game"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"github.com/coder/websocket"
|
||||
)
|
||||
|
||||
type Destination struct {
|
||||
ID string `json:"id"`
|
||||
URL string `json:"url"`
|
||||
}
|
||||
type HTTP struct {
|
||||
s *Service
|
||||
auth *Auth
|
||||
assets string
|
||||
worlds []Destination
|
||||
mu sync.Mutex
|
||||
rates map[string]*bucket
|
||||
}
|
||||
type bucket struct {
|
||||
tokens float64
|
||||
updated time.Time
|
||||
}
|
||||
|
||||
func NewHTTP(s *Service, a *Auth, assets string, worlds []Destination) *HTTP {
|
||||
return &HTTP{s: s, auth: a, assets: assets, worlds: worlds, rates: map[string]*bucket{}}
|
||||
}
|
||||
func respond(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
func fail(w http.ResponseWriter, status int, msg string) {
|
||||
respond(w, status, map[string]string{"error": msg})
|
||||
}
|
||||
func decode(w http.ResponseWriter, r *http.Request, v any) error {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 4096)
|
||||
d := json.NewDecoder(r.Body)
|
||||
d.DisallowUnknownFields()
|
||||
if err := d.Decode(v); err != nil {
|
||||
return err
|
||||
}
|
||||
var extra any
|
||||
if err := d.Decode(&extra); err != io.EOF {
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (h *HTTP) allow(r *http.Request) bool {
|
||||
// RemoteAddr is authoritative here. Proxy headers are deliberately not trusted.
|
||||
key, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
key = r.RemoteAddr
|
||||
}
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
now := time.Now()
|
||||
b := h.rates[key]
|
||||
if b == nil {
|
||||
if len(h.rates) >= 4096 {
|
||||
for k, v := range h.rates {
|
||||
if now.Sub(v.updated) > time.Minute {
|
||||
delete(h.rates, k)
|
||||
}
|
||||
}
|
||||
if len(h.rates) >= 4096 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
b = &bucket{60, now}
|
||||
h.rates[key] = b
|
||||
}
|
||||
b.tokens = min(60, b.tokens+now.Sub(b.updated).Seconds()*5)
|
||||
b.updated = now
|
||||
if b.tokens < 1 {
|
||||
return false
|
||||
}
|
||||
b.tokens--
|
||||
return true
|
||||
}
|
||||
func (h *HTTP) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.s.ready.Load() {
|
||||
fail(w, 503, "world frozen")
|
||||
return
|
||||
}
|
||||
respond(w, 200, map[string]string{"status": "alive"})
|
||||
})
|
||||
mux.HandleFunc("GET /readyz", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.s.ready.Load() {
|
||||
fail(w, 503, "world unavailable")
|
||||
return
|
||||
}
|
||||
respond(w, 200, map[string]string{"status": "ready"})
|
||||
})
|
||||
mux.HandleFunc("GET /auth/login", h.auth.login)
|
||||
mux.HandleFunc("GET /auth/callback", h.auth.callback)
|
||||
mux.HandleFunc("POST /auth/dev", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.auth.dev {
|
||||
fail(w, 404, "not enabled")
|
||||
return
|
||||
}
|
||||
if account, err := h.auth.account(r); err == nil {
|
||||
respond(w, 200, map[string]bool{"authenticated": account != ""})
|
||||
return
|
||||
}
|
||||
if err := h.auth.session(w, r, "dev:"+game.ID()); err != nil {
|
||||
fail(w, 503, "session unavailable")
|
||||
return
|
||||
}
|
||||
respond(w, 200, map[string]bool{"authenticated": true})
|
||||
})
|
||||
mux.HandleFunc("POST /auth/logout", func(w http.ResponseWriter, r *http.Request) {
|
||||
account, _ := h.auth.account(r)
|
||||
if cookie, err := r.Cookie(h.auth.cookieName()); err == nil {
|
||||
_ = h.auth.db.DeleteSession(r.Context(), hash(cookie.Value))
|
||||
}
|
||||
h.s.mu.Lock()
|
||||
if c := h.s.world.ForAccount(account); c != nil {
|
||||
if p := h.s.peers[c.View.Entity.ID]; p != nil {
|
||||
p.close()
|
||||
}
|
||||
}
|
||||
h.s.mu.Unlock()
|
||||
http.SetCookie(w, &http.Cookie{Name: h.auth.cookieName(), Path: "/", HttpOnly: true, Secure: !h.auth.dev, SameSite: http.SameSiteLaxMode, MaxAge: -1})
|
||||
respond(w, 200, map[string]bool{"ok": true})
|
||||
})
|
||||
mux.HandleFunc("GET /api/config", func(w http.ResponseWriter, r *http.Request) {
|
||||
h.s.mu.Lock()
|
||||
defer h.s.mu.Unlock()
|
||||
b := h.s.world.Balance
|
||||
respond(w, 200, map[string]any{"worldId": h.s.world.ID, "development": h.auth.dev, "worlds": h.worlds, "chunkSize": b.ChunkSize, "playerSpeed": b.PlayerSpeed, "attackRange": b.AttackRange, "gatherRange": b.GatherRange, "recipes": b.Recipes, "tickHz": b.TickHz})
|
||||
})
|
||||
mux.HandleFunc("GET /api/preview", func(w http.ResponseWriter, r *http.Request) {
|
||||
h.s.mu.Lock()
|
||||
defer h.s.mu.Unlock()
|
||||
t := game.NewTerrain(h.s.world.Seed, h.s.world.Balance)
|
||||
chunks := []p.Chunk{}
|
||||
for z := -1; z <= 1; z++ {
|
||||
for x := -1; x <= 1; x++ {
|
||||
chunks = append(chunks, t.Chunk(x, z))
|
||||
}
|
||||
}
|
||||
respond(w, 200, chunks)
|
||||
})
|
||||
mux.HandleFunc("GET /api/me", func(w http.ResponseWriter, r *http.Request) {
|
||||
account, err := h.auth.account(r)
|
||||
if err != nil {
|
||||
fail(w, 401, "sign in required")
|
||||
return
|
||||
}
|
||||
h.s.mu.Lock()
|
||||
defer h.s.mu.Unlock()
|
||||
if c := h.s.world.ForAccount(account); c != nil {
|
||||
respond(w, 200, map[string]any{"character": c.View, "world": h.s.world.Info()})
|
||||
return
|
||||
}
|
||||
respond(w, 200, map[string]any{"character": nil, "world": h.s.world.Info()})
|
||||
})
|
||||
mux.HandleFunc("POST /api/join", func(w http.ResponseWriter, r *http.Request) {
|
||||
account, err := h.auth.account(r)
|
||||
if err != nil {
|
||||
fail(w, 401, "sign in required")
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Name string `json:"name"`
|
||||
Passage string `json:"passage"`
|
||||
}
|
||||
if decode(w, r, &req) != nil {
|
||||
fail(w, 400, "invalid request")
|
||||
return
|
||||
}
|
||||
req.Name = strings.TrimSpace(req.Name)
|
||||
if req.Passage == "" && !regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9 _-]{1,23}$`).MatchString(req.Name) {
|
||||
fail(w, 400, "Name must be 2-24 letters, numbers, spaces, or hyphens.")
|
||||
return
|
||||
}
|
||||
c, err := h.s.join(r.Context(), account, req.Name, req.Passage)
|
||||
if err != nil {
|
||||
fail(w, 409, err.Error())
|
||||
return
|
||||
}
|
||||
respond(w, 200, c)
|
||||
})
|
||||
mux.HandleFunc("GET /api/passages", func(w http.ResponseWriter, r *http.Request) {
|
||||
account, err := h.auth.account(r)
|
||||
if err != nil {
|
||||
fail(w, 401, "sign in required")
|
||||
return
|
||||
}
|
||||
passages, err := h.auth.db.Passages(r.Context(), account)
|
||||
if err != nil {
|
||||
fail(w, 503, "passages unavailable")
|
||||
return
|
||||
}
|
||||
respond(w, 200, passages)
|
||||
})
|
||||
mux.HandleFunc("POST /api/dev/boss", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.auth.dev {
|
||||
fail(w, 404, "not enabled")
|
||||
return
|
||||
}
|
||||
if _, err := h.auth.account(r); err != nil {
|
||||
fail(w, 401, "sign in required")
|
||||
return
|
||||
}
|
||||
h.s.mu.Lock()
|
||||
defer h.s.mu.Unlock()
|
||||
if !h.s.ready.Load() {
|
||||
fail(w, 503, "world unavailable")
|
||||
return
|
||||
}
|
||||
if err := h.s.world.TriggerBoss(); err != nil {
|
||||
fail(w, 409, err.Error())
|
||||
return
|
||||
}
|
||||
if err := h.s.persist(r.Context(), ""); err != nil {
|
||||
fail(w, 503, "save failed")
|
||||
return
|
||||
}
|
||||
respond(w, 200, map[string]bool{"ok": true})
|
||||
})
|
||||
mux.HandleFunc("GET /ws", h.socket)
|
||||
files := http.FileServer(http.Dir(h.assets))
|
||||
mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) {
|
||||
clean := filepath.Clean(filepath.FromSlash(r.URL.Path))
|
||||
if strings.HasPrefix(r.URL.Path, "/api/") {
|
||||
fail(w, 404, "not found")
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/" {
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
}
|
||||
if strings.Contains(clean, ".env") || strings.HasPrefix(r.URL.Path, "/.") {
|
||||
fail(w, 404, "not found")
|
||||
return
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(h.assets, strings.TrimPrefix(clean, string(filepath.Separator)))); err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
files.ServeHTTP(w, r)
|
||||
})
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Referrer-Policy", "no-referrer")
|
||||
w.Header().Set("X-Frame-Options", "DENY")
|
||||
w.Header().Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
|
||||
w.Header().Set("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'")
|
||||
if !h.auth.dev {
|
||||
w.Header().Set("Strict-Transport-Security", "max-age=31536000")
|
||||
}
|
||||
if strings.HasPrefix(r.URL.Path, "/api/") || strings.HasPrefix(r.URL.Path, "/auth/") {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
if !h.allow(r) {
|
||||
fail(w, 429, "too many requests")
|
||||
return
|
||||
}
|
||||
}
|
||||
if r.Method == "POST" && !validOrigin(r, h.auth.base) {
|
||||
fail(w, 403, "origin rejected")
|
||||
return
|
||||
}
|
||||
mux.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
func (h *HTTP) socket(w http.ResponseWriter, r *http.Request) {
|
||||
if !validOrigin(r, h.auth.base) {
|
||||
fail(w, 403, "origin rejected")
|
||||
return
|
||||
}
|
||||
if !h.allow(r) {
|
||||
fail(w, 429, "too many connections")
|
||||
return
|
||||
}
|
||||
account, err := h.auth.account(r)
|
||||
if err != nil {
|
||||
fail(w, 401, "sign in required")
|
||||
return
|
||||
}
|
||||
h.s.mu.Lock()
|
||||
if !h.s.ready.Load() {
|
||||
h.s.mu.Unlock()
|
||||
fail(w, 503, "world unavailable")
|
||||
return
|
||||
}
|
||||
c := h.s.world.ForAccount(account)
|
||||
if c == nil {
|
||||
h.s.mu.Unlock()
|
||||
fail(w, 403, "create a character first")
|
||||
return
|
||||
}
|
||||
id := c.View.Entity.ID
|
||||
if h.s.peers[id] != nil {
|
||||
h.s.mu.Unlock()
|
||||
fail(w, 409, "character already connected")
|
||||
return
|
||||
}
|
||||
if err = h.s.world.Connect(id); err != nil {
|
||||
h.s.mu.Unlock()
|
||||
fail(w, 403, err.Error())
|
||||
return
|
||||
}
|
||||
conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{CompressionMode: websocket.CompressionDisabled})
|
||||
if err != nil {
|
||||
h.s.world.Disconnect(id)
|
||||
h.s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
conn.SetReadLimit(1024)
|
||||
ctx, cancel := context.WithCancel(r.Context())
|
||||
peer := &peer{character: id, out: make(chan []byte, 2), known: map[string]bool{}, close: func() { cancel(); _ = conn.CloseNow() }}
|
||||
h.s.peers[id] = peer
|
||||
h.s.mu.Unlock()
|
||||
defer func() {
|
||||
cancel()
|
||||
_ = conn.CloseNow()
|
||||
h.s.mu.Lock()
|
||||
delete(h.s.peers, id)
|
||||
h.s.world.Disconnect(id)
|
||||
h.s.mu.Unlock()
|
||||
}()
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case data := <-peer.out:
|
||||
writeCtx, stop := context.WithTimeout(ctx, 3*time.Second)
|
||||
err := conn.Write(writeCtx, websocket.MessageText, data)
|
||||
stop()
|
||||
if err != nil {
|
||||
peer.close()
|
||||
return
|
||||
}
|
||||
var snap p.Snapshot
|
||||
if json.Unmarshal(data, &snap) == nil && snap.Self.RemainingSeconds <= 0 {
|
||||
_ = conn.Close(websocket.StatusPolicyViolation, "daily play limit reached")
|
||||
peer.close()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
tokens := float64(40)
|
||||
last := time.Now()
|
||||
lastSessionCheck := last
|
||||
for {
|
||||
readCtx, stop := context.WithTimeout(ctx, 45*time.Second)
|
||||
kind, data, err := conn.Read(readCtx)
|
||||
stop()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
now := time.Now()
|
||||
tokens = min(40, tokens+now.Sub(last).Seconds()*30)
|
||||
last = now
|
||||
if tokens < 1 {
|
||||
_ = conn.Close(websocket.StatusPolicyViolation, "input rate exceeded")
|
||||
return
|
||||
}
|
||||
tokens--
|
||||
if now.Sub(lastSessionCheck) > time.Minute {
|
||||
if _, err = h.auth.account(r); err != nil {
|
||||
return
|
||||
}
|
||||
lastSessionCheck = now
|
||||
}
|
||||
if kind != websocket.MessageText {
|
||||
return
|
||||
}
|
||||
var intent p.Intent
|
||||
d := json.NewDecoder(bytes.NewReader(data))
|
||||
d.DisallowUnknownFields()
|
||||
if d.Decode(&intent) != nil {
|
||||
return
|
||||
}
|
||||
var extra any
|
||||
if d.Decode(&extra) != io.EOF {
|
||||
return
|
||||
}
|
||||
h.s.mu.Lock()
|
||||
if !h.s.ready.Load() {
|
||||
h.s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
if err = h.s.world.Intent(id, intent); err != nil {
|
||||
c.Message = err.Error()
|
||||
}
|
||||
h.s.mu.Unlock()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"aeternalis/server/content"
|
||||
"aeternalis/server/internal/game"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"aeternalis/server/internal/store"
|
||||
"github.com/coder/websocket"
|
||||
)
|
||||
|
||||
func TestHTTPAndSocketSecurity(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
db, err := store.Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "http.db")))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
b, _ := content.Load()
|
||||
w := game.New("test", 123, time.Now(), b)
|
||||
lease, _, err := db.Acquire(ctx, w)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
svc := NewService(w, lease)
|
||||
auth, _ := NewAuth(ctx, db, true, "http://127.0.0.1", "", "", "")
|
||||
server := httptest.NewServer(NewHTTP(svc, auth, t.TempDir(), nil).Handler())
|
||||
defer server.Close()
|
||||
auth.base = server.URL
|
||||
go svc.Run(ctx)
|
||||
defer func() { cancel(); <-svc.done; _ = svc.Stop(context.Background()) }()
|
||||
request := func(path, origin, body string, cookie *http.Cookie) *http.Response {
|
||||
t.Helper()
|
||||
req, _ := http.NewRequest(http.MethodPost, server.URL+path, strings.NewReader(body))
|
||||
if origin != "" {
|
||||
req.Header.Set("Origin", origin)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if cookie != nil {
|
||||
req.AddCookie(cookie)
|
||||
}
|
||||
response, err := server.Client().Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return response
|
||||
}
|
||||
for _, origin := range []string{"", "https://evil.example", "null", server.URL + ".evil"} {
|
||||
r := request("/auth/dev", origin, "{}", nil)
|
||||
r.Body.Close()
|
||||
if r.StatusCode != 403 {
|
||||
t.Fatalf("accepted origin %q", origin)
|
||||
}
|
||||
}
|
||||
r := request("/auth/dev", server.URL, "{}", nil)
|
||||
cookies := r.Cookies()
|
||||
r.Body.Close()
|
||||
if len(cookies) != 1 || !cookies[0].HttpOnly {
|
||||
t.Fatal("missing HttpOnly session")
|
||||
}
|
||||
cookie := cookies[0]
|
||||
r = request("/api/join", server.URL, `{"name":"Traveler","passage":"","hp":999}`, cookie)
|
||||
r.Body.Close()
|
||||
if r.StatusCode != 400 {
|
||||
t.Fatal("unknown join field accepted")
|
||||
}
|
||||
r = request("/api/join", server.URL, `{"name":"Traveler","passage":""}`, cookie)
|
||||
raw, _ := io.ReadAll(r.Body)
|
||||
r.Body.Close()
|
||||
if r.StatusCode != 200 {
|
||||
t.Fatalf("join %d %s", r.StatusCode, raw)
|
||||
}
|
||||
var character p.Character
|
||||
if err = json.Unmarshal(raw, &character); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wsURL := "ws" + strings.TrimPrefix(server.URL, "http") + "/ws"
|
||||
badCtx, stop := context.WithTimeout(ctx, time.Second)
|
||||
_, response, err := websocket.Dial(badCtx, wsURL, &websocket.DialOptions{HTTPHeader: http.Header{"Origin": []string{"https://evil.example"}, "Cookie": []string{cookie.String()}}})
|
||||
stop()
|
||||
if err == nil || response.StatusCode != 403 {
|
||||
t.Fatal("cross-origin websocket accepted")
|
||||
}
|
||||
socketCtx, stopSocket := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer stopSocket()
|
||||
conn, _, err := websocket.Dial(socketCtx, wsURL, &websocket.DialOptions{HTTPHeader: http.Header{"Origin": []string{server.URL}, "Cookie": []string{cookie.String()}}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.CloseNow()
|
||||
conn.SetReadLimit(2 << 20)
|
||||
_, data, err := conn.Read(socketCtx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var s p.Snapshot
|
||||
if err = json.Unmarshal(data, &s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(s.Chunks) != 9 {
|
||||
t.Fatal("missing chunk snapshot")
|
||||
}
|
||||
if bytes.Contains(data, []byte(`"account"`)) {
|
||||
t.Fatal("account identity leaked")
|
||||
}
|
||||
intent := p.Intent{Op: "move", Seq: 1, X: 1}
|
||||
payload, _ := json.Marshal(intent)
|
||||
if err = conn.Write(socketCtx, websocket.MessageText, payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = conn.Write(socketCtx, websocket.MessageText, []byte(`{"op":"move","seq":2,"x":1,"z":0,"target":"","hp":999}`)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for {
|
||||
_, _, err = conn.Read(socketCtx)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
t.Fatal("malformed intent was not disconnected")
|
||||
}
|
||||
}
|
||||
func TestProductionAuthRequiresOIDC(t *testing.T) {
|
||||
if _, err := NewAuth(context.Background(), nil, false, "http://insecure", "", "", ""); err == nil {
|
||||
t.Fatal("insecure production auth accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"maps"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"aeternalis/server/internal/game"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"aeternalis/server/internal/store"
|
||||
)
|
||||
|
||||
type peer struct {
|
||||
character string
|
||||
out chan []byte
|
||||
known map[string]bool
|
||||
close func()
|
||||
}
|
||||
type Service struct {
|
||||
mu sync.Mutex
|
||||
world *game.World
|
||||
lease *store.Lease
|
||||
peers map[string]*peer
|
||||
ready atomic.Bool
|
||||
lastSave time.Time
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
func NewService(w *game.World, l *store.Lease) *Service {
|
||||
s := &Service{world: w, lease: l, peers: map[string]*peer{}, lastSave: time.Now(), done: make(chan struct{})}
|
||||
s.ready.Store(true)
|
||||
return s
|
||||
}
|
||||
func (s *Service) persist(ctx context.Context, claim string) error {
|
||||
err := s.lease.Save(ctx, s.world, claim)
|
||||
if err != nil {
|
||||
s.ready.Store(false)
|
||||
slog.Error("world frozen: persistence failed", "error", err)
|
||||
for _, p := range s.peers {
|
||||
p.close()
|
||||
}
|
||||
return err
|
||||
}
|
||||
s.lastSave = time.Now()
|
||||
return nil
|
||||
}
|
||||
func (s *Service) Run(ctx context.Context) {
|
||||
defer close(s.done)
|
||||
ticker := time.NewTicker(time.Second / time.Duration(s.world.Balance.TickHz))
|
||||
defer ticker.Stop()
|
||||
last := time.Now()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case now := <-ticker.C:
|
||||
s.mu.Lock()
|
||||
if !s.ready.Load() {
|
||||
s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
s.world.Advance(now, now.Sub(last).Seconds())
|
||||
last = now
|
||||
if s.world.Dirty() || now.Sub(s.lastSave) >= time.Second {
|
||||
saveCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
err := s.persist(saveCtx, "")
|
||||
cancel()
|
||||
if err != nil {
|
||||
s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
}
|
||||
if s.world.Tick%int64(s.world.Balance.TickHz/s.world.Balance.SnapshotHz) == 0 {
|
||||
for id, p := range s.peers {
|
||||
snapshot := s.world.Snapshot(id, p.known)
|
||||
data, err := json.Marshal(snapshot)
|
||||
if err != nil {
|
||||
slog.Error("snapshot encoding failed", "error", err)
|
||||
p.close()
|
||||
continue
|
||||
}
|
||||
select {
|
||||
case p.out <- data:
|
||||
for key := range p.known {
|
||||
delete(p.known, key)
|
||||
}
|
||||
for _, key := range snapshot.ChunkKeys {
|
||||
p.known[key] = true
|
||||
}
|
||||
default:
|
||||
p.close()
|
||||
}
|
||||
}
|
||||
}
|
||||
s.mu.Unlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
func (s *Service) Stop(ctx context.Context) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
wasReady := s.ready.Swap(false)
|
||||
for id, p := range s.peers {
|
||||
s.world.Disconnect(id)
|
||||
p.close()
|
||||
}
|
||||
if !wasReady {
|
||||
return errors.New("world already frozen; lease will expire")
|
||||
}
|
||||
if err := s.lease.Save(ctx, s.world, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.lease.Release(ctx)
|
||||
}
|
||||
func (s *Service) join(ctx context.Context, account, name, claim string) (p.Character, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if !s.ready.Load() {
|
||||
return p.Character{}, errors.New("world unavailable")
|
||||
}
|
||||
var c *game.Character
|
||||
var err error
|
||||
if claim != "" {
|
||||
c, err = s.lease.DB.ReadPassage(ctx, claim, account)
|
||||
if err != nil {
|
||||
return p.Character{}, errors.New("passage unavailable")
|
||||
}
|
||||
if err = s.world.Import(c); err != nil {
|
||||
return p.Character{}, err
|
||||
}
|
||||
} else {
|
||||
c, err = s.world.Join(account, name)
|
||||
if err != nil {
|
||||
return p.Character{}, err
|
||||
}
|
||||
}
|
||||
if err = s.persist(ctx, claim); err != nil {
|
||||
return p.Character{}, errors.New("world persistence unavailable")
|
||||
}
|
||||
view := c.View
|
||||
view.Inventory = maps.Clone(view.Inventory)
|
||||
view.Skills = maps.Clone(view.Skills)
|
||||
return view, nil
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
async function enter(page, name = 'Wayfarer') {
|
||||
await page.goto('/');
|
||||
await expect(page.locator('#connection-status')).toHaveText('World online');
|
||||
await page.getByLabel('Character name').fill(name);
|
||||
await page.getByRole('button', { name: 'Enter world' }).click();
|
||||
await expect(page.locator('#connection-status')).toHaveText('Connected');
|
||||
await expect(page.locator('#game-controls')).toBeVisible();
|
||||
await expect.poll(() => page.evaluate(() => (window as any).__aeternalis?.diagnostics().chunks)).toBe(9);
|
||||
}
|
||||
|
||||
test('desktop renders models, moves authoritatively, gathers, and reconnects', async ({ page }) => {
|
||||
const errors: string[] = [];
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
await page.setViewportSize({ width: 1440, height: 900 });
|
||||
await enter(page);
|
||||
const before = await page.evaluate(() => (window as any).__aeternalis.snapshot.self.entity.position);
|
||||
await page.keyboard.down('d'); await page.waitForTimeout(1000); await page.keyboard.up('d');
|
||||
await expect.poll(() => page.evaluate(() => (window as any).__aeternalis.snapshot.self.entity.position.x)).toBeGreaterThan(before.x + 3);
|
||||
await page.getByRole('button', { name: 'Gather', exact: true }).click();
|
||||
await expect.poll(() => page.evaluate(() => Object.values((window as any).__aeternalis.snapshot.self.skills).reduce((sum: number, n: any) => sum + n, 0)), { timeout: 15000 }).toBeGreaterThan(0);
|
||||
await page.getByRole('button', { name: 'Inventory and crafting' }).click();
|
||||
await expect(page.locator('#inventory')).toBeVisible();
|
||||
await expect(page.locator('#inventory-items')).toContainText('Knife');
|
||||
await page.getByRole('button', { name: 'Close inventory', exact: true }).click();
|
||||
const id = await page.evaluate(() => (window as any).__aeternalis.snapshot.self.entity.id);
|
||||
await page.screenshot({ path: 'test-results/desktop.png' });
|
||||
const pixels = await page.evaluate(async () => {
|
||||
const canvas = document.getElementById('world') as HTMLCanvasElement;
|
||||
// Read in the animation frame immediately after rendering; avoid a cleared backbuffer.
|
||||
return new Promise<number>(resolve => requestAnimationFrame(() => {
|
||||
const gl = canvas.getContext('webgl2')!;
|
||||
const data = new Uint8Array(64 * 64 * 4);
|
||||
gl.readPixels(Math.floor(canvas.width / 2) - 32, Math.floor(canvas.height / 2) - 32, 64, 64, gl.RGBA, gl.UNSIGNED_BYTE, data);
|
||||
const colors = new Set<string>(); for (let i = 0; i < data.length; i += 4) colors.add(`${data[i]},${data[i+1]},${data[i+2]}`);
|
||||
resolve(colors.size);
|
||||
}));
|
||||
});
|
||||
expect(pixels).toBeGreaterThan(8);
|
||||
const diagnostics = await page.evaluate(() => (window as any).__aeternalis.diagnostics());
|
||||
expect(diagnostics.models).toBe(6); expect(diagnostics.frames).toBeGreaterThan(10); expect(diagnostics.triangles).toBeGreaterThan(1000);
|
||||
await page.reload();
|
||||
await expect(page.locator('#connection-status')).toHaveText('Connected');
|
||||
await expect.poll(() => page.evaluate(() => (window as any).__aeternalis?.snapshot?.self.entity.id)).toBe(id);
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
test('mobile controls fit and move the character', async ({ page }) => {
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await enter(page, 'Mobile');
|
||||
await expect(page.getByRole('button', { name: 'Move north' })).toBeVisible();
|
||||
const before = await page.evaluate(() => (window as any).__aeternalis.snapshot.self.entity.position.z);
|
||||
const button = page.getByRole('button', { name: 'Move north' });
|
||||
await button.dispatchEvent('pointerdown', { pointerId: 1 }); await page.waitForTimeout(650); await button.dispatchEvent('pointerup', { pointerId: 1 });
|
||||
await expect.poll(() => page.evaluate(() => (window as any).__aeternalis.snapshot.self.entity.position.z)).toBeLessThan(before - 2);
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true);
|
||||
await page.getByRole('button', { name: 'Inventory and crafting' }).click();
|
||||
const box = await page.locator('#inventory').boundingBox();
|
||||
expect(box!.x).toBeGreaterThanOrEqual(0); expect(box!.x + box!.width).toBeLessThanOrEqual(390);
|
||||
await page.screenshot({ path: 'test-results/mobile.png' });
|
||||
await page.getByRole('button', { name: 'Close inventory', exact: true }).click();
|
||||
await page.setViewportSize({ width: 844, height: 390 });
|
||||
await page.screenshot({ path: 'test-results/mobile-landscape.png' });
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true);
|
||||
});
|
||||
|
||||
test('unauthenticated API and hostile origins cannot mutate state', async ({ request }) => {
|
||||
expect((await request.post('/api/join', { data: { name: 'Intruder' }, headers: { Origin: 'https://evil.example' } })).status()).toBe(403);
|
||||
expect((await request.get('/api/me')).status()).toBe(401);
|
||||
const response = await request.get('/api/config');
|
||||
expect(response.headers()['content-security-policy']).toContain("frame-ancestors 'none'");
|
||||
expect(response.headers()['x-content-type-options']).toBe('nosniff');
|
||||
});
|
||||
|
||||
test('boss event is visible and accepts server-authoritative combat', async ({ page }) => {
|
||||
await page.setViewportSize({ width: 1440, height: 900 });
|
||||
await enter(page, 'Boss witness');
|
||||
await page.getByRole('button', { name: 'Display settings' }).click();
|
||||
await page.getByRole('button', { name: 'Awaken Harbinger' }).click();
|
||||
await expect(page.locator('#phase-label')).toHaveText('THE UNRAVELING');
|
||||
await page.getByRole('button', { name: 'Close display settings' }).click();
|
||||
const hp = await page.evaluate(() => (window as any).__aeternalis.snapshot.world.bossHp);
|
||||
await page.getByRole('button', { name: 'Target Harbinger', exact: true }).click();
|
||||
await expect.poll(() => page.evaluate(() => (window as any).__aeternalis.snapshot.world.bossHp), { timeout: 15000 }).toBeLessThan(hp);
|
||||
await expect(page.locator('#boss-bar')).toBeVisible();
|
||||
await page.screenshot({ path: 'test-results/boss.png' });
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$toolsDir = Join-Path $PSScriptRoot '..\.tools'
|
||||
New-Item -ItemType Directory -Force -Path $toolsDir | Out-Null
|
||||
$releases = Invoke-RestMethod 'https://go.dev/dl/?mode=json'
|
||||
$release = $releases | Where-Object stable | Select-Object -First 1
|
||||
$archive = $release.files | Where-Object { $_.os -eq 'windows' -and $_.arch -eq 'amd64' -and $_.kind -eq 'archive' } | Select-Object -First 1
|
||||
if (-not $archive) { throw 'No stable Windows Go archive found.' }
|
||||
$destination = Join-Path $toolsDir $archive.filename
|
||||
Invoke-WebRequest ('https://go.dev/dl/' + $archive.filename) -OutFile $destination
|
||||
if ((Get-FileHash $destination -Algorithm SHA256).Hash.ToLowerInvariant() -ne $archive.sha256) { throw 'Go checksum mismatch.' }
|
||||
Expand-Archive -LiteralPath $destination -DestinationPath $toolsDir -Force
|
||||
& (Join-Path $toolsDir 'go\bin\go.exe') version
|
||||
@@ -0,0 +1,13 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
|
||||
$toolsDir = Join-Path $PSScriptRoot '..\.tools'
|
||||
New-Item -ItemType Directory -Force -Path $toolsDir | Out-Null
|
||||
$name = 'helm-v3.18.6-windows-amd64.zip'
|
||||
$destination = Join-Path $toolsDir $name
|
||||
$checksumResponse = (Invoke-WebRequest ('https://get.helm.sh/' + $name + '.sha256sum') -UseBasicParsing).Content
|
||||
$checksumText = if ($checksumResponse -is [byte[]]) { [Text.Encoding]::ASCII.GetString($checksumResponse) } else { [string]$checksumResponse }
|
||||
$expected = ($checksumText.Trim() -split '\s+')[0]
|
||||
Invoke-WebRequest ('https://get.helm.sh/' + $name) -UseBasicParsing -OutFile $destination
|
||||
if ((Get-FileHash $destination -Algorithm SHA256).Hash.ToLowerInvariant() -ne $expected) { throw 'Helm checksum mismatch.' }
|
||||
Expand-Archive -LiteralPath $destination -DestinationPath $toolsDir -Force
|
||||
& (Join-Path $toolsDir 'windows-amd64\helm.exe') version --short
|
||||
@@ -0,0 +1,36 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$source = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..')).TrimEnd('\')
|
||||
$target = 'C:\Dev\aeternalis'
|
||||
if ($source -ne 'C:\Dev\RPGTheory\aeternalis-build') { throw 'Unexpected source workspace.' }
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $target 'planning\VISION.md'))) { throw 'Original target planning document not found.' }
|
||||
$visionHash = (Get-FileHash -LiteralPath (Join-Path $target 'planning\VISION.md') -Algorithm SHA256).Hash
|
||||
$excluded = @('.git', '.tools', '.local', 'node_modules', 'test-results', 'playwright-report')
|
||||
$copied = 0
|
||||
foreach ($entry in Get-ChildItem -Force -LiteralPath $source) {
|
||||
if ($entry.Name -in $excluded) { continue }
|
||||
if ($entry.PSIsContainer) {
|
||||
foreach ($file in Get-ChildItem -File -Recurse -Force -LiteralPath $entry.FullName) {
|
||||
$relative = $file.FullName.Substring($source.Length + 1)
|
||||
if ($relative -eq 'planning\VISION.md') { continue }
|
||||
$destination = [IO.Path]::GetFullPath((Join-Path $target $relative))
|
||||
if (-not $destination.StartsWith($target + '\', [StringComparison]::OrdinalIgnoreCase)) { throw 'Copy escaped destination.' }
|
||||
New-Item -ItemType Directory -Force -Path (Split-Path -Parent $destination) | Out-Null
|
||||
Copy-Item -LiteralPath $file.FullName -Destination $destination -Force
|
||||
if ((Get-FileHash -LiteralPath $destination -Algorithm SHA256).Hash -ne (Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256).Hash) { throw "Copy mismatch: $relative" }
|
||||
$copied++
|
||||
}
|
||||
} else {
|
||||
Copy-Item -LiteralPath $entry.FullName -Destination (Join-Path $target $entry.Name) -Force
|
||||
$copied++
|
||||
}
|
||||
}
|
||||
if ((Get-FileHash -LiteralPath (Join-Path $target 'planning\VISION.md') -Algorithm SHA256).Hash -ne $visionHash) { throw 'Original vision changed unexpectedly.' }
|
||||
$binary = Join-Path $source '.local\world-001.exe'
|
||||
if (Test-Path -LiteralPath $binary) {
|
||||
New-Item -ItemType Directory -Force -Path (Join-Path $target '.local') | Out-Null
|
||||
$binaryDestination = Join-Path $target '.local\world-001.exe'
|
||||
Copy-Item -LiteralPath $binary -Destination $binaryDestination -Force
|
||||
if ((Get-FileHash -LiteralPath $binaryDestination -Algorithm SHA256).Hash -ne (Get-FileHash -LiteralPath $binary -Algorithm SHA256).Hash) { throw 'Server binary copy mismatch.' }
|
||||
$copied++
|
||||
}
|
||||
Write-Output "Copied $copied files into $target. Original vision and .git preserved."
|
||||
@@ -0,0 +1,119 @@
|
||||
"""Rebuild original placeholder meshes: blender --background --python tools/create-models.py."""
|
||||
import bpy
|
||||
import math
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
OUT = ROOT / "client" / "public" / "models"
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def material(name, color, metallic=0):
|
||||
mat = bpy.data.materials.new(name)
|
||||
mat.diffuse_color = (*color, 1)
|
||||
mat.use_nodes = True
|
||||
node = mat.node_tree.nodes.get("Principled BSDF")
|
||||
node.inputs["Base Color"].default_value = (*color, 1)
|
||||
node.inputs["Roughness"].default_value = 0.85
|
||||
node.inputs["Metallic"].default_value = metallic
|
||||
return mat
|
||||
|
||||
pine = material("pine needles", (0.15, 0.34, 0.25))
|
||||
tips = material("fresh needles", (0.28, 0.48, 0.3))
|
||||
bark = material("bark", (0.24, 0.22, 0.2))
|
||||
rock = material("stone", (0.42, 0.47, 0.48))
|
||||
iron = material("iron", (0.23, 0.29, 0.3), 0.4)
|
||||
cloth = material("traveler green", (0.24, 0.45, 0.41))
|
||||
linen = material("linen", (0.73, 0.76, 0.71))
|
||||
skin = material("skin", (0.7, 0.49, 0.34))
|
||||
ember = material("ember", (0.88, 0.16, 0.16))
|
||||
leaf = material("sage", (0.41, 0.64, 0.3))
|
||||
flower = material("flowers", (0.89, 0.75, 0.29))
|
||||
|
||||
def clear():
|
||||
bpy.ops.object.select_all(action="SELECT")
|
||||
bpy.ops.object.delete(use_global=False)
|
||||
|
||||
def cone(name, pos, radius, depth, mat, top=0, vertices=7):
|
||||
bpy.ops.mesh.primitive_cone_add(vertices=vertices, radius1=radius, radius2=top, depth=depth, location=pos)
|
||||
obj = bpy.context.object
|
||||
obj.name = name
|
||||
obj.data.materials.append(mat)
|
||||
return obj
|
||||
|
||||
def cube(name, pos, scale, mat):
|
||||
bpy.ops.mesh.primitive_cube_add(size=1, location=pos)
|
||||
obj = bpy.context.object
|
||||
obj.name = name
|
||||
obj.scale = scale
|
||||
obj.data.materials.append(mat)
|
||||
bevel = obj.modifiers.new("worn edges", "BEVEL")
|
||||
bevel.width = 0.09
|
||||
bevel.segments = 1
|
||||
bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)
|
||||
return obj
|
||||
|
||||
def ico(name, pos, scale, mat):
|
||||
bpy.ops.mesh.primitive_ico_sphere_add(subdivisions=1, radius=1, location=pos)
|
||||
obj = bpy.context.object
|
||||
obj.name = name
|
||||
obj.scale = scale
|
||||
obj.data.materials.append(mat)
|
||||
return obj
|
||||
|
||||
def export(name):
|
||||
bpy.ops.export_scene.gltf(filepath=str(OUT / (name + ".glb")), export_format="GLB", export_yup=True)
|
||||
|
||||
clear()
|
||||
cone("trunk", (0,0,3.7), 0.6, 7.4, bark, 0.22)
|
||||
for z,r in [(5,3.8),(7.5,3),(9.5,2.2)]:
|
||||
cone("canopy", (0,0,z), r, 5.2, pine if z<9 else tips)
|
||||
export("tree")
|
||||
|
||||
clear()
|
||||
ico("boulder", (0,0,1), (2.3,1.7,1.5), rock)
|
||||
for x,y in [(-0.8,0.3),(0.6,-0.7),(1,0.6)]:
|
||||
cone("iron vein", (x,y,1.7), 0.35, 1.8, iron, 0.1, 5)
|
||||
export("ore")
|
||||
|
||||
clear()
|
||||
for i in range(6):
|
||||
a = i*math.tau/6
|
||||
x,y = math.cos(a)*0.6,math.sin(a)*0.6
|
||||
cone("stem",(x,y,0.6),0.09,1.2,leaf,0.04,5)
|
||||
ico("leaf",(x,y,0.9),(0.6,0.3,0.2),leaf)
|
||||
ico("flower",(x,y,1.4),(0.3,0.3,0.25),flower)
|
||||
export("herb")
|
||||
|
||||
def humanoid(boss=False):
|
||||
body_mat = iron if boss else cloth
|
||||
cube("torso", (0,0,1.7), (0.9,0.5,1.1), body_mat)
|
||||
cube("belt", (0,0,1.22), (1,0.6,0.2), bark)
|
||||
ico("head", (0,0,2.55), (0.37,0.34,0.43), rock if boss else skin)
|
||||
cone("hood", (0,0.05,2.83), 0.46, 0.5, body_mat, 0.18)
|
||||
for sign in [-1,1]:
|
||||
cube("leg", (sign*0.24,0,0.65), (0.32,0.34,1.2), iron if boss else linen)
|
||||
cube("boot", (sign*0.24,-0.12,0.15), (0.37,0.58,0.3), bark)
|
||||
cube("arm", (sign*0.64,0,1.67), (0.3,0.35,1), body_mat)
|
||||
ico("hand", (sign*0.64,0,1.03), (0.18,0.18,0.2), rock if boss else skin)
|
||||
if boss:
|
||||
for sign in [-1,1]:
|
||||
horn=cone("crown", (sign*0.4,0,3.2),0.2,1.2,ember,0,5)
|
||||
horn.rotation_euler[1] = sign*0.4
|
||||
cube("heart", (0,-0.28,1.9), (0.3,0.12,0.5),ember)
|
||||
else:
|
||||
cube("pack", (0,0.38,1.8), (0.72,0.4,0.85),bark)
|
||||
cone("knife", (0.7,-0.05,0.75),0.13,0.6,iron,0,4)
|
||||
|
||||
clear()
|
||||
humanoid()
|
||||
export("player")
|
||||
clear()
|
||||
humanoid(True)
|
||||
export("sentinel")
|
||||
clear()
|
||||
humanoid(True)
|
||||
for obj in bpy.context.scene.objects:
|
||||
obj.location *= 4
|
||||
obj.scale *= 4
|
||||
export("boss")
|
||||
bpy.ops.wm.save_as_mainfile(filepath=str(ROOT / "assets" / "harbinger.blend"))
|
||||
@@ -0,0 +1,23 @@
|
||||
import { existsSync, mkdirSync } from 'node:fs';
|
||||
import { spawn, spawnSync } from 'node:child_process';
|
||||
import { resolve } from 'node:path';
|
||||
|
||||
const localGo = resolve('.tools/go/bin/go.exe');
|
||||
const go = process.env.GO_EXE || (existsSync(localGo) ? localGo : 'go');
|
||||
mkdirSync('.local', { recursive: true });
|
||||
const executable = resolve(`.local/world${process.platform === 'win32' ? '.exe' : ''}`);
|
||||
const environment = { ...process.env, GOCACHE: resolve('.local/go-cache') };
|
||||
const result = spawnSync(go, ['build', '-o', executable, './cmd/world'], { cwd: resolve('server'), env: environment, stdio: 'inherit' });
|
||||
if (result.status !== 0) process.exit(result.status || 1);
|
||||
const port = process.env.PORT || '18080';
|
||||
const child = spawn(executable, [], {
|
||||
cwd: resolve('server'), stdio: 'inherit',
|
||||
env: {
|
||||
...environment, APP_ENV: 'development', LISTEN_ADDR: `127.0.0.1:${port}`,
|
||||
PUBLIC_URL: process.env.PUBLIC_URL || `http://127.0.0.1:${port}`, CLIENT_DIR: resolve('client/dist'),
|
||||
DATABASE_URL: process.env.DATABASE_URL || `file:${resolve('.local', process.env.E2E ? `e2e-${Date.now()}.db` : 'aeternalis.db')}`,
|
||||
WORLD_ID: process.env.WORLD_ID || 'world-001',
|
||||
},
|
||||
});
|
||||
for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => { child.kill('SIGTERM'); });
|
||||
child.on('exit', code => process.exit(code || 0));
|
||||
@@ -0,0 +1,22 @@
|
||||
import { readFile, writeFile, mkdir } from 'node:fs/promises';
|
||||
import { quicktype, InputData, JSONSchemaInput, FetchingJSONSchemaStore } from 'quicktype-core';
|
||||
|
||||
const schema = await readFile(new URL('../schemas/protocol.json', import.meta.url), 'utf8');
|
||||
const input = new JSONSchemaInput(new FetchingJSONSchemaStore());
|
||||
await input.addSource({ name: 'Protocol', schema });
|
||||
const inputData = new InputData();
|
||||
inputData.addInput(input);
|
||||
for (const [lang, path, rendererOptions] of [
|
||||
['go', '../server/internal/protocol/generated.go', { package: 'protocol', 'just-types': 'true' }],
|
||||
['typescript', '../client/src/generated.ts', { 'just-types': 'true' }],
|
||||
]) {
|
||||
const result = await quicktype({ inputData, lang, rendererOptions, alphabetizeProperties: true });
|
||||
const output = '// Code generated from schemas/protocol.json. DO NOT EDIT.\n' + (lang === 'go' ? 'package protocol\n\n' : '') + result.lines.join('\n').trimEnd() + '\n';
|
||||
const url = new URL(path, import.meta.url);
|
||||
if (process.argv.includes('--check')) {
|
||||
if (await readFile(url, 'utf8') !== output) throw new Error(`Stale generated contract: ${path}`);
|
||||
} else {
|
||||
await mkdir(new URL('.', url), { recursive: true });
|
||||
await writeFile(url, output);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
||||
import { resolve, relative, isAbsolute } from 'node:path';
|
||||
import YAML from 'yaml';
|
||||
|
||||
const env = process.env;
|
||||
for (const key of ['GITOPS_REPOSITORY', 'GITOPS_USERNAME', 'GITOPS_TOKEN', 'IMAGE_REPOSITORY', 'IMAGE_DIGEST']) if (!env[key]) throw new Error(`Missing ${key}`);
|
||||
if (!/^sha256:[a-f0-9]{64}$/.test(env.IMAGE_DIGEST)) throw new Error('Invalid image digest');
|
||||
const repository = new URL(env.GITOPS_REPOSITORY);
|
||||
if (repository.protocol !== 'https:' || repository.username || repository.password) throw new Error('GITOPS_REPOSITORY must be HTTPS without credentials');
|
||||
const root = resolve('.local/gitops');
|
||||
const askpass = resolve('.local/git-askpass.cjs');
|
||||
await mkdir(resolve('.local'), { recursive: true });
|
||||
await writeFile(askpass, '#!/usr/bin/env node\nprocess.stdout.write(process.argv[2].toLowerCase().includes("username") ? process.env.GITOPS_USERNAME : process.env.GITOPS_TOKEN);\n', { mode: 0o700 });
|
||||
function git(args, cwd = process.cwd()) {
|
||||
const result = spawnSync('git', args, { cwd, env: { ...env, GIT_ASKPASS: askpass, GIT_TERMINAL_PROMPT: '0' }, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
if (result.status !== 0) throw new Error(`Git operation failed (${args[0]}): ${result.stderr.replaceAll(env.GITOPS_TOKEN, '[redacted]')}`);
|
||||
return result.stdout;
|
||||
}
|
||||
git(['clone', '--branch', env.GITOPS_BRANCH || 'main', '--depth', '1', '--', repository.href, root]);
|
||||
const file = resolve(root, env.GITOPS_VALUES_FILE || 'apps/aeternalis/values.yaml');
|
||||
const local = relative(root, file);
|
||||
if (local.startsWith('..') || isAbsolute(local) || !/\.ya?ml$/.test(local)) throw new Error('Values file must stay inside the GitOps checkout');
|
||||
const document = YAML.parseDocument(await readFile(file, 'utf8'));
|
||||
document.setIn(['image', 'repository'], env.IMAGE_REPOSITORY);
|
||||
document.setIn(['image', 'digest'], env.IMAGE_DIGEST);
|
||||
await writeFile(file, document.toString());
|
||||
git(['config', 'user.name', 'Aeternalis CI'], root);
|
||||
git(['config', 'user.email', 'aeternalis-ci@localhost'], root);
|
||||
git(['add', '--', local], root);
|
||||
if (git(['diff', '--cached', '--name-only'], root).trim()) {
|
||||
git(['commit', '-m', `Deploy Aeternalis ${env.IMAGE_DIGEST.slice(0,19)}`], root);
|
||||
git(['push', 'origin', `HEAD:${env.GITOPS_BRANCH || 'main'}`], root);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
param([int]$Port = 18080, [string]$WorldId = 'world-001', [int]$Seed = 734291, [switch]$UseExisting)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$root = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..'))
|
||||
if ($WorldId -notmatch '^[a-z][a-z0-9-]{0,30}$') { throw 'Invalid world ID.' }
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $root 'client\dist\index.html'))) { throw 'Run npm ci and npm run build first.' }
|
||||
$listener = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback, $Port)
|
||||
try { $listener.Start() } finally { $listener.Stop() }
|
||||
New-Item -ItemType Directory -Force -Path (Join-Path $root '.local') | Out-Null
|
||||
$exe = Join-Path $root ".local\$WorldId.exe"
|
||||
$env:GOCACHE = Join-Path $root '.local\go-cache'
|
||||
if (-not $UseExisting) {
|
||||
$go = Join-Path $root '.tools\go\bin\go.exe'
|
||||
if (-not (Test-Path -LiteralPath $go)) { $go = (Get-Command go -ErrorAction Stop).Source }
|
||||
Push-Location (Join-Path $root 'server')
|
||||
try { & $go build -o $exe ./cmd/world; if ($LASTEXITCODE -ne 0) { throw 'Go build failed.' } } finally { Pop-Location }
|
||||
}
|
||||
if (-not (Test-Path -LiteralPath $exe)) { throw "Missing server binary: $exe" }
|
||||
$env:APP_ENV = 'development'
|
||||
$env:LISTEN_ADDR = "127.0.0.1:$Port"
|
||||
$env:PUBLIC_URL = "http://127.0.0.1:$Port"
|
||||
$env:CLIENT_DIR = Join-Path $root 'client\dist'
|
||||
$env:DATABASE_URL = 'file:' + ((Join-Path $root '.local\aeternalis.db') -replace '\\','/')
|
||||
$env:WORLD_ID = $WorldId
|
||||
$env:WORLD_SEED = "$Seed"
|
||||
$process = Start-Process -FilePath $exe -WorkingDirectory (Join-Path $root 'server') -WindowStyle Hidden -PassThru -RedirectStandardOutput (Join-Path $root ".local\$WorldId.stdout.log") -RedirectStandardError (Join-Path $root ".local\$WorldId.stderr.log")
|
||||
Write-Output "World ${WorldId}: http://127.0.0.1:$Port (PID $($process.Id))"
|
||||
Reference in New Issue
Block a user