prototype-server-vision: phase 2b client (Vite+TS+Pixi v8, fog masks, drag, reducer test)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
node_modules/
|
||||
dist/
|
||||
@@ -0,0 +1,6 @@
|
||||
<!doctype html>
|
||||
<meta charset="utf-8"><title>servervision</title>
|
||||
<style>html,body{margin:0;height:100%;overflow:hidden;background:#000}
|
||||
#bar{position:fixed;top:0;left:0;right:0;padding:2px 8px;font:12px monospace;color:#0f0;background:#000a;z-index:1;pointer-events:none}</style>
|
||||
<div id="bar"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
+1314
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"name": "servervision-client",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc && vite build",
|
||||
"check": "node --test src/state.test.ts"
|
||||
},
|
||||
"dependencies": { "pixi.js": "^8.0.0" },
|
||||
"devDependencies": { "typescript": "^5.6.0", "vite": "^6.0.0", "@types/node": "^22.0.0" }
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import { Application, Container, Graphics, Sprite, Text, Texture } from 'pixi.js';
|
||||
import { apply, newState, tilesOfCells, type Tok, type V2 } from './state.ts';
|
||||
|
||||
const R = 20; // token radius, world px
|
||||
const s = newState();
|
||||
const bar = document.getElementById('bar')!;
|
||||
let conn = 'connecting';
|
||||
const status = () => (bar.textContent = `role=${s.role ?? '?'} conn=${conn} gseq=${s.gseq}${s.lastError ? ' err=' + s.lastError : ''}`);
|
||||
|
||||
const app = new Application();
|
||||
await app.init({ resizeTo: window, background: 0x000000, antialias: true });
|
||||
document.body.appendChild(app.canvas);
|
||||
|
||||
const world = new Container();
|
||||
const tilesL = new Container();
|
||||
const doorsG = new Graphics();
|
||||
const tokensL = new Container();
|
||||
// Fog: dim = everywhere except current vision; black = everywhere except explored. Inverse stencil masks.
|
||||
const dim = new Graphics();
|
||||
const black = new Graphics();
|
||||
const visionM = new Graphics();
|
||||
const exploredM = new Graphics();
|
||||
dim.addChild(visionM); dim.setMask({ mask: visionM, inverse: true });
|
||||
black.addChild(exploredM); black.setMask({ mask: exploredM, inverse: true });
|
||||
world.addChild(tilesL, dim, black, doorsG, tokensL);
|
||||
app.stage.addChild(world);
|
||||
|
||||
// ---- tiles ----
|
||||
const tileState = new Map<string, 'loading' | 'ok' | 'fail'>();
|
||||
function loadTile(key: string) {
|
||||
if (tileState.has(key) && tileState.get(key) !== 'fail') return;
|
||||
tileState.set(key, 'loading');
|
||||
fetch(`/tiles/${key}.png`)
|
||||
.then((r) => (r.ok ? r.blob() : Promise.reject(r.status))) // 403 = not available (yet)
|
||||
.then((b) => createImageBitmap(b))
|
||||
.then((bmp) => {
|
||||
const [x, y] = key.split('_').map(Number);
|
||||
const sp = new Sprite(Texture.from(bmp));
|
||||
sp.position.set(x * s.tileSize, y * s.tileSize);
|
||||
tilesL.addChild(sp);
|
||||
tileState.set(key, 'ok');
|
||||
})
|
||||
.catch(() => tileState.set(key, 'fail'));
|
||||
}
|
||||
|
||||
// ---- tokens ----
|
||||
const sprites = new Map<string, Container>();
|
||||
const dragging = new Map<string, true>();
|
||||
function drawToken(t: Tok) {
|
||||
let c = sprites.get(t.id);
|
||||
if (!c) {
|
||||
c = new Container();
|
||||
const g = new Graphics().circle(0, 0, R).fill(t.mine ? 0x3a9d3a : 0xb03030).stroke({ width: 3, color: 0xffffff });
|
||||
const l = new Text({ text: t.name, style: { fontSize: 14, fill: 0xffffff, stroke: { color: 0, width: 3 } } });
|
||||
l.anchor.set(0.5, 0); l.y = R + 2;
|
||||
c.addChild(g, l);
|
||||
tokensL.addChild(c); sprites.set(t.id, c);
|
||||
}
|
||||
if (!dragging.has(t.id)) c.position.set(t.pos[0], t.pos[1]); // incoming pos ignored while locally dragging
|
||||
}
|
||||
const canDrag = (t: Tok) => s.role === 'gm' || t.mine;
|
||||
|
||||
// ---- ws ----
|
||||
let ws: WebSocket;
|
||||
const send = (o: object) => ws.readyState === 1 && ws.send(JSON.stringify(o));
|
||||
let reqId = 0;
|
||||
const pending = new Map<number, string>();
|
||||
|
||||
function onMsg(m: any) {
|
||||
if (m.t === 'moveAck') {
|
||||
const id = pending.get(m.reqId); pending.delete(m.reqId);
|
||||
if (!m.ok && id && !dragging.has(id)) { // snap to server pos
|
||||
const t = s.tokens.get(id), c = sprites.get(id);
|
||||
if (t) t.pos = m.pos;
|
||||
c?.position.set(m.pos[0], m.pos[1]);
|
||||
}
|
||||
s.gseq = m.gseq;
|
||||
return;
|
||||
}
|
||||
const fresh = apply(s, m);
|
||||
switch (m.t) {
|
||||
case 'hello':
|
||||
fit();
|
||||
if (s.role === 'gm') { dim.visible = black.visible = false; const n = Math.ceil(s.w / s.tileSize), k = Math.ceil(s.h / s.tileSize); for (let y = 0; y < k; y++) for (let x = 0; x < n; x++) loadTile(x + '_' + y); }
|
||||
else { for (const g of [dim, black]) g.clear().rect(0, 0, s.w, s.h).fill(0x000000); dim.alpha = 0.6; }
|
||||
break;
|
||||
case 'walls': case 'door': drawDoors(); break;
|
||||
case 'vision':
|
||||
visionM.clear();
|
||||
for (const p of s.polys) visionM.poly(p.flat()).fill(0xffffff);
|
||||
break;
|
||||
case 'explored':
|
||||
if (fresh!.length) {
|
||||
for (const [cx, cy] of fresh!) exploredM.rect(cx * s.cell, cy * s.cell, s.cell, s.cell);
|
||||
exploredM.fill(0xffffff); // shortcut: Graphics grows unbounded, re-tessellates; bake to RenderTexture when cells >~50k
|
||||
// retry failed/unrequested tiles under newly explored cells
|
||||
for (const k of tilesOfCells(fresh!, s)) loadTile(k);
|
||||
}
|
||||
break;
|
||||
case 'token': drawToken(s.tokens.get(m.id)!); break;
|
||||
case 'remove': sprites.get(m.id)?.destroy({ children: true }); sprites.delete(m.id); break;
|
||||
}
|
||||
}
|
||||
function connect() {
|
||||
ws = new WebSocket(`${location.protocol === 'https:' ? 'wss' : 'ws'}://${location.host}/ws`);
|
||||
ws.onopen = () => { conn = 'open'; status(); };
|
||||
ws.onclose = () => { conn = 'closed (retry 2s)'; status(); setTimeout(connect, 2000); }; // shortcut: no state reset on reconnect, assumes server resends full state/hello; verify
|
||||
ws.onmessage = (e) => { onMsg(JSON.parse(e.data)); status(); };
|
||||
}
|
||||
|
||||
// ---- walls (GM only) ----
|
||||
function drawDoors() {
|
||||
doorsG.clear();
|
||||
for (const w of s.walls.values()) {
|
||||
doorsG.moveTo(...w.a).lineTo(...w.b).stroke({ width: w.door ? 6 : 3, color: w.door ? (w.open ? 0x40ff40 : 0xff4040) : 0xffff00 });
|
||||
}
|
||||
}
|
||||
function pickDoor(p: V2): string | null {
|
||||
const tol = 10 / world.scale.x;
|
||||
for (const w of s.walls.values()) {
|
||||
if (!w.door) continue;
|
||||
const [ax, ay] = w.a, [bx, by] = w.b, dx = bx - ax, dy = by - ay;
|
||||
const u = Math.max(0, Math.min(1, ((p[0] - ax) * dx + (p[1] - ay) * dy) / (dx * dx + dy * dy || 1)));
|
||||
if (Math.hypot(p[0] - (ax + u * dx), p[1] - (ay + u * dy)) < tol) return w.id;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ---- camera + input ----
|
||||
function fit() { const k = Math.min(innerWidth / s.w, innerHeight / s.h); world.scale.set(k); world.position.set(0, 0); }
|
||||
const toWorld = (e: PointerEvent | WheelEvent): V2 => [(e.clientX - world.x) / world.scale.x, (e.clientY - world.y) / world.scale.x];
|
||||
let pan: { x: number; y: number } | null = null;
|
||||
let drag: { id: string; dx: number; dy: number; last: number } | null = null;
|
||||
const moveTok = (id: string, pos: V2) => { const r = ++reqId; pending.set(r, id); send({ t: 'move', reqId: r, id, pos }); };
|
||||
const cv = app.canvas;
|
||||
cv.addEventListener('pointerdown', (e) => {
|
||||
cv.setPointerCapture(e.pointerId);
|
||||
const p = toWorld(e);
|
||||
for (const [id, c] of [...sprites].reverse()) { // O(N) hit test on press
|
||||
const t = s.tokens.get(id)!;
|
||||
if (canDrag(t) && Math.hypot(p[0] - c.x, p[1] - c.y) <= R) { drag = { id, dx: c.x - p[0], dy: c.y - p[1], last: 0 }; dragging.set(id, true); return; }
|
||||
}
|
||||
if (s.role === 'gm') { const d = pickDoor(p); if (d) { send({ t: 'door', id: d, open: !s.walls.get(d)!.open }); return; } }
|
||||
pan = { x: e.clientX - world.x, y: e.clientY - world.y };
|
||||
});
|
||||
cv.addEventListener('pointermove', (e) => {
|
||||
if (drag) {
|
||||
const p = toWorld(e), pos: V2 = [p[0] + drag.dx, p[1] + drag.dy];
|
||||
sprites.get(drag.id)!.position.set(pos[0], pos[1]); // optimistic
|
||||
const now = performance.now();
|
||||
if (now - drag.last >= 50) { drag.last = now; moveTok(drag.id, pos); }
|
||||
} else if (pan) world.position.set(e.clientX - pan.x, e.clientY - pan.y);
|
||||
});
|
||||
const up = () => {
|
||||
if (drag) {
|
||||
const c = sprites.get(drag.id)!, pos: V2 = [c.x, c.y];
|
||||
moveTok(drag.id, pos); // final
|
||||
const t = s.tokens.get(drag.id); if (t) t.pos = pos;
|
||||
dragging.delete(drag.id); drag = null;
|
||||
}
|
||||
pan = null;
|
||||
};
|
||||
cv.addEventListener('pointerup', up); cv.addEventListener('pointercancel', up);
|
||||
cv.addEventListener('wheel', (e) => {
|
||||
e.preventDefault();
|
||||
const p = toWorld(e), k = Math.max(0.05, Math.min(8, world.scale.x * Math.exp(-e.deltaY * 0.001)));
|
||||
world.scale.set(k); world.position.set(e.clientX - p[0] * k, e.clientY - p[1] * k);
|
||||
}, { passive: false });
|
||||
|
||||
status();
|
||||
connect();
|
||||
@@ -0,0 +1,36 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { apply, newState, tilesOfCells } from './state.ts';
|
||||
|
||||
test('protocol reducer: fake server script', () => {
|
||||
const s = newState();
|
||||
apply(s, { t: 'hello', gseq: 1, role: 'player', tokens: ['a'], world: { w: 4096, h: 4096 }, tileSize: 512, exploredCell: 64 });
|
||||
assert.equal(s.role, 'player');
|
||||
assert.equal(s.walls.size, 0); // players never get walls
|
||||
assert.deepEqual(apply(s, { t: 'explored', gseq: 2, cells: [[0, 0], [1, 0]] }), [[0, 0], [1, 0]]);
|
||||
assert.deepEqual(apply(s, { t: 'explored', gseq: 3, cells: [[1, 0], [2, 0]] }), [[2, 0]]); // diff accumulates
|
||||
assert.equal(s.explored.size, 3);
|
||||
apply(s, { t: 'vision', gseq: 4, polys: [[[0, 0], [1, 0], [1, 1]]] });
|
||||
apply(s, { t: 'vision', gseq: 5, polys: [] });
|
||||
assert.equal(s.polys.length, 0); // full replacement
|
||||
apply(s, { t: 'token', gseq: 6, id: 'a', name: 'A', kind: 'pc', pos: [5, 6], mine: true });
|
||||
apply(s, { t: 'token', gseq: 7, id: 'a', name: 'A', kind: 'pc', pos: [7, 8], mine: true });
|
||||
assert.deepEqual(s.tokens.get('a')!.pos, [7, 8]);
|
||||
apply(s, { t: 'remove', gseq: 8, id: 'a' });
|
||||
assert.equal(s.tokens.size, 0);
|
||||
assert.equal(s.gseq, 8);
|
||||
});
|
||||
|
||||
test('gm walls + door', () => {
|
||||
const s = newState();
|
||||
apply(s, { t: 'walls', gseq: 1, walls: [{ id: 'd1', a: [0, 0], b: [10, 0], door: true, open: false }] });
|
||||
apply(s, { t: 'door', gseq: 2, id: 'd1', open: true });
|
||||
assert.equal(s.walls.get('d1')!.open, true);
|
||||
});
|
||||
|
||||
test('tilesOfCells', () => {
|
||||
const g = { w: 4096, h: 4096, tileSize: 512, cell: 64 };
|
||||
assert.deepEqual([...tilesOfCells([[0, 0], [7, 7]], g)], ['0_0']);
|
||||
assert.deepEqual([...tilesOfCells([[8, 0]], g)], ['1_0']);
|
||||
assert.deepEqual([...tilesOfCells([[0, 0]], { ...g, cell: 1024 })].length, 4); // cell spans 2x2 tiles
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
// Pure protocol state + reducer (no Pixi) so it can be checked without a server.
|
||||
export type V2 = [number, number];
|
||||
export type Tok = { id: string; name: string; kind: string; pos: V2; mine: boolean };
|
||||
export type Wall = { id: string; a: V2; b: V2; door: boolean; open: boolean };
|
||||
export type Msg = { t: string; gseq: number; [k: string]: any };
|
||||
|
||||
export type State = {
|
||||
role: 'gm' | 'player' | null;
|
||||
owned: string[];
|
||||
w: number; h: number; tileSize: number; cell: number;
|
||||
walls: Map<string, Wall>;
|
||||
polys: V2[][];
|
||||
explored: Set<string>;
|
||||
tokens: Map<string, Tok>;
|
||||
gseq: number;
|
||||
lastError: string;
|
||||
};
|
||||
|
||||
export const newState = (): State => ({
|
||||
role: null, owned: [], w: 0, h: 0, tileSize: 512, cell: 32,
|
||||
walls: new Map(), polys: [], explored: new Set(), tokens: new Map(), gseq: 0, lastError: '',
|
||||
});
|
||||
|
||||
// Returns newly-added explored cells (only for t=explored), else undefined.
|
||||
export function apply(s: State, m: Msg): V2[] | undefined {
|
||||
s.gseq = m.gseq;
|
||||
switch (m.t) {
|
||||
case 'hello':
|
||||
s.role = m.role; s.owned = m.tokens; s.w = m.world.w; s.h = m.world.h;
|
||||
s.tileSize = m.tileSize; s.cell = m.exploredCell;
|
||||
break;
|
||||
case 'walls':
|
||||
s.walls = new Map((m.walls as Wall[]).map((w) => [w.id, w]));
|
||||
break;
|
||||
case 'door': {
|
||||
const w = s.walls.get(m.id);
|
||||
if (w) w.open = m.open;
|
||||
break;
|
||||
}
|
||||
case 'vision': s.polys = m.polys; break;
|
||||
case 'explored': {
|
||||
const fresh: V2[] = [];
|
||||
for (const c of m.cells as V2[]) {
|
||||
const k = c[0] + ',' + c[1];
|
||||
if (!s.explored.has(k)) { s.explored.add(k); fresh.push(c); }
|
||||
}
|
||||
return fresh;
|
||||
}
|
||||
case 'token':
|
||||
s.tokens.set(m.id, { id: m.id, name: m.name, kind: m.kind, pos: m.pos, mine: !!m.mine });
|
||||
break;
|
||||
case 'remove': s.tokens.delete(m.id); break;
|
||||
case 'error': s.lastError = m.msg; break;
|
||||
// moveAck handled by the view (needs pending/drag state)
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Tile keys "x_y" overlapped by the given explored cells.
|
||||
export function tilesOfCells(cells: V2[], s: Pick<State, 'w' | 'h' | 'tileSize' | 'cell'>): Set<string> {
|
||||
const out = new Set<string>();
|
||||
const maxX = Math.ceil(s.w / s.tileSize) - 1, maxY = Math.ceil(s.h / s.tileSize) - 1;
|
||||
for (const [cx, cy] of cells) {
|
||||
const x0 = Math.floor((cx * s.cell) / s.tileSize), x1 = Math.floor(((cx + 1) * s.cell - 1) / s.tileSize);
|
||||
const y0 = Math.floor((cy * s.cell) / s.tileSize), y1 = Math.floor(((cy + 1) * s.cell - 1) / s.tileSize);
|
||||
for (let y = Math.max(0, y0); y <= Math.min(maxY, y1); y++)
|
||||
for (let x = Math.max(0, x0); x <= Math.min(maxX, x1); x++) out.add(x + '_' + y);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022", "module": "ESNext", "moduleResolution": "bundler",
|
||||
"lib": ["ES2022", "DOM"], "strict": true, "noEmit": true, "skipLibCheck": true,
|
||||
"allowImportingTsExtensions": true, "erasableSyntaxOnly": true, "types": ["node"]
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export default { base: './', build: { target: 'es2022' } };
|
||||
@@ -13,6 +13,9 @@
|
||||
"gen": [
|
||||
"node tools/genmap.mjs"
|
||||
],
|
||||
"client": [
|
||||
"cd client && npm install --silent && npm run check && npm run build"
|
||||
],
|
||||
"test": [
|
||||
"node tools/genmap.mjs",
|
||||
"nimble test"
|
||||
|
||||
Reference in New Issue
Block a user