xonecas.ioDon't click! Sean Caetano Martin Sign in

space-browser / commits / bc7914e

feat: scene is now server authorative

Asteroids droppped form design, their function passed to barren planets.

xonecas5 weeks agobc7914e344b4c8b73b04ba6705b136d9f14ca86eparent 5be9bf57 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

GAME_DESIGN.md+8-7
@@ -9,7 +9,7 @@ A ruthless browser mini-MMO of survival, physical ship-building, and deep-space
99 ## Lessons from Iterations 1 & 2
1010
1111 1. **Resolution vs. Zoom Scale:** Both previous iterations used a fixed monospace character grid while trying to zoom continuously from ship scale to full galaxy scale in one scene. At close zoom, ships had enough character cells for silhouette; zooming out collapsed ships, planets, and POIs into 1–2 flickering character cells, turning everything into indistinguishable smudges. **Fix:** Split the game into two dedicated scenes (**Local Space** and **Galaxy Map**) and shrink the overall scale s …
12-2. **Static Orbits:** Both iterations generated orbital radii and angles for planets and POIs, but never advanced them over time. Nothing revolved around stars, and "orbiting" a POI simply stopped the ship at a standoff distance. **Fix:** All planets and asteroid fields actively revolve around their stars, and orbiting a POI anchors the player to its moving trajectory.
12+2. **Static Orbits:** Both iterations generated orbital radii and angles for planets and POIs, but never advanced them over time. Nothing revolved around stars, and "orbiting" a POI simply stopped the ship at a standoff distance. **Fix:** All planets actively revolve around their stars, and orbiting a POI anchors the player to its moving trajectory.
1313 3. **Passive Combat & Blind Ranges:** Iteration 1 required manual targeting and suffered from shot tunneling; Iteration 2 used unavoidable homing projectiles that damaged random pieces, while NPCs were single static ships that stopped at max range. Neither showed weapon ranges. **Fix:** Visible weapon range rings (yours and the enemy's), roaming multi-ship Rogue AI packs, Galaxy Security patrols, and directional positioning combat in which damaged pieces can be lost permanently.
1414 4. **Ship Movement Feel:** Iteration 1 used per-piece spring physics that made ships lag and snake awkwardly on turns; Iteration 2 used a whole-hull velocity offset that made the ship wobble away from its true center. **Fix:** Ships fly as a rigid, responsive cluster — rotation and steering are immediate and predictable, and a ship only stops being one piece when the graph is actually severed.
1515 5. **Web UI Crutches:** Both iterations leaned on DOM cargo slots, right-click dropdown menus, and SVG modals (ship editor) instead of solving interactions in the game world. Every one of those panels was a place where the game stopped being a game. **Fix:** Eliminate cargo slots and editor modals; ore is physically towed in space and ship pieces are dragged directly onto or off the hull.
@@ -47,8 +47,8 @@ Inspired by the amber/sepia monospace terminal animation of `xonecas.io`. The wo
4747
4848 - **Shared Seed & Collective Fog of War:** One deterministic galaxy shared by all players. Only the central spawn systems start revealed. Exploring new space permanently lifts the fog of war for all players. First discoverers can name unnamed stars and planets while orbiting them.
4949 - **Smaller Scale:** System sizes and inter-system gaps are compact enough that traversal is brisk, encounters are frequent, and stars and planets feel present rather than lost in empty void.
50-- **Active Orbital Motion:** Stars sit at system centers; planets and asteroid fields continuously revolve around their stars along visible orbital paths.
51-- **Orbit Anchoring:** Clicking a POI to orbit moves the ship into its orbit ring and anchors the ship to the POI's orbital motion. While orbiting a moving planet or asteroid field, the player travels with it around the star.
50+- **Active Orbital Motion:** Stars sit at system centers; planets continuously revolve around their stars along visible orbital paths.
51+- **Orbit Anchoring:** Clicking a POI to orbit moves the ship into its orbit ring and anchors the ship to the POI's orbital motion. While orbiting a moving planet, the player travels with it around the star.
5252 - **One Pressure Gradient:** The galactic core is dense, protected, and shipyard-rich; the rim is sparse, hostile, and shipyard-poor. Distance from the center is the single difficulty dial for hostiles, shipyards, and the value of what you can bring home.
5353
5454 ---
@@ -58,8 +58,9 @@ Inspired by the amber/sepia monospace terminal animation of `xonecas.io`. The wo
5858 Every POI has a clear gameplay function. Nothing decorative.
5959
6060 - **Stars:** Deadly cosmic hazards at the heart of each system. Colliding with a star destroys ship pieces on contact.
61-- **Planets:** Orbit stars. A subset of planets have **Shipyard** capabilities (refueling, crafting, upgrading, and repairing). Shipyard Planets are common in the central spawn systems and become increasingly rare toward the galaxy edges in a smooth progression.
62-- **Asteroid Fields:** Orbit stars. While anchored in orbit around an asteroid field, the player automatically pulls physical ore out of the field at a steady rate per second (no "collect ore" menu clicks). A field holds a finite amount and regrows over time, so a single field cannot be farmed forever — plenty is what makes you move.
61+- **Planets:** Orbit stars. Every planet is one of two kinds.
62+ - **Shipyard Planets:** Provide refuelling, crafting, upgrading, and repairing. Common in the central spawn systems and increasingly rare toward the galaxy edges in a smooth progression.
63+ - **Barren Planets:** The ore bodies of the galaxy. While anchored in orbit around a barren planet, the player automatically pulls physical ore out of it at a steady rate per second (no "collect ore" menu clicks). Each planet holds a finite amount and regrows it over time, so a single planet cannot be farmed forever — plenty is what makes you move.
6364 - **Wrecks:** Physical clusters of severed or destroyed ship pieces and loose ore drifting in space, left behind by defeated ships and dead players. Wrecks are the only source of new ship pieces.
6465 - **Rogue AI (Hostile):** Roaming groups of ships that patrol their system and hunt anything that enters it. Common and weak (small ships, small groups) near the center of the galaxy; larger ships in much greater numbers toward the outer edges. They do not leave their system.
6566 - **Galaxy Security (Friendly NPCs):** Friendly patrol ships that guard spawn systems and Planets with Shipyards, and hunt anyone who attacks within their system. They use the exact same ship piece system, stats, and combat rules as players and Rogue AI — systemic protection instead of artificial invulnerability zones.
@@ -101,7 +102,7 @@ Combat is frequent, automated, and controlled purely through movement and positi
101102 - Enemy weapon range rings are clearly drawn when approaching or engaging hostiles, so the player always sees the exact line between safety and danger.
102103 - **Movement as Control:** Because firing is automatic and projectiles hit physical pieces on the hull, combat skill comes from kiting, maintaining optimal range, using orbital motion, and rotating the ship so Square armor pieces absorb fire before Triangle guns or the root piece are severed. Leaving range is the only way to break off a fight.
103104 - **Players Are Not Special:** The same rules apply to other players. Automated fire does not ask permission; anyone in range gets shot, and Galaxy Security hunts whoever shoots first in a core system. Every piece lost or gained in a fight stays lost or gained.
104-- **What Combat Pays:** Ship pieces come only from wrecks. Ore comes from asteroid fields and from the loose ore left in wrecks. You can survive by mining, but everything you fly comes from fights you won.
105+- **What Combat Pays:** Ship pieces come only from wrecks. Ore comes from barren planets and from the loose ore left in wrecks. You can survive by mining, but everything you fly comes from fights you won.
105106
106107 ---
107108
@@ -127,7 +128,7 @@ Combat is frequent, automated, and controlled purely through movement and positi
127128 ## Core Loop & Permadeath
128129
129130 1. **Deploy:** Enter a unique callsign, pick a starting Tier 1 piece (Triangle, Square, or Circle), and spawn in orbit of a Galaxy Security-protected core planet.
130-2. **Harvest & Scavenge:** Orbit Asteroid Fields to pull out physical ore per second, or hunt Rogue AI in and near the core and salvage their wrecks for ship pieces and loose ore.
131+2. **Harvest & Scavenge:** Orbit barren planets to pull out physical ore per second, or hunt Rogue AI in and near the core and salvage their wrecks for ship pieces and loose ore.
131132 3. **Tow, Stash & Build:** Tow ore (`Circles + 1`) to a Shipyard Planet (or hide stashes in space) to craft and upgrade pieces, dragging them directly onto your ship graph.
132133 4. **Expedition Outward:** Use the Galaxy Map to plot fuel-efficient Deep Space routes into the fog of war. Fight or cross Rogue AI packs that grow as Shipyard Planets and Galaxy Security disappear.
133134 5. **Endgame Rim:** Reach the treacherous outer edges to find rare edge Shipyards and craft **Star** pieces, the only way to survive a run that keeps going.
client/src/main.ts+89-166
@@ -1,80 +1,37 @@
1-import { connect, type Remote } from './net';
2-import {
3- attach,
4- detach,
5- nextPieceId,
6- toWorld,
7- GRAB,
8- makeShip,
9- step,
10- type Loose,
11- type Piece,
12- type Ship,
13-} from './sim';
1+import { connect, type State } from './net';
2+import type { Loose, Ship } from './sim';
143 import { View, CELL, CELL_WORLD, ZOOM_MIN, ZOOM_MAX, type Camera } from './view';
15-import { makeSystem, stepSystem, type Planet } from './world';
164
175 const canvas = document.getElementById('view') as HTMLCanvasElement;
186 const view = new View(canvas);
197 addEventListener('resize', () => view.resize());
208
21-const sys = makeSystem();
22-view.system(sys);
23-
24-// Clear of the star, out where the whole system is in reach of the camera.
25-const SPAWN = { x: 0, y: -70 };
26-const own = makeShip(0, '', SPAWN.x, SPAWN.y);
27-const others = new Map<number, Ship>();
28-// A few pieces lying around the spawn, to build onto the starting triangle.
29-const loose: Loose[] = [
30- { id: nextPieceId(), kind: 'armor', x: 30, y: -20, h: 0 },
31- { id: nextPieceId(), kind: 'cargo', x: 37, y: 18, h: 0 },
32- { id: nextPieceId(), kind: 'engine', x: -29, y: 26, h: 0 },
33- { id: nextPieceId(), kind: 'gun', x: -35, y: -22, h: 0 },
34-];
35-let held: Loose | null = null;
36-let marker: { x: number; y: number } | null = null;
37-
38-// Clear of the hull, so the ring the ship parks on never touches the body.
39-const STANDOFF = 26;
40-const STAR_STANDOFF = 34; // a star kills on contact: its ring is further out
41-const HIT = 1.5; // click radius of a body, as a multiple of its radius: covers its outermost ring
42-
43-// Orbiting parks the ship on a body's ring: the target is a point bolted to the
44-// body's frame, so a planet drags the ship around its star and a star holds still.
45-type Orbit = { body: Planet | 'star'; x: number; y: number; a0: number };
46-let orbit: Orbit | null = null;
47-
48-function bodyAt(x: number, y: number): Planet | 'star' | null {
49- for (const p of sys.planets) if (Math.hypot(p.x - x, p.y - y) < p.r * HIT) return p;
50- return Math.hypot(x, y) < sys.star * HIT ? 'star' : null;
51-}
52-
53-function orbitAt(b: Planet | 'star', from: { x: number; y: number }): Orbit {
54- if (b === 'star') {
55- const a = Math.atan2(from.y, from.x);
56- const r = sys.star + STAR_STANDOFF;
57- return { body: b, x: Math.cos(a) * r, y: Math.sin(a) * r, a0: 0 };
9+// Everything drawn comes from the server. We only send intents: pick up what is
10+// under the cursor, report the drag, drop it and let the server decide.
11+let state: State | null = null;
12+const net = connect((s) => {
13+ const first = state === null;
14+ state = s;
15+ if (first) {
16+ const me = s.players.find((p) => p.id === s.you);
17+ if (me) {
18+ cam.x = me.x;
19+ cam.y = me.y;
20+ }
5821 }
59- // Enter the ring on the side we are already on, so the ship moves radially in.
60- const a = Math.atan2(from.y - b.y, from.x - b.x);
61- const r = b.r + STANDOFF;
62- return { body: b, x: b.x + Math.cos(a) * r, y: b.y + Math.sin(a) * r, a0: b.angle };
63-}
22+});
6423
65-// The planet's own rotation carries its ring point around the star with it.
66-function orbitTarget(o: Orbit): { x: number; y: number } {
67- if (o.body === 'star') return { x: o.x, y: o.y };
68- const d = o.body.angle - o.a0;
69- const c = Math.cos(d);
70- const s = Math.sin(d);
71- return { x: o.x * c - o.y * s, y: o.x * s + o.y * c };
72-}
24+// The server reports at tick rate; we ease our copies toward it so movement reads
25+// smooth without ever deciding anything ourselves.
26+const ships = new Map<number, Ship>();
27+const loose = new Map<number, Loose>();
7328
74-const cam: Camera & { follow: boolean } = { x: own.x, y: own.y, zoom: 0.5, follow: true };
29+const cam: Camera & { follow: boolean } = { x: 0, y: 0, zoom: 0.5, follow: true };
7530 const keys = new Set<string>();
76-let drag: { x: number; y: number } | null = null;
77-let sendIn = 0;
31+let pan0: { x: number; y: number } | null = null; // right/middle drag moves the camera
32+let pulling = false; // left button down: keep reporting where the piece is
33+let pullTo: { x: number; y: number } | null = null;
34+let pullIn = 0;
7835
7936 const wpc = () => CELL_WORLD / cam.zoom; // world units per character cell
8037 const wpp = () => wpc() / CELL; // world units per css px
@@ -91,93 +48,33 @@ const at = (e: MouseEvent) => {
9148 };
9249 };
9350
94-const net = connect(
95- (w) => {
96- if (own.id) return; // spawn once
97- own.id = w.id;
98- own.name = w.name;
99- own.x = own.tx = SPAWN.x;
100- for (const l of loose) {
101- l.x += own.x; // the wreckage lies where we wake up
102- l.y += own.y;
103- }
104- marker = null;
105- },
106- (players: Remote[]) => {
107- if (!own.id) return; // welcome first: never mirror ourselves as a stranger
108- for (const p of players) {
109- if (p.id === own.id) continue;
110- const s = others.get(p.id);
111- if (!s) {
112- const n = makeShip(p.id, p.name, p.x, p.y);
113- others.set(p.id, n);
114- continue;
115- }
116- s.tx = p.x;
117- s.ty = p.y;
118- s.h = p.h;
119- }
120- for (const id of others.keys()) if (!players.some((p) => p.id === id)) others.delete(id);
121- },
122-);
123-
124-// A piece under the cursor is picked up: loose ones straight off the ground, hull
125-// pieces torn off their ship (with whatever hung below them). Root stays put.
126-function grab(x: number, y: number): Loose | null {
127- const l = loose.find((l) => Math.hypot(l.x - x, l.y - y) < GRAB);
128- if (l) return l;
129- let hit: Piece | null = null;
130- let best = GRAB;
131- for (const p of own.pieces) {
132- const w = toWorld(own, p);
133- const d = Math.hypot(w.x - x, w.y - y);
134- if (d < best) {
135- best = d;
136- hit = p;
137- }
138- }
139- const off = hit && detach(own, hit.id);
140- if (!off) return null;
141- loose.push(...off);
142- return loose.find((l) => l.id === hit!.id)!;
143-}
144-
14551 addEventListener('pointerdown', (e) => {
14652 if (e.button !== 0) {
147- drag = { x: e.clientX, y: e.clientY };
53+ pan0 = { x: e.clientX, y: e.clientY };
14854 return;
14955 }
15056 const p = at(e);
151- held = grab(p.x, p.y);
152- if (held) {
153- orbit = null;
154- return;
155- }
156- const body = bodyAt(p.x, p.y);
157- orbit = body ? orbitAt(body, own) : null;
158- if (orbit) return; // the frame loop aims at the ring from here on
159- own.tx = p.x;
160- own.ty = p.y;
161- marker = { x: p.x, y: p.y };
57+ pulling = true;
58+ net.send({ t: 'pick', x: p.x, y: p.y });
16259 });
16360
16461 addEventListener('pointermove', (e) => {
165- if (held) {
166- const p = at(e);
167- held.x = p.x;
168- held.y = p.y;
62+ if (pan0) {
63+ pan(-(e.clientX - pan0.x) * wpp(), (e.clientY - pan0.y) * wpp());
64+ pan0 = { x: e.clientX, y: e.clientY };
16965 return;
17066 }
171- if (!drag) return;
172- pan(-(e.clientX - drag.x) * wpp(), (e.clientY - drag.y) * wpp());
173- drag = { x: e.clientX, y: e.clientY };
67+ if (!pulling) return;
68+ pullTo = at(e);
17469 });
175-addEventListener('pointerup', () => {
176- drag = null;
177- if (!held) return;
178- // Dropped on the hull it bolts on; dropped in space it stays where it lands.
179- if (attach(own, held)) loose.splice(loose.indexOf(held), 1);
180- held = null;
70+
71+addEventListener('pointerup', (e) => {
72+ pan0 = null;
73+ if (!pulling) return;
74+ pulling = false;
75+ pullTo = null;
76+ const p = at(e);
77+ net.send({ t: 'drop', x: p.x, y: p.y });
18178 });
18279 addEventListener('contextmenu', (e) => e.preventDefault());
18380
@@ -198,26 +95,15 @@ addEventListener('keydown', (e) => {
19895 });
19996 addEventListener('keyup', (e) => keys.delete(e.code));
20097
98+const ease = (a: number, b: number, k: number) => a + (b - a) * k;
99+const turn = (a: number, b: number, k: number) => a + Math.atan2(Math.sin(b - a), Math.cos(b - a)) * k;
100+
201101 let last = performance.now();
202102 function frame(): void {
203103 const now = performance.now();
204104 const dt = Math.min(0.05, Math.max(0, now - last) / 1000);
205105 last = now;
206106
207- stepSystem(sys, dt);
208- if (orbit) {
209- // Re-aim every frame: the ring point the ship parks on travels with its body.
210- const t = orbitTarget(orbit);
211- own.tx = t.x;
212- own.ty = t.y;
213- marker = t;
214- }
215- step(own, dt);
216- const k = 1 - Math.exp(-dt * 12);
217- for (const s of others.values()) {
218- s.x += (s.tx - s.x) * k;
219- s.y += (s.ty - s.y) * k;
220- }
221107 // Pan on screen-space speed so it feels the same at every zoom.
222108 const px = (keys.has('KeyD') || keys.has('ArrowRight') ? 1 : 0) - (keys.has('KeyA') || keys.has('ArrowLeft') ? 1 : 0);
223109 const py = (keys.has('KeyW') || keys.has('ArrowUp') ? 1 : 0) - (keys.has('KeyS') || keys.has('ArrowDown') ? 1 : 0);
@@ -225,19 +111,56 @@ function frame(): void {
225111 const s = (30 * wpc() * dt) / Math.hypot(px, py); // 30 cells / second
226112 pan(px * s, py * s);
227113 }
228- if (cam.follow) {
229- const k = 1 - Math.exp(-dt * 8);
230- cam.x += (own.x - cam.x) * k;
231- cam.y += (own.y - cam.y) * k;
114+
115+ if (pullTo && (pullIn += dt) > 1 / 30) {
116+ pullIn = 0;
117+ net.send({ t: 'drag', x: pullTo.x, y: pullTo.y });
118+ pullTo = null;
119+ }
120+
121+ const k = 1 - Math.exp(-dt * 12);
122+ if (state) {
123+ const live = new Set<number>();
124+ for (const p of state.players) {
125+ live.add(p.id);
126+ let s = ships.get(p.id);
127+ if (!s) {
128+ ships.set(p.id, (s = { ...p }));
129+ } else {
130+ s.x = ease(s.x, p.x, k);
131+ s.y = ease(s.y, p.y, k);
132+ s.h = turn(s.h, p.h, k);
133+ s.tx = p.tx;
134+ s.ty = p.ty;
135+ s.pieces = p.pieces; // a hull is never eased: a piece is where the server says
136+ }
137+ }
138+ for (const id of ships.keys()) if (!live.has(id)) ships.delete(id);
139+
140+ const looseLive = new Set<number>();
141+ for (const l of state.loose) {
142+ looseLive.add(l.id);
143+ const d = loose.get(l.id);
144+ if (!d) loose.set(l.id, { ...l });
145+ else {
146+ d.x = ease(d.x, l.x, k);
147+ d.y = ease(d.y, l.y, k);
148+ d.h = turn(d.h, l.h, k);
149+ }
150+ }
151+ for (const id of loose.keys()) if (!looseLive.has(id)) loose.delete(id);
232152 }
233153
234- sendIn += dt;
235- if (sendIn > 1 / 30) {
236- sendIn = 0;
237- net.send({ t: 'pos', x: own.x, y: own.y, h: own.h });
154+ const me = state ? ships.get(state.you) : undefined;
155+ if (cam.follow && me) {
156+ const c = 1 - Math.exp(-dt * 8);
157+ cam.x = ease(cam.x, me.x, c);
158+ cam.y = ease(cam.y, me.y, c);
238159 }
239160
240- view.draw(cam, [own, ...others.values()], own.id, loose, marker);
161+ // The marker is the order the server is flying: never a click of our own.
162+ const marker = me && !state?.held ? { x: me.tx, y: me.ty } : null;
163+ view.draw(cam, state?.bodies ?? [], [...ships.values()], state?.you ?? 0, [...loose.values()], marker);
241164 requestAnimationFrame(frame);
242165 }
243166 requestAnimationFrame(frame);
client/src/net.ts+7-9
@@ -1,18 +1,16 @@
1-// One socket is one player. Server broadcasts every player's position at 15Hz.
2-export type Welcome = { id: number; name: string };
3-export type Remote = { id: number; name: string; x: number; y: number; h: number };
1+// One socket is one player. The server owns the world; we send intents and are
2+// handed back the state to draw.
3+import type { Body, Loose, Ship } from './sim';
44
5-export function connect(
6- onWelcome: (w: Welcome) => void,
7- onState: (players: Remote[]) => void,
8-): { send: (msg: unknown) => void } {
5+export type State = { you: number; held: number; bodies: Body[]; loose: Loose[]; players: Ship[] };
6+
7+export function connect(onState: (s: State) => void): { send: (msg: unknown) => void } {
98 let ws: WebSocket | null = null;
109 const open = () => {
1110 ws = new WebSocket(`ws://${location.hostname}:8090/ws`);
1211 ws.onmessage = (e) => {
1312 const m = JSON.parse(e.data);
14- if (m.t === 'welcome') onWelcome(m);
15- if (m.t === 'state') onState(m.players);
13+ if (m.t === 'state') onState(m);
1614 };
1715 ws.onclose = () => setTimeout(open, 500);
1816 };
client/src/sim.ts+5-104
@@ -1,18 +1,11 @@
1-// A ship is a connected graph of pieces that flies as one rigid body.
2-// Client simulates its own; the server relays.
3-const MAX_SPEED = 90; // world units / second
4-const ACCEL = 260;
5-const ARRIVE = 2.2; // slowdown radius factor
6-
7-const SLOTS = 6; // attachment directions around a hull piece
8-export const SPACING = 17; // world distance between attached piece centers
9-export const GRAB = 13; // world radius to pick a piece up
10-
1+// The server owns ships, hulls and loose pieces; this is the shape it reports,
2+// plus the local-to-world transform every client needs to draw a hull.
113 export type Kind = 'gun' | 'armor' | 'cargo' | 'engine';
124
135 // Piece position is local to the ship: the graph is rigid, so only the hull moves.
146 export type Piece = { id: number; kind: Kind; lx: number; ly: number; parent: number };
157 export type Loose = { id: number; kind: Kind; x: number; y: number; h: number };
8+export type Body = { id: number; kind: 'star' | 'shipyard' | 'barren'; r: number; x: number; y: number };
169
1710 export type Ship = {
1811 id: number;
@@ -20,105 +13,13 @@ export type Ship = {
2013 x: number;
2114 y: number;
2215 h: number;
23- vx: number;
24- vy: number;
25- tx: number;
16+ tx: number; // where it is flying to, so the marker can show the order
2617 ty: number;
27- pieces: Piece[]; // pieces[0] is the root
18+ pieces: Piece[];
2819 };
2920
30-let pid = 0;
31-export const nextPieceId = () => ++pid;
32-
33-export function makeShip(id: number, name: string, x: number, y: number): Ship {
34- const pieces = [{ id: nextPieceId(), kind: 'gun' as const, lx: 0, ly: 0, parent: 0 }];
35- return { id, name, x, y, h: 0, vx: 0, vy: 0, tx: x, ty: y, pieces };
36-}
37-
3821 export function toWorld(s: Ship, p: Piece): { x: number; y: number } {
3922 const c = Math.cos(s.h);
4023 const n = Math.sin(s.h);
4124 return { x: s.x + p.lx * c - p.ly * n, y: s.y + p.lx * n + p.ly * c };
4225 }
43-
44-export function toLocal(s: Ship, x: number, y: number): { x: number; y: number } {
45- const c = Math.cos(s.h);
46- const n = Math.sin(s.h);
47- const dx = x - s.x;
48- const dy = y - s.y;
49- return { x: dx * c + dy * n, y: -dx * n + dy * c };
50-}
51-
52-const TAU = Math.PI * 2;
53-const wrap = (a: number) => Math.atan2(Math.sin(a), Math.cos(a));
54-
55-// Snap a dropped piece onto the free slot closest to where it was let go.
56-export function attach(s: Ship, l: Loose): boolean {
57- const at = toLocal(s, l.x, l.y);
58- const near = [...s.pieces].sort(
59- (a, b) => Math.hypot(a.lx - at.x, a.ly - at.y) - Math.hypot(b.lx - at.x, b.ly - at.y),
60- );
61- if (Math.hypot(near[0].lx - at.x, near[0].ly - at.y) > SPACING * 1.5) return false; // not dropped on the hull
62- for (const p of near) {
63- let slot = -1;
64- let best = TAU;
65- for (let i = 0; i < SLOTS; i++) {
66- const a = (i / SLOTS) * TAU;
67- const x = p.lx + Math.cos(a) * SPACING;
68- const y = p.ly + Math.sin(a) * SPACING;
69- if (s.pieces.some((q) => Math.hypot(q.lx - x, q.ly - y) < SPACING * 0.5)) continue; // slot taken
70- const d = Math.abs(wrap(a - Math.atan2(at.y - p.ly, at.x - p.lx)));
71- if (d < best) {
72- best = d;
73- slot = i;
74- }
75- }
76- if (slot < 0) continue; // piece is surrounded, try the next one out
77- const a = (slot / SLOTS) * TAU;
78- s.pieces.push({ id: l.id, kind: l.kind, lx: p.lx + Math.cos(a) * SPACING, ly: p.ly + Math.sin(a) * SPACING, parent: p.id });
79- return true;
80- }
81- return false;
82-}
83-
84-// Remove a piece and everything hanging off it. The root never detaches; what
85-// comes off is dropped in space at the spot it already occupied.
86-export function detach(s: Ship, id: number): Loose[] | null {
87- if (s.pieces.length < 2 || s.pieces[0].id === id) return null;
88- const gone = new Set([id]);
89- for (let grew = true; grew; ) {
90- grew = false;
91- for (const p of s.pieces) {
92- if (!gone.has(p.id) && gone.has(p.parent)) {
93- gone.add(p.id);
94- grew = true;
95- }
96- }
97- }
98- const out = s.pieces.filter((p) => gone.has(p.id)).map((p) => ({ id: p.id, kind: p.kind, h: s.h, ...toWorld(s, p) }));
99- s.pieces = s.pieces.filter((p) => !gone.has(p.id));
100- return out;
101-}
102-
103-export function step(s: Ship, dt: number): void {
104- const dx = s.tx - s.x;
105- const dy = s.ty - s.y;
106- const dist = Math.hypot(dx, dy);
107- const speed = dist < 0.5 ? 0 : Math.min(MAX_SPEED, dist * ARRIVE);
108- const wantX = dist < 0.5 ? 0 : (dx / dist) * speed;
109- const wantY = dist < 0.5 ? 0 : (dy / dist) * speed;
110- const dvx = wantX - s.vx;
111- const dvy = wantY - s.vy;
112- const dl = Math.hypot(dvx, dvy);
113- const maxDv = ACCEL * dt;
114- if (dl > maxDv) {
115- s.vx += (dvx / dl) * maxDv;
116- s.vy += (dvy / dl) * maxDv;
117- } else {
118- s.vx = wantX;
119- s.vy = wantY;
120- }
121- s.x += s.vx * dt;
122- s.y += s.vy * dt;
123- if (Math.hypot(s.vx, s.vy) > 4) s.h = Math.atan2(s.vy, s.vx);
124-}
client/src/view.ts+45-35
@@ -2,8 +2,7 @@
22 // then a single fullscreen pass quantizes it into glyphs of the amber ramp.
33 // Two channels carry the shading: R = luminance (which glyph), G = palette index.
44 import * as THREE from 'three';
5-import { toWorld, type Kind, type Loose, type Ship } from './sim';
6-import type { Planet, System } from './world';
5+import { toWorld, type Body, type Kind, type Loose, type Ship } from './sim';
76
87 export const CELL = 12; // css px per character cell
98 export const CELL_WORLD = 2; // world units per character cell at zoom 1
@@ -103,16 +102,20 @@ function plate(w: number, h: number, v: number): THREE.Mesh {
103102 }
104103
105104 // A piece is a bright silhouette with a dimmer inset plate, so the cel shading
106-// survives the downsample to cell resolution. Owned pieces read brighter than
107-// loose wreckage, and a piece flips shade the moment it is bolted on or torn off.
105+// survives the downsample to cell resolution. Three roles must never read as
106+// each other: your hull is the brightest cream, another player's hull is gold,
107+// and loose wreckage is dim sepia. A piece flips shade the moment it is bolted
108+// on or torn off.
108109 const SHADE = {
109110 own: [lum(1, 7), lum(0.5, 7)],
110- loose: [lum(0.7, 5), lum(0.35, 5)],
111+ other: [lum(0.8, 6), lum(0.4, 6)],
112+ loose: [lum(0.55, 5), lum(0.28, 5)],
111113 };
112-const shade = (g: THREE.Group, own: boolean) => {
113- if (g.userData.own === own) return;
114- g.userData.own = own;
115- const c = own ? SHADE.own : SHADE.loose;
114+export type Role = keyof typeof SHADE;
115+const shade = (g: THREE.Group, role: Role) => {
116+ if (g.userData.role === role) return;
117+ g.userData.role = role;
118+ const c = SHADE[role];
116119 g.children.forEach((m, i) => (m as THREE.Mesh<THREE.BufferGeometry, THREE.MeshBasicMaterial>).material.color.copy(c[i]));
117120 };
118121
@@ -120,7 +123,7 @@ function piece(kind: Kind): THREE.Group {
120123 const g = new THREE.Group();
121124 g.add(new THREE.Mesh(pieceGeometry(kind, 1), new THREE.MeshBasicMaterial({ color: SHADE.loose[0] })));
122125 g.add(new THREE.Mesh(pieceGeometry(kind, 0.7), new THREE.MeshBasicMaterial({ color: SHADE.loose[1] })));
123- shade(g, false);
126+ shade(g, 'loose');
124127 return g;
125128 }
126129
@@ -174,7 +177,7 @@ function starMesh(r: number): THREE.Group {
174177 }
175178
176179 // A barren planet: a rust disk lit from one side, with craters punched out of it.
177-// Nothing on it is usable.
180+// These are the ore bodies of the galaxy.
178181 function barrenMesh(r: number): THREE.Group {
179182 const g = new THREE.Group();
180183 g.add(disk(r, 0.7, 9));
@@ -216,9 +219,8 @@ export class View {
216219 private pass: THREE.ShaderMaterial;
217220 private quad = new THREE.Scene();
218221 private pieceMeshes = new Map<number, THREE.Group>();
222+ private bodyMeshes = new Map<number, THREE.Group>();
219223 private marker = crosshair();
220- private star: THREE.Group | null = null;
221- private planets: { planet: Planet; mesh: THREE.Group }[] = [];
222224 private cols = 0;
223225 private rows = 0;
224226
@@ -252,16 +254,26 @@ export class View {
252254 this.resize();
253255 }
254256
255- // Built once: bodies keep an identity for the whole run, only their orbit moves.
256- system(sys: System): void {
257- this.star = starMesh(sys.star);
258- this.star.position.z = -1;
259- this.scene.add(this.star);
260- for (const planet of sys.planets) {
261- const mesh = planet.kind === 'shipyard' ? shipyardMesh(planet.r) : barrenMesh(planet.r);
262- mesh.position.z = -1;
263- this.scene.add(mesh);
264- this.planets.push({ planet, mesh });
257+ // Built once: a body keeps an identity for the whole run, only its place moves.
258+ private bodies(bs: Body[], t: number): void {
259+ const seen = new Set<number>();
260+ for (const b of bs) {
261+ seen.add(b.id);
262+ let m = this.bodyMeshes.get(b.id);
263+ if (!m) {
264+ m = b.kind === 'star' ? starMesh(b.r) : b.kind === 'shipyard' ? shipyardMesh(b.r) : barrenMesh(b.r);
265+ m.position.z = -1;
266+ m.userData.spin = b.kind === 'star' ? 0.08 : 0.15; // slow enough to read as alive
267+ this.scene.add(m);
268+ this.bodyMeshes.set(b.id, m);
269+ }
270+ m.position.set(b.x, b.y, -1);
271+ m.rotation.z = t * m.userData.spin;
272+ }
273+ for (const [id, m] of this.bodyMeshes) {
274+ if (seen.has(id)) continue;
275+ this.scene.remove(m);
276+ this.bodyMeshes.delete(id);
265277 }
266278 }
267279
@@ -282,8 +294,9 @@ export class View {
282294 this.pass.uniforms.uCellPx.value = CELL * dpr;
283295 }
284296
285- // One mesh per piece id, whether it is bolted to a hull or drifting loose.
286- private place(id: number, kind: Kind, own: boolean, x: number, y: number, h: number, seen: Set<number>): void {
297+ // One mesh per piece, whether it is bolted to a hull or drifting loose: ids are
298+ // unique across the world, so a torn-off piece stays the same mesh.
299+ private place(id: number, kind: Kind, role: Role, x: number, y: number, h: number, seen: Set<number>): void {
287300 seen.add(id);
288301 let g = this.pieceMeshes.get(id);
289302 if (!g) {
@@ -291,13 +304,14 @@ export class View {
291304 this.pieceMeshes.set(id, g);
292305 this.scene.add(g);
293306 }
294- shade(g, own);
307+ shade(g, role);
295308 g.position.set(x, y, 0);
296309 g.rotation.z = h;
297310 }
298311
299312 draw(
300313 cam: Camera,
314+ bodies: Body[],
301315 ships: Ship[],
302316 ownId: number,
303317 loose: Loose[],
@@ -313,22 +327,18 @@ export class View {
313327 this.camera.top = hh;
314328 this.camera.bottom = -hh;
315329 this.camera.updateProjectionMatrix();
316- // Bodies sit behind the ships, drifting and turning slowly enough to read as alive.
317- const t = performance.now() / 1000;
318- if (this.star) this.star.rotation.z = t * 0.08;
319- for (const { planet, mesh } of this.planets) {
320- mesh.position.set(planet.x, planet.y, -1);
321- mesh.rotation.z = t * 0.15;
322- }
330+ // Bodies sit behind the ships: the server says where, we only draw them.
331+ this.bodies(bodies, performance.now() / 1000);
323332
324333 const seen = new Set<number>();
325334 for (const s of ships) {
335+ const role: Role = s.id === ownId ? 'own' : 'other';
326336 for (const p of s.pieces) {
327337 const w = toWorld(s, p);
328- this.place(p.id, p.kind, s.id === ownId, w.x, w.y, s.h, seen);
338+ this.place(p.id, p.kind, role, w.x, w.y, s.h, seen);
329339 }
330340 }
331- for (const l of loose) this.place(l.id, l.kind, false, l.x, l.y, l.h, seen);
341+ for (const l of loose) this.place(l.id, l.kind, 'loose', l.x, l.y, l.h, seen);
332342 for (const [id, g] of this.pieceMeshes) {
333343 if (seen.has(id)) continue;
334344 this.scene.remove(g);
client/src/world.ts+0-41
@@ -1,41 +0,0 @@
1-// The one star system we render while tuning POIs: a star with two planets that
2-// actually revolve around it. Client-side only until galaxy generation lands.
3-export type PlanetKind = 'shipyard' | 'barren';
4-
5-export type Planet = {
6- kind: PlanetKind;
7- r: number; // world radius
8- orbit: number; // distance from the star
9- angle: number; // current orbital angle
10- speed: number; // radians / second
11- x: number;
12- y: number;
13-};
14-
15-export type System = { star: number; planets: Planet[] };
16-
17-const STAR_R = 30;
18-
19-export function makeSystem(): System {
20- const sys: System = {
21- star: STAR_R,
22- planets: [
23- { kind: 'shipyard', r: 20, orbit: 120, angle: -1.57, speed: 0.06, x: 0, y: 0 },
24- { kind: 'barren', r: 28, orbit: 215, angle: 0.6, speed: 0.035, x: 0, y: 0 },
25- ],
26- };
27- place(sys);
28- return sys;
29-}
30-
31-function place(sys: System): void {
32- for (const p of sys.planets) {
33- p.x = Math.cos(p.angle) * p.orbit;
34- p.y = Math.sin(p.angle) * p.orbit;
35- }
36-}
37-
38-export function stepSystem(sys: System, dt: number): void {
39- for (const p of sys.planets) p.angle += p.speed * dt;
40- place(sys);
41-}
server/main.go+390-26
@@ -6,6 +6,7 @@ import (
66 "log"
77 "math"
88 "net/http"
9+ "sort"
910 "strconv"
1011 "sync"
1112 "time"
@@ -13,15 +14,77 @@ import (
1314 "github.com/gorilla/websocket"
1415 )
1516
16-// A browser tab is one player. The client simulates its own ship and reports
17-// position; the server stores it and broadcasts everyone to everyone.
17+// The server owns everything a client draws: celestial bodies, ships, hulls and
18+// loose pieces. Clients send intents (pick, drag, drop) and render the state
19+// they are handed.
1820
19-type player struct {
21+const (
22+ tickRate = 20
23+ tickDt = 1.0 / tickRate
24+
25+ starR = 30.0
26+ standoff = 26.0 // ring radius beyond a planet's surface
27+ starGap = 34.0 // a star kills on contact, so its ring sits further out
28+ hitR = 1.5 // click radius of a body, as a multiple of its radius
29+ grabR = 13.0 // world radius to pick a piece up
30+ spacing = 17.0 // world distance between attached piece centers
31+ slots = 6 // attachment directions around a hull piece
32+ maxSpeed = 90.0
33+ accel = 260.0
34+ arrive = 2.2 // slowdown radius factor
35+ spawnX = 0.0
36+ spawnY = -70.0
37+ reach = 4000.0 // an order further out than this is ignored
38+)
39+
40+// A hull is a graph of pieces placed relative to the ship. Piece ids are unique
41+// across the whole world, so a piece can be torn off one hull and bolted to
42+// another without ever changing identity.
43+type piece struct {
44+ ID int `json:"id"`
45+ Kind string `json:"kind"`
46+ LX float64 `json:"lx"`
47+ LY float64 `json:"ly"`
48+ Parent int `json:"parent"`
49+}
50+
51+type loose struct {
2052 ID int `json:"id"`
21- Name string `json:"name"`
53+ Kind string `json:"kind"`
2254 X float64 `json:"x"`
2355 Y float64 `json:"y"`
2456 H float64 `json:"h"`
57+ held int // player dragging it, 0 = free
58+}
59+
60+// A body is a star or a planet. Orbit 0 and speed 0 is the star, which never
61+// moves; planets revolve and their current place is recomputed every tick.
62+type body struct {
63+ ID int `json:"id"`
64+ Kind string `json:"kind"`
65+ R float64 `json:"r"`
66+ X float64 `json:"x"`
67+ Y float64 `json:"y"`
68+ orbit float64
69+ a0 float64
70+ speed float64
71+}
72+
73+type player struct {
74+ ID int `json:"id"`
75+ Name string `json:"name"`
76+ X float64 `json:"x"`
77+ Y float64 `json:"y"`
78+ H float64 `json:"h"`
79+ TX float64 `json:"tx"`
80+ TY float64 `json:"ty"`
81+ Pieces []piece `json:"pieces"`
82+
83+ vx, vy float64
84+ orbit int // body the ship is anchored to, 0 = none
85+ ox, oy float64 // ring point, in world space, at the moment of anchoring
86+ anchored float64 // world time of anchoring
87+ held int // loose piece being dragged, 0 = none
2588 }
2689
2790 type client struct {
@@ -30,9 +93,22 @@ type client struct {
3093 }
3194
3295 type hub struct {
33- mu sync.Mutex
34- clients map[*client]bool
35- nextID int
96+ mu sync.Mutex
97+ clients map[*client]bool
98+ nextID int
99+ bodies []*body
100+ loose []*loose
101+ nextPiece int
102+ time float64
103+}
104+
105+type state struct {
106+ T string `json:"t"`
107+ You int `json:"you"`
108+ Held int `json:"held"`
109+ Bodies []*body `json:"bodies"`
110+ Loose []*loose `json:"loose"`
111+ Players []*player `json:"players"`
36112 }
37113
38114 var upgrader = websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }}
@@ -41,12 +117,38 @@ var addr = flag.String("addr", ":8090", "listen address")
41117
42118 func main() {
43119 flag.Parse()
44- h := &hub{clients: map[*client]bool{}}
120+ h := newHub()
45121 go h.tick()
46122 http.HandleFunc("/ws", h.handle)
47123 log.Fatal(http.ListenAndServe(*addr, nil))
48124 }
49125
126+func newHub() *hub {
127+ h := &hub{clients: map[*client]bool{}}
128+ // One hand-tuned system: a star, a shipyard planet and a barren planet, both
129+ // revolving. The real galaxy generator replaces this later.
130+ h.bodies = []*body{
131+ {ID: 1, Kind: "star", R: starR},
132+ {ID: 2, Kind: "shipyard", R: 20, orbit: 120, a0: -1.57, speed: 0.06},
133+ {ID: 3, Kind: "barren", R: 28, orbit: 215, a0: 0.6, speed: 0.035},
134+ }
135+ // Wreckage around the spawn, to build a first hull out of.
136+ for i, k := range []string{"armor", "cargo", "engine", "gun"} {
137+ h.loose = append(h.loose, &loose{
138+ ID: h.pieceID(),
139+ Kind: k,
140+ X: spawnX + []float64{30, 37, -29, -35}[i],
141+ Y: spawnY + []float64{-20, 18, 26, -22}[i],
142+ })
143+ }
144+ return h
145+}
146+
147+func (h *hub) pieceID() int {
148+ h.nextPiece++
149+ return h.nextPiece
150+}
151+
50152 func (h *hub) handle(w http.ResponseWriter, r *http.Request) {
51153 ws, err := upgrader.Upgrade(w, r, nil)
52154 if err != nil {
@@ -54,12 +156,12 @@ func (h *hub) handle(w http.ResponseWriter, r *http.Request) {
54156 }
55157 h.mu.Lock()
56158 h.nextID++
57- c := &client{ws: ws, p: &player{ID: h.nextID, Name: "P" + strconv.Itoa(h.nextID)}}
159+ c := &client{ws: ws, p: &player{ID: h.nextID, X: spawnX, Y: spawnY, TX: spawnX, TY: spawnY}}
160+ c.p.Name = "P" + strconv.Itoa(c.p.ID)
161+ c.p.Pieces = []piece{{ID: h.pieceID(), Kind: "gun"}} // every run starts from one gun
58162 h.clients[c] = true
59163 h.mu.Unlock()
60164
61- h.send(c, map[string]any{"t": "welcome", "id": c.p.ID, "name": c.p.Name})
62-
63165 for {
64166 _, msg, err := ws.ReadMessage()
65167 if err != nil {
@@ -69,49 +171,311 @@ func (h *hub) handle(w http.ResponseWriter, r *http.Request) {
69171 T string `json:"t"`
70172 X *float64 `json:"x"`
71173 Y *float64 `json:"y"`
72- H *float64 `json:"h"`
73174 }
74- if json.Unmarshal(msg, &in) != nil || in.T != "pos" || in.X == nil || in.Y == nil || in.H == nil {
175+ if json.Unmarshal(msg, &in) != nil {
176+ continue
177+ }
178+ if in.X == nil || in.Y == nil || !finite(*in.X) || !finite(*in.Y) {
75179 continue
76180 }
77- if !finite(*in.X) || !finite(*in.Y) || !finite(*in.H) {
181+ if math.Abs(*in.X) > reach || math.Abs(*in.Y) > reach {
78182 continue
79183 }
80184 h.mu.Lock()
81- c.p.X, c.p.Y, c.p.H = *in.X, *in.Y, *in.H
185+ switch in.T {
186+ case "pick":
187+ h.pick(c.p, *in.X, *in.Y)
188+ case "drag":
189+ h.drag(c.p, *in.X, *in.Y)
190+ case "drop":
191+ h.drop(c.p, *in.X, *in.Y)
192+ }
82193 h.mu.Unlock()
83194 }
84195
85196 h.mu.Lock()
86197 delete(h.clients, c)
198+ if l := h.looseByID(c.p.held); l != nil {
199+ l.held = 0
200+ }
87201 h.mu.Unlock()
88202 ws.Close()
89203 }
90204
205+// ---- intents ----
206+
207+// A click is resolved by the server: grab a piece, tear one off, park on a body,
208+// or fly to a point. The client never decides which happened.
209+func (h *hub) pick(p *player, x, y float64) {
210+ if l := h.freeLooseAt(x, y); l != nil {
211+ p.held, l.held = l.ID, p.ID
212+ return
213+ }
214+ if id := hullPieceAt(p, x, y); id != 0 {
215+ if off := h.detach(p, id); len(off) > 0 {
216+ h.loose = append(h.loose, off...)
217+ if l := h.looseByID(id); l != nil {
218+ p.held, l.held = id, p.ID
219+ }
220+ return
221+ }
222+ }
223+ if b := h.bodyAt(x, y); b != nil {
224+ h.anchor(p, b)
225+ return
226+ }
227+ p.orbit = 0
228+ p.TX, p.TY = x, y
229+}
230+
231+func (h *hub) drag(p *player, x, y float64) {
232+ l := h.looseByID(p.held)
233+ if l == nil || l.held != p.ID {
234+ return
235+ }
236+ l.X, l.Y = x, y
237+}
238+
239+func (h *hub) drop(p *player, x, y float64) {
240+ l := h.looseByID(p.held)
241+ if l == nil {
242+ return
243+ }
244+ p.held, l.held = 0, 0
245+ l.X, l.Y = x, y
246+ h.attach(p, l)
247+}
248+
249+// ---- world ----
250+
251+// Parking on a body bolts the target to that body's frame: the ring point turns
252+// with the planet around its star, so the ship is carried along.
253+func (h *hub) anchor(p *player, b *body) {
254+ gap := standoff
255+ if b.Kind == "star" {
256+ gap = starGap
257+ }
258+ a := math.Atan2(p.Y-b.Y, p.X-b.X) // enter the ring on the side we already are on
259+ r := b.R + gap
260+ p.orbit, p.anchored = b.ID, h.time
261+ p.ox, p.oy = b.X+math.Cos(a)*r, b.Y+math.Sin(a)*r
262+}
263+
264+// Torn-off pieces keep the ids they had, so a piece never becomes a new thing by
265+// being ripped off a hull.
266+func (h *hub) detach(p *player, id int) []*loose {
267+ if len(p.Pieces) < 2 || p.Pieces[0].ID == id {
268+ return nil
269+ }
270+ gone := map[int]bool{id: true}
271+ for grew := true; grew; {
272+ grew = false
273+ for _, q := range p.Pieces {
274+ if !gone[q.ID] && gone[q.Parent] {

Cut short: this commit's diff is over 1000 lines.