space-browser / commits / c825130
fix: I think I did worst than the Ai, sorry
This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.
@@ -31,10 +31,6 @@ export class Camera {
3131 this.th = Math.min(this.maxHeight, Math.max(this.minHeight, this.th * factor));
3232 }
3333
34- get targetHeight() {
35- return this.th;
36- }
37-
3834 update(dt: number) {
3935 const k = 1 - Math.exp(-9 * dt);
4036 this.cx += (this.tx - this.cx) * k;
@@ -1,7 +1,7 @@
11 import * as THREE from "three";
22 import type { GameConfig } from "./config";
33 import { buildGlyphAtlas, CELL_H, CELL_W, PAL, RAMP } from "./palette";
4-import type { ItemView, NPCView, PlayerView, POI, ProjView, Shape } from "./protocol";
4+import type { ItemView, NPCView, PlayerView, POI, ProjView, Shape, Vec2 } from "./protocol";
55
66 const PIECE_R = 20;
77 const SHAPES: Shape[] = ["triangle", "square", "circle", "pentagon", "star"];
@@ -24,10 +24,6 @@ const KIND_SHAPE: Record<string, number> = {
2424 wreck: 0,
2525 };
2626
27-const PLAYER_COLOR = new THREE.Color("#fff3d0");
28-const FRIEND_COLOR = new THREE.Color("#a9743a");
29-const HOSTILE_COLOR = new THREE.Color("#ff7a3c");
30-
3127 const POINT_VERT = /* glsl */ `
3228 attribute float aSize;
3329 attribute vec3 aColor;
@@ -38,7 +34,6 @@ uniform float uTime;
3834 varying vec3 vColor;
3935 varying float vShape;
4036 varying float vTw;
41-varying float vShapeKind;
4237 void main() {
4338 vColor = aColor;
4439 vShape = aShape;
@@ -46,16 +41,13 @@ void main() {
4641 vec4 mv = modelViewMatrix * vec4(position, 1.0);
4742 gl_Position = projectionMatrix * mv;
4843 gl_PointSize = clamp(aSize * 2.0 * uZoom, 1.0, 900.0);
49- vShapeKind = aShape;
5044 }
5145 `;
5246
5347 const POINT_FRAG = /* glsl */ `
54-uniform float uTime;
5548 varying vec3 vColor;
5649 varying float vShape;
5750 varying float vTw;
58-varying float vShapeKind;
5951 void main() {
6052 vec2 d = gl_PointCoord * 2.0 - 1.0;
6153 float r = length(d);
@@ -78,7 +70,6 @@ uniform sampler2D tGlyph;
7870 uniform vec2 uCells;
7971 uniform float uGlyphs;
8072 uniform vec3 uInk;
81-uniform float uTime;
8273 varying vec2 vUv;
8374 float hash(vec2 p) {
8475 return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453);
@@ -103,6 +94,14 @@ void main() {
10394
10495 type GalaxyShape = GameConfig["galaxy"]["shape"];
10596
97+// Radius that lights the dust up around explored POIs, and how dim the fog is.
98+const FOG_REVEAL = 20000;
99+const FOG_DIM = 0.55;
100+
101+// Pieces trail the direction of travel by a few units, subtle jiggle.
102+const JIGGLE = 5;
103+const JIGGLE_PER_SPEED = 10;
104+
106105 // mulberry32: same seed, same dust, every reload.
107106 function seeded(seed: string): () => number {
108107 let a = 2166136261;
@@ -122,7 +121,6 @@ function wrapPi(a: number): number {
122121 return a - Math.PI;
123122 }
124123
125-// armTerm is 1 on an arm centreline and falls off between the arms.
126124 function armTerm(x: number, y: number, r: number, sh: GalaxyShape, radius: number): number {
127125 const r0 = sh.bulgeScale * radius;
128126 const angle = Math.atan2(y, x);
@@ -135,8 +133,6 @@ function armTerm(x: number, y: number, r: number, sh: GalaxyShape, radius: numbe
135133 return best;
136134 }
137135
138-// galaxyShape is the same surface density the server bakes its stars from: a
139-// bulge, a disc, and log-spiral arms.
140136 function galaxyShape(x: number, y: number, sh: GalaxyShape, radius: number): number {
141137 const r = Math.hypot(x, y);
142138 if (r > radius) return 0;
@@ -217,13 +213,15 @@ export class Engine {
217213 private poiPoints: THREE.Points;
218214 private poiGeom = new THREE.BufferGeometry();
219215 private dust: THREE.Points;
216+ private dustShape = new Float32Array(0);
217+ private lastPOIs: POI[] = [];
220218 private projPoints: THREE.Points;
221219 private projGeom = new THREE.BufferGeometry();
222220 private projPos: Float32Array;
223221 private projCol: Float32Array;
224- private projCount = 0;
225222 private shipMeshes: Record<Shape, THREE.InstancedMesh>;
226223 private pieceGeoms: Record<Shape, THREE.BufferGeometry>;
224+ private jitters = new Map<string, { px: number; py: number; vx: number; vy: number }>();
227225 private previewGhost: THREE.Mesh;
228226 private anchorGhost: THREE.Mesh;
229227 private previewMat: THREE.MeshBasicMaterial;
@@ -264,7 +262,6 @@ export class Engine {
264262 uCells: { value: this.cells },
265263 uGlyphs: { value: RAMP.length },
266264 uInk: { value: new THREE.Color(PAL[0]) },
267- uTime: { value: 0 },
268265 };
269266 const post = new THREE.Mesh(
270267 new THREE.PlaneGeometry(2, 2),
@@ -314,17 +311,24 @@ export class Engine {
314311
315312 this.shipMeshes = {} as Record<Shape, THREE.InstancedMesh>;
316313 this.pieceGeoms = {} as Record<Shape, THREE.BufferGeometry>;
314+ // ship pieces invert the colour they are drawn over, so a hull is never
315+ // lost against whatever it happens to be flying across.
316+ const pieceMat = new THREE.MeshBasicMaterial({
317+ color: 0xffffff,
318+ blending: THREE.CustomBlending,
319+ blendSrc: THREE.OneMinusDstColorFactor,
320+ blendDst: THREE.ZeroFactor,
321+ transparent: true,
322+ depthTest: false,
323+ depthWrite: false,
324+ });
317325 for (const s of SHAPES) {
318326 const geo = pieceGeometry(s);
319327 this.pieceGeoms[s] = geo;
320- const mesh = new THREE.InstancedMesh(
321- geo,
322- new THREE.MeshBasicMaterial({ color: 0xffffff }),
323- 4096,
324- );
328+ const mesh = new THREE.InstancedMesh(geo, pieceMat, 4096);
325329 mesh.frustumCulled = false;
326330 mesh.count = 0;
327- mesh.instanceColor = new THREE.InstancedBufferAttribute(new Float32Array(4096 * 3), 3);
331+ mesh.renderOrder = 30;
328332 this.shipMeshes[s] = mesh;
329333 this.scene.add(mesh);
330334 }
@@ -346,21 +350,22 @@ export class Engine {
346350 for (const g of [this.previewGhost, this.anchorGhost]) {
347351 g.frustumCulled = false;
348352 g.visible = false;
349- g.renderOrder = 10;
353+ g.renderOrder = 40;
350354 this.scene.add(g);
351355 }
352356
353357 this.resize();
354358 }
355359
356- // dust fills the disc evenly; its brightness carries the galaxy shape, so
357- // the spiral and the bulge read as denser glyphs under the fog.
360+ // dust carries the galaxy shape but stays dim under the fog; explored
361+ // areas light up as POIs are revealed.
358362 private buildDust(seed: string): THREE.BufferGeometry {
359363 const sh = this.cfg.galaxy.shape;
360364 const radius = this.cfg.galaxy.radius;
361365 const rnd = seeded(seed);
362366 const n = 14000;
363367 const peak = 1 + sh.armStrength + sh.bulgeWeight;
368+ this.dustShape = new Float32Array(n);
364369 const pos = new Float32Array(n * 3);
365370 const size = new Float32Array(n);
366371 const col = new Float32Array(n * 3);
@@ -376,10 +381,10 @@ export class Engine {
376381 pos[k * 3 + 1] = y;
377382 pos[k * 3 + 2] = -2;
378383 size[k] = 3 + rnd() * 6;
379- const b = 1.3 + 3.4 * Math.pow(galaxyShape(x, y, sh, radius) / peak, 0.35);
380- col[k * 3] = c.r * b;
381- col[k * 3 + 1] = c.g * b;
382- col[k * 3 + 2] = c.b * b;
384+ this.dustShape[k] = Math.pow(galaxyShape(x, y, sh, radius) / peak, 0.35);
385+ col[k * 3] = c.r;
386+ col[k * 3 + 1] = c.g;
387+ col[k * 3 + 2] = c.b;
383388 shape[k] = 0;
384389 phase[k] = rnd() * 6.28;
385390 }
@@ -395,6 +400,7 @@ export class Engine {
395400 setDustSeed(seed: string) {
396401 this.dust.geometry.dispose();
397402 this.dust.geometry = this.buildDust(seed);
403+ this.applyFog();
398404 }
399405
400406 setPOIs(pois: Iterable<POI>) {
@@ -423,42 +429,107 @@ export class Engine {
423429 this.poiGeom.setAttribute("aColor", new THREE.BufferAttribute(col, 3));
424430 this.poiGeom.setAttribute("aShape", new THREE.BufferAttribute(shape, 1));
425431 this.poiGeom.setAttribute("aPhase", new THREE.BufferAttribute(phase, 1));
432+ this.lastPOIs = list;
433+ this.applyFog();
434+ }
435+
436+ private applyFog() {
437+ const g = this.dust.geometry;
438+ const posA = g.getAttribute("position") as THREE.BufferAttribute;
439+ const colA = g.getAttribute("aColor") as THREE.BufferAttribute;
440+ if (!posA || !colA || this.dustShape.length === 0) return;
441+ const cell = FOG_REVEAL;
442+ const grid = new Map<number, POI[]>();
443+ for (const p of this.lastPOIs) {
444+ const k = (Math.floor(p.x / cell) + 100) * 1000 + (Math.floor(p.y / cell) + 100);
445+ let a = grid.get(k);
446+ if (!a) grid.set(k, (a = []));
447+ a.push(p);
448+ }
449+ const r2 = FOG_REVEAL * FOG_REVEAL;
450+ const c = new THREE.Color("#2a1d10");
451+ for (let i = 0; i < this.dustShape.length; i++) {
452+ const x = posA.getX(i);
453+ const y = posA.getY(i);
454+ const cx = Math.floor(x / cell);
455+ const cy = Math.floor(y / cell);
456+ let seen = false;
457+ for (let dx = -1; dx <= 1 && !seen; dx++) {
458+ for (let dy = -1; dy <= 1 && !seen; dy++) {
459+ const a = grid.get((cx + dx + 100) * 1000 + (cy + dy + 100));
460+ if (!a) continue;
461+ for (const p of a) {
462+ const ddx = p.x - x;
463+ const ddy = p.y - y;
464+ if (ddx * ddx + ddy * ddy <= r2) {
465+ seen = true;
466+ break;
467+ }
468+ }
469+ }
470+ }
471+ const b = seen ? 1.3 + 3.4 * this.dustShape[i] : FOG_DIM * (1 + 1.6 * this.dustShape[i]);
472+ colA.setXYZ(i, c.r * b, c.g * b, c.b * b);
473+ }
474+ colA.needsUpdate = true;
426475 }
427476
428- updateShips(players: PlayerView[], npcs: NPCView[], selfId: string) {
477+ // jiggle returns how far a hull trails its heading, so a moving ship
478+ // wobbles a few units behind itself.
479+ private jiggle(id: string, x: number, y: number): Vec2 {
480+ let j = this.jitters.get(id);
481+ if (!j) {
482+ j = { px: x, py: y, vx: 0, vy: 0 };
483+ this.jitters.set(id, j);
484+ }
485+ j.vx += (x - j.px - j.vx) * 0.25;
486+ j.vy += (y - j.py - j.vy) * 0.25;
487+ j.px = x;
488+ j.py = y;
489+ const sp = Math.hypot(j.vx, j.vy);
490+ if (sp < 0.05) return { x: 0, y: 0 };
491+ const wob = 0.7 + 0.3 * Math.sin(this.time * 6 + x * 0.02);
492+ const amp = Math.min(JIGGLE, sp * JIGGLE_PER_SPEED) * wob;
493+ return { x: (-j.vx / sp) * amp, y: (-j.vy / sp) * amp };
494+ }
495+
496+ updateShips(players: PlayerView[], npcs: NPCView[]) {
429497 const counts: Record<Shape, number> = { triangle: 0, square: 0, circle: 0, pentagon: 0, star: 0 };
430- const add = (pieces: PlayerView["ship"]["pieces"], x: number, y: number, a: number, color: THREE.Color) => {
498+ const seen = new Set<string>();
499+ const add = (id: string, pieces: PlayerView["ship"]["pieces"], x: number, y: number, a: number) => {
500+ seen.add(id);
501+ const jig = this.jiggle(id, x, y);
431502 for (const key in pieces) {
432503 const p = pieces[key];
433504 const mesh = this.shipMeshes[p.shape];
434505 const n = counts[p.shape];
435506 if (n >= 4096) continue;
436- const wx = x + Math.cos(a) * p.x - Math.sin(a) * p.y;
437- const wy = y + Math.sin(a) * p.x + Math.cos(a) * p.y;
507+ const wx = x + jig.x + Math.cos(a) * p.x - Math.sin(a) * p.y;
508+ const wy = y + jig.y + Math.sin(a) * p.x + Math.cos(a) * p.y;
438509 this.pos.set(wx, wy, 0);
439510 this.quat.setFromAxisAngle({ x: 0, y: 0, z: 1 }, a);
440511 this.scale.setScalar(1);
441512 this.matrix.compose(this.pos, this.quat, this.scale);
442513 mesh.setMatrixAt(n, this.matrix);
443- mesh.setColorAt(n, color);
444514 counts[p.shape] = n + 1;
445515 }
446516 };
447- for (const p of players) {
448- add(p.ship.pieces, p.x, p.y, p.a, selfId === p.id ? PLAYER_COLOR : FRIEND_COLOR);
449- }
450- for (const n of npcs) {
451- add(n.ship.pieces, n.x, n.y, n.a, n.hostile ? HOSTILE_COLOR : FRIEND_COLOR);
452- }
517+ for (const p of players) add(p.id, p.ship.pieces, p.x, p.y, p.a);
518+ for (const n of npcs) add(n.id, n.ship.pieces, n.x, n.y, n.a);
519+ for (const id of [...this.jitters.keys()]) if (!seen.has(id)) this.jitters.delete(id);
453520 for (const s of SHAPES) {
454521 const mesh = this.shipMeshes[s];
455522 mesh.count = counts[s];
456523 mesh.instanceMatrix.needsUpdate = true;
457- if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
458524 }
459525 }
460526
461- updateDynamic(projs: ProjView[], items: ItemView[], markers: { x: number; y: number }[]) {
527+ updateDynamic(
528+ projs: ProjView[],
529+ items: ItemView[],
530+ markers: { x: number; y: number }[],
531+ hover: Vec2 | null,
532+ ) {
462533 const c = new THREE.Color();
463534 let i = 0;
464535 const put = (x: number, y: number, size: number, shape: number, color: string) => {
@@ -477,9 +548,9 @@ export class Engine {
477548 };
478549 for (const p of projs) put(p.x, p.y, 8, 0, "#ffcf6b");
479550 for (const it of items)
480- put(it.x, it.y, 10, it.item.kind === "ore" ? 1 : 2, it.item.kind === "ore" ? "#8a5f2c" : "#ffcf6b");
551+ put(it.x, it.y, 22, it.item.kind === "ore" ? 1 : 2, it.item.kind === "ore" ? "#8a5f2c" : "#ffcf6b");
481552 for (const m of markers ?? []) put(m.x, m.y, 7, 2, "#ffcf6b");
482- this.projCount = i;
553+ if (hover) put(hover.x, hover.y, 9, 1, "#ffcf6b");
483554 this.projGeom.setDrawRange(0, i);
484555 (this.projGeom.getAttribute("position") as THREE.BufferAttribute).needsUpdate = true;
485556 (this.projGeom.getAttribute("aColor") as THREE.BufferAttribute).needsUpdate = true;
@@ -557,7 +628,6 @@ export class Engine {
557628 this.renderer.clear();
558629 this.renderer.render(this.scene, this.camera);
559630 this.renderer.setRenderTarget(null);
560- this.postUniforms.uTime.value = this.time;
561631 this.renderer.render(this.postScene, this.postCam);
562632 }
563633 }
@@ -1,4 +1,4 @@
1-import type { CargoItem, POIKind, RunStats, SelfView, Shape } from "./protocol";
1+import type { CargoItem, RunStats, SelfView, Shape } from "./protocol";
22
33 const SHAPE_GLYPH: Record<Shape, string> = {
44 triangle: "\u25B2",
@@ -29,7 +29,7 @@ export interface CtxItem {
2929 action?: () => void;
3030 }
3131
32-export type Location = { id: string; kind: POIKind; name: string } | null;
32+export type Location = { prefix: string; name: string } | null;
3333
3434 export class HUD {
3535 private root: HTMLElement;
@@ -115,6 +115,8 @@ export class HUD {
115115 this.fuelFill.style.width = "0%";
116116 this.fuelGhost.style.width = "0%";
117117 this.lastFuel = 0;
118+ this.setHint("", 0, 0);
119+ this.closeContext();
118120 }
119121
120122 // --- per-frame self state -------------------------------------------------
@@ -127,7 +129,7 @@ export class HUD {
127129 this.call.textContent = self.callsign + (self.combat ? " [combat]" : "");
128130 if (location) {
129131 this.loc.innerHTML = "";
130- this.loc.append(document.createTextNode("in orbit of "));
132+ this.loc.append(document.createTextNode(location.prefix + " "));
131133 const b = el("b", undefined, location.name);
132134 this.loc.append(b);
133135 } else {
@@ -151,8 +153,12 @@ export class HUD {
151153 const item = self.cargo[i];
152154 const slot = el("div", "slot" + (item ? " filled" : ""));
153155 if (item) {
154- slot.textContent = item.kind === "ore" ? "\u25C6" : SHAPE_GLYPH[(item.shape ?? "circle") as Shape];
155- if (item.kind === "piece") slot.append(el("span", "q", String(item.q ?? 1)));
156+ if (item.kind === "ore") {
157+ slot.textContent = "\u25C6";
158+ } else {
159+ slot.append(el("span", "g", SHAPE_GLYPH[(item.shape ?? "circle") as Shape]));
160+ slot.append(el("span", "q", stars(item.q)));
161+ }
156162 slot.addEventListener("contextmenu", (e) => {
157163 e.preventDefault();
158164 e.stopPropagation();
@@ -208,10 +214,6 @@ export class HUD {
208214 while (this.radioLog.childElementCount > 8) this.radioLog.firstElementChild?.remove();
209215 }
210216
211- focusRadio() {
212- this.radioInput.focus();
213- }
214-
215217 // --- toasts / hints -------------------------------------------------------
216218
217219 toast(msg: string) {
@@ -239,7 +241,7 @@ export class HUD {
239241 const m = el("div", "ctx");
240242 m.append(el("div", "head", head));
241243 for (const it of items) {
242- const row = el("div", "item", it.label + (it.disabled ? " -" : ""));
244+ const row = el("div", "item", it.label);
243245 if (!it.disabled && it.action) {
244246 row.addEventListener("click", () => {
245247 this.closeContext();
@@ -374,15 +376,14 @@ export class HUD {
374376 help() {
375377 const m = this.modal("help");
376378 const lines = [
377- "LMB move / attack / interact",
379+ "LMB move / attack / pick up",
378380 "SHIFT+LMB queue a move",
379381 "RMB context menu on anything",
380- "WHEEL zoom: ship scale to galaxy scale",
381- "DRAG pan the view C centre on ship",
382+ "WHEEL zoom from ship scale to galaxy scale",
382383 "ENTER radio input ? help",
383- "orbit a POI to name it; shipyards refuel and craft",
384+ "orbit a POI to name it; shipyards refuel, craft, repair",
384385 "right-click your pieces to detach, upgrade, repair",
385- "attach: right-click a loose piece, then click a glowing spot on your ship",
386+ "attach: right-click a loose piece, then click a spot on the hull",
386387 ];
387388 for (const l of lines) m.append(el("div", "kv", l));
388389 const row = el("div", "choices");
@@ -59,9 +59,8 @@ class Game {
5959
6060 private onboarding: { error: (m: string) => void } | null = null;
6161 private attachItem: string | null = null;
62- private follow = true;
6362 private spawned = false;
64- private drag: { x: number; y: number; moved: boolean; button: number } | null = null;
63+ private hoverMark: Vec2 | null = null;
6564 private lastPointer = { x: 0, y: 0 };
6665 private last = performance.now();
6766
@@ -101,7 +100,6 @@ class Game {
101100 this.dead = false;
102101 this.self = null;
103102 this.selfId = "";
104- this.follow = true;
105103 this.spawned = false;
106104 this.hud.clear();
107105 this.onboarding = this.hud.onboarding((callsign, shape) => {
@@ -224,13 +222,34 @@ class Game {
224222 private location(): Location {
225223 if (!this.self) return null;
226224 const poi = this.pois.get(this.self.orbit);
227- if (!poi) return null;
228- return { id: poi.id, kind: poi.kind, name: poi.name || `unnamed ${KIND_LABEL[poi.kind]}` };
225+ if (poi) return { prefix: "in orbit of", name: this.label(poi) };
226+ const star = this.nearestStar();
227+ if (star) return { prefix: "system", name: this.label(star) };
228+ return null;
229+ }
230+
231+ private nearestStar(): POI | null {
232+ if (!this.self) return null;
233+ let best: POI | null = null;
234+ let bestD = this.cfg.galaxy.starSpacing.min;
235+ for (const p of this.pois.values()) {
236+ if (p.kind !== "star") continue;
237+ const d = Math.hypot(p.x - this.self.x, p.y - this.self.y);
238+ if (d < bestD) {
239+ bestD = d;
240+ best = p;
241+ }
242+ }
243+ return best;
244+ }
245+
246+ private label(poi: POI): string {
247+ return poi.name || `unnamed ${KIND_LABEL[poi.kind]}`;
229248 }
230249
231250 private nameOf(id: string): string {
232251 const poi = this.pois.get(id);
233- if (poi && poi.kind !== "fleet") return poi.name || `unnamed ${KIND_LABEL[poi.kind]}`;
252+ if (poi && poi.kind !== "fleet") return this.label(poi);
234253 const p = this.players.get(id);
235254 if (p) return p.cs;
236255 const n = this.npcs.get(id);
@@ -255,11 +274,12 @@ class Game {
255274 e.a += da * k;
256275 }
257276
258- if (this.self && this.follow) this.camera.setTarget(this.self.x, this.self.y);
277+ const me = this.players.get(this.selfId);
278+ if (me) this.camera.setTarget(me.x, me.y);
259279 this.camera.update(dt);
260280 this.engine.setView(this.camera.cx, this.camera.cy, this.camera.viewHeight);
261- this.engine.updateShips([...this.players.values()], [...this.npcs.values()], this.selfId);
262- this.engine.updateDynamic(this.projs, this.items, this.self?.queue ?? []);
281+ this.engine.updateShips([...this.players.values()], [...this.npcs.values()]);
282+ this.engine.updateDynamic(this.projs, this.items, this.self?.queue ?? [], this.hoverMark);
263283 this.engine.render(dt);
264284 requestAnimationFrame(() => this.frame());
265285 }
@@ -272,35 +292,13 @@ class Game {
272292 e.preventDefault();
273293 this.openContext(e.clientX, e.clientY);
274294 });
275- el.addEventListener("pointerdown", (e) => {
276- this.drag = { x: e.clientX, y: e.clientY, moved: false, button: e.button };
277- this.lastPointer = { x: e.clientX, y: e.clientY };
278- });
279295 el.addEventListener("pointermove", (e) => {
280296 this.lastPointer = { x: e.clientX, y: e.clientY };
281- if (this.drag) {
282- const dx = e.clientX - this.drag.x;
283- const dy = e.clientY - this.drag.y;
284- if (Math.abs(dx) + Math.abs(dy) > 4) this.drag.moved = true;
285- if (this.drag.button === 1) {
286- this.follow = false;
287- const ppu = this.camera.pixelsPerUnit();
288- this.camera.setTarget(this.camera.cx - dx / ppu, this.camera.cy + dy / ppu);
289- this.drag.x = e.clientX;
290- this.drag.y = e.clientY;
291- }
292- }
293297 this.hover();
294298 });
295- el.addEventListener("pointerup", (e) => {
296- const d = this.drag;
297- this.drag = null;
298- if (this.attachItem) {
299- if (e.button === 0) this.placePiece(this.camera.screenToWorld(e.clientX, e.clientY));
300- return;
301- }
302- if (!d || d.moved) return;
303- if (e.button === 0) this.leftClick(e.clientX, e.clientY, e.shiftKey);
299+ el.addEventListener("click", (e) => {
300+ if (this.attachItem) this.placePiece(this.camera.screenToWorld(e.clientX, e.clientY));
301+ else this.leftClick(e.clientX, e.clientY, e.shiftKey);
304302 });
305303 el.addEventListener("wheel", (e) => {
306304 e.preventDefault();
@@ -311,7 +309,6 @@ class Game {
311309 const tag = (document.activeElement?.tagName ?? "").toLowerCase();
312310 if (tag === "input" || tag === "textarea") return;
313311 if (e.key === "?") this.hud.help();
314- if (e.key === "c") this.follow = true;
315312 if (e.key === "Escape") {
316313 this.hud.closeContext();
317314 this.cancelAttach();
@@ -320,12 +317,16 @@ class Game {
320317 }
321318
322319 private hover() {
320+ this.hoverMark = null;
323321 if (this.attachItem) {
324322 const world = this.camera.screenToWorld(this.lastPointer.x, this.lastPointer.y);
325- const s = this.snapAttach(world);
323+ const s = this.placeSpot(world);
326324 this.engine.setAttachPreview(s ? this.toPreview(s) : null);
327- const valid = s?.valid ?? false;
328- this.hud.setHint(valid ? "click to attach" : "no room here", this.lastPointer.x, this.lastPointer.y);
325+ this.hud.setHint(
326+ s && s.valid ? "click to attach" : "piece must touch the hull, without overlapping",
327+ this.lastPointer.x,
328+ this.lastPointer.y,
329+ );
329330 return;
330331 }
331332 const hit = this.pick(this.lastPointer.x, this.lastPointer.y);
@@ -333,6 +334,7 @@ class Game {
333334 this.hud.setHint("", 0, 0);
334335 return;
335336 }
337+ if (hit.kind !== "piece") this.hoverMark = hit.w;
336338 this.hud.setHint(hit.hint, this.lastPointer.x, this.lastPointer.y);
337339 }
338340
@@ -345,34 +347,28 @@ class Game {
345347 const world = this.camera.screenToWorld(sx, sy);
346348 const hit = this.pick(sx, sy);
347349 if (hit) {
348- if (hit.kind === "piece") return;
349- if (hit.kind === "npc" || (hit.kind === "player" && hit.id !== this.selfId)) {
350- this.follow = true;
350+ if (hit.kind === "npc" || hit.kind === "player") {
351351 this.send({ t: "attack", target: hit.id });
352352 return;
353353 }
354- if (hit.kind === "player" && hit.id === this.selfId) return;
355354 if (hit.kind === "item") {
356- this.follow = true;
357355 this.send({ t: "pickup", target: hit.id });
358356 return;
359357 }
360358 if (hit.kind === "poi" && hit.moveTo) {
361- this.follow = true;
362359 this.send({ t: "move", x: hit.moveTo.x, y: hit.moveTo.y, queue: shift });
363360 return;
364361 }
365362 }
366- this.follow = true;
367363 this.send({ t: "move", x: world.x, y: world.y, queue: shift });
368364 }
369365
370366 private placePiece(world: Vec2) {
371367 if (!this.self || !this.attachItem) return;
372- const s = this.snapAttach(world);
368+ const s = this.placeSpot(world);
373369 if (!s) return;
374370 if (!s.valid) {
375- this.hud.toast("pieces would overlap");
371+ this.hud.toast("piece must touch the hull, without overlapping");
376372 return;
377373 }
378374 this.send({ t: "attach", target: this.attachItem, piece: s.anchorId, x: s.localX, y: s.localY });
@@ -385,16 +381,24 @@ class Game {
385381 this.hud.setHint("", 0, 0);
386382 }
387383
388- // snapAttach maps the cursor to a local position on a ring around the
389- // nearest ship piece, so the loose piece snaps onto a connection point.
390- private snapAttach(world: Vec2): Snap | null {
391- if (!this.self) return null;
384+ // me is the drawn (smoothed) position of the player's ship, which is what
385+ // the camera, the cursor and the attach ghost all work in.
386+ private me(): { x: number; y: number; a: number } | null {
387+ return this.players.get(this.selfId) ?? this.self;
388+ }
389+
390+ // placeSpot maps the cursor to a spot on the hull: anywhere the loose piece
391+ // stays connected to it and clear of every other piece.
392+ private placeSpot(world: Vec2): Snap | null {
393+ const me = this.me();
394+ const self = this.self;
395+ if (!me || !self || !this.attachItem) return null;
392396 const item = this.items.find((i) => i.id === this.attachItem);
393397 const shape = item?.item.shape;
394398 if (!shape) return null;
395- const a = this.self.a;
396- const local = rotate({ x: world.x - this.self.x, y: world.y - this.self.y }, -a);
397- const pieces = Object.values(this.self.ship.pieces);
399+ const a = me.a;
400+ const local = rotate({ x: world.x - me.x, y: world.y - me.y }, -a);
401+ const pieces = Object.values(self.ship.pieces);
398402 if (!pieces.length) return null;
399403 let anchor = pieces[0];
400404 let bestD = Infinity;
@@ -405,39 +409,25 @@ class Game {
405409 anchor = q;
406410 }
407411 }
408- let dx = local.x - anchor.x;
409- let dy = local.y - anchor.y;
410- const len = Math.hypot(dx, dy);
411- if (len < 1e-3) {
412- dx = 1;
413- dy = 0;
414- } else {
415- dx /= len;
416- dy /= len;
417- }
418- const sep = this.cfg.ship.minSeparation + 4;
419- const lx = anchor.x + dx * sep;
420- const ly = anchor.y + dy * sep;
421- let valid = true;
412+ let valid = bestD <= this.cfg.ship.attachMax;
422413 for (const q of pieces) {
423- if (q.id === anchor.id) continue;
424- if (Math.hypot(q.x - lx, q.y - ly) < this.cfg.ship.minSeparation) {
414+ if (Math.hypot(q.x - local.x, q.y - local.y) < this.cfg.ship.minSeparation) {
425415 valid = false;
426416 break;
427417 }
428418 }
429419 const toWorld = (x: number, y: number): Vec2 => ({
430- x: this.self!.x + Math.cos(a) * x - Math.sin(a) * y,
431- y: this.self!.y + Math.sin(a) * x + Math.cos(a) * y,
420+ x: me.x + Math.cos(a) * x - Math.sin(a) * y,
421+ y: me.y + Math.sin(a) * x + Math.cos(a) * y,
432422 });
433423 return {
434424 shape,
435425 anchorId: anchor.id,
436426 anchorShape: anchor.shape,
437- localX: lx,
438- localY: ly,
427+ localX: local.x,
428+ localY: local.y,
439429 valid,
440- world: toWorld(lx, ly),
430+ world: toWorld(local.x, local.y),
441431 anchorWorld: toWorld(anchor.x, anchor.y),
442432 a,
443433 };
@@ -468,29 +458,33 @@ class Game {
468458 }
469459 };
470460 const ppu = this.camera.pixelsPerUnit();
471- if (this.self) {
472- const a = this.self.a;
461+ const me = this.me();
462+ if (me && this.self) {
463+ const a = me.a;
473464 for (const p of Object.values(this.self.ship.pieces)) {
474- const wx = this.self.x + Math.cos(a) * p.x - Math.sin(a) * p.y;
475- const wy = this.self.y + Math.sin(a) * p.x + Math.cos(a) * p.y;
465+ const wx = me.x + Math.cos(a) * p.x - Math.sin(a) * p.y;
466+ const wy = me.y + Math.sin(a) * p.x + Math.cos(a) * p.y;
476467 const s = this.camera.worldToScreen(wx, wy);
477468 consider({
478469 kind: "piece",
479470 id: String(p.id),
480471 sx: s.x,
481472 sy: s.y,
473+ w: { x: wx, y: wy },
482474 screenR: Math.max(8, 20 * ppu),
483475 hint: `${p.shape} ${p.q}\u2605 ${Math.round(p.hp)}/${Math.round(p.maxHp)}`,
484476 });
485477 }
486478 }
487479 for (const p of this.players.values()) {
480+ if (p.id === this.selfId) continue;
488481 const s = this.camera.worldToScreen(p.x, p.y);
489482 consider({
490483 kind: "player",
491484 id: p.id,
492485 sx: s.x,
493486 sy: s.y,
487+ w: { x: p.x, y: p.y },
494488 screenR: 26,
495489 hint: p.cs,
496490 });
@@ -502,25 +496,34 @@ class Game {
502496 id: n.id,
503497 sx: s.x,
504498 sy: s.y,
499+ w: { x: n.x, y: n.y },
505500 screenR: 26 + 4 * Object.keys(n.ship.pieces).length,
506501 hint: n.name,
507502 });
508503 }
509504 for (const it of this.items) {
510505 const s = this.camera.worldToScreen(it.x, it.y);
511- consider({ kind: "item", id: it.id, sx: s.x, sy: s.y, screenR: 10, hint: it.item.kind });
506+ consider({
507+ kind: "item",
508+ id: it.id,
509+ sx: s.x,
510+ sy: s.y,
511+ w: { x: it.x, y: it.y },
512+ screenR: 20,
513+ hint: it.item.kind,
514+ });
512515 }
513516 for (const poi of this.pois.values()) {
514517 if (poi.kind === "fleet") continue;
515518 const s = this.camera.worldToScreen(poi.x, poi.y);
516- const label = poi.name || `unnamed ${KIND_LABEL[poi.kind]}`;
517519 consider({
518520 kind: "poi",
519521 id: poi.id,
520522 sx: s.x,
521523 sy: s.y,
522- screenR: Math.min(60, Math.max(10, poi.r * ppu)),
523- hint: label,
524+ w: { x: poi.x, y: poi.y },
525+ screenR: Math.min(120, Math.max(20, poi.r * ppu)),
526+ hint: this.label(poi),
524527 moveTo: safeApproach(poi, this.self, this.orbitDistance(poi.r)),
525528 });
526529 }
@@ -551,7 +554,7 @@ class Game {
551554 if (!poi) return;
552555 const items: CtxItem[] = [{ label: "orbit", action: () => this.send({ t: "orbit", target: id }) }];
553556 const inOrbit = this.inOrbit(poi);
554- if (!poi.name && poi.kind !== "fleet") {
557+ if (!poi.name && poi.kind !== "wreck") {
555558 items.push({
556559 label: "name this place",
557560 disabled: !inOrbit,
@@ -599,8 +602,7 @@ class Game {
599602 label: "attach to ship",
600603 action: () => {
601604 this.attachItem = id;
602- this.follow = true;
603- this.hud.toast("drag the piece onto a glowing spot");
605+ this.hud.toast("click a spot on the hull to place the piece");
604606 },
605607 });
606608 }
@@ -611,10 +613,6 @@ class Game {
611613 private playerMenu(sx: number, sy: number, id: string) {
612614 const p = this.players.get(id);
613615 if (!p) return;
614- if (id === this.selfId) {
615- this.selfMenu(sx, sy);
616- return;
617- }
618616 this.hud.openContext(sx, sy, p.cs, [
619617 { label: "share fuel", action: () => this.send({ t: "sharefuel", target: id }) },
620618 { label: "attack", action: () => this.send({ t: "attack", target: id }) },
@@ -633,20 +631,6 @@ class Game {
633631 return [...this.pois.values()].some((p) => p.kind === "shipyard" && this.inOrbit(p));
634632 }
635633
636- private selfMenu(sx: number, sy: number) {
637- if (!this.self) return;
638- this.hud.openContext(sx, sy, this.self.callsign, [
639- { label: "stop", action: () => this.send({ t: "stop" }) },
640- {
641- label: "self-destruct",
642- action: () =>
643- this.hud.confirm("Self-destruct and leave a wreck? This ends your run.", () =>
644- this.send({ t: "selfdestruct" }),
645- ),
646- },
647- ]);
648- }
649-
650634 private pieceMenu(sx: number, sy: number, id: number) {
651635 if (!this.self) return;
652636 const piece = this.self.ship.pieces[String(id)];
@@ -687,6 +671,7 @@ interface Pick {
687671 id: string;
688672 sx: number;
689673 sy: number;
674+ w: Vec2;
690675 screenR: number;
691676 hint: string;
692677 moveTo?: Vec2;
@@ -158,7 +158,7 @@ export type ServerMsg =
158158 | { t: "joined"; id: string; callsign: string; reconnect?: boolean }
159159 | { t: "death"; reason: string; stats: RunStats }
160160 | { t: "toast"; msg: string }
161- | { t: "radio"; from: string; text: string; ch: string }
161+ | { t: "radio"; from: string; text: string }
162162 | { t: "error"; msg: string };
163163
164164 export type ClientMsg =
@@ -139,12 +139,13 @@ body {
139139 height: 22px;
140140 border: 1px solid var(--p1);
141141 display: flex;
142+ flex-direction: column;
142143 align-items: center;
143144 justify-content: center;
144145 color: var(--p2);
145146 font-size: 12px;
146147 position: relative;
147- cursor: pointer;
148+ line-height: 1;
148149 }
149150
150151 #hud .slot.filled {
@@ -152,11 +153,12 @@ body {
152153 color: var(--gold);
153154 }
154155
156+#hud .slot .g {
157+ font-size: 11px;
158+}
159+
155160 #hud .slot .q {
156- position: absolute;
157- right: 1px;
158- bottom: 0;
159- font-size: 8px;
161+ font-size: 6px;
160162 color: var(--gold);
161163 }
162164
@@ -341,11 +343,6 @@ body {
341343 color: var(--gold);
342344 border: 1px solid var(--p2);
343345 padding: 6px 12px;
344- cursor: pointer;
345-}
346-
347-#hud button:hover {
348- background: var(--p1);
349346 }
350347
351348 #hud button.sel {
@@ -412,15 +409,9 @@ body {
412409 #hud .ctx .item {
413410 padding: 4px 12px;
414411 color: var(--p3);
415- cursor: pointer;
416412 white-space: nowrap;
417413 }
418414
419-#hud .ctx .item:hover {
420- background: var(--p1);
421- color: var(--gold);
422-}
423-
424415 #hud .ctx .head {
425416 padding: 3px 12px;
426417 color: var(--gold);
@@ -101,7 +101,7 @@ func (w *World) applyDamage(targetID string, amount float64, attacker string) {
101101 if p, ok := w.players[targetID]; ok {
102102 w.damageShip(p.Ship, p.Pos, amount)
103103 p.Stats.DamageReceived += amount
104- w.tagCombat(targetID, attacker)
104+ w.tagCombat(attacker, targetID)
105105 if len(p.Ship.Pieces) == 0 || p.Ship.Pieces[p.Ship.Root] == nil {
106106 w.killPlayer(p, "destroyed in combat")
107107 }
@@ -109,7 +109,7 @@ func (w *World) applyDamage(targetID string, amount float64, attacker string) {
109109 }
110110 if n, ok := w.npcs[targetID]; ok {
111111 w.damageShip(n.Ship, n.Pos, amount)
112- w.tagCombat(targetID, attacker)
112+ w.tagCombat(attacker, targetID)
113113 if len(n.Ship.Pieces) == 0 || n.Ship.Pieces[n.Ship.Root] == nil {
114114 w.destroyNPC(n)
115115 }
@@ -79,7 +79,6 @@ type Config struct {
7979 FuelPerPoint float64 `json:"fuelPerPoint"`
8080 MinSeparation float64 `json:"minSeparation"`
8181 AttachMax float64 `json:"attachMax"`
82- MaxPieces int `json:"maxPieces"`
8382 } `json:"ship"`
8483 Combat struct {
8584 Range float64 `json:"range"`
@@ -11,7 +11,7 @@
1111 "min": 5000,
1212 "max": 9000
1313 },
14- "discoverRange": 8000,
14+ "discoverRange": 1500,
1515 "orbitFactor": 2.5,
1616 "orbitMin": 140,
1717 "shape": {
@@ -68,8 +68,7 @@
6868 "speedPerPoint": 10,
6969 "fuelPerPoint": 10,
7070 "minSeparation": 45,
71- "attachMax": 140,
72- "maxPieces": 64
71+ "attachMax": 140
7372 },
7473 "combat": {
7574 "range": 320,
@@ -20,8 +20,8 @@ func (w *World) namePOI(p *Player, id, name string) {
2020 switch {
2121 case name == "" || len(name) > 24:
2222 w.toast(p, "invalid name")
23- case poi.Kind == kindFleet:
24- w.toast(p, "fleets cannot be named")
23+ case poi.Kind == kindFleet || poi.Kind == kindWreck:
24+ w.toast(p, "this place cannot be named")
2525 case poi.Name != "":
2626 w.toast(p, "this place is already named")
2727 case !inOrbitOf(p, poi):
@@ -213,13 +213,23 @@ func (w *World) stepPlayer(p *Player, dt float64) {
213213 p.Fuel = p.fuelCap()
214214 }
215215 }
216- if s := w.galaxy.starAt(p.Pos, p.Ship.Radius()); s != nil {
216+ if w.touchesStar(p) {
217217 w.killPlayer(p, "collided with a star")
218218 return
219219 }
220220 w.fireShip(p.ID, p.Ship, p.Pos, p.Angle, p.Target, dt, p.fire)
221221 }
222222
223+// touchesStar reports whether any piece of the ship overlaps a star.
224+func (w *World) touchesStar(p *Player) bool {
225+ for _, piece := range p.Ship.piecesSlice() {
226+ if w.galaxy.starAt(p.Pos.Add(rotate(Vec2{piece.X, piece.Y}, p.Angle)), 0) != nil {
227+ return true
228+ }
229+ }
230+ return false
231+}
232+
223233 // killPlayer destroys a player, leaving behind a wreck POI, and notifies the
224234 // client with the run statistics.
225235 func (w *World) killPlayer(p *Player, reason string) {
@@ -276,10 +286,6 @@ func (w *World) attach(p *Player, itemID string, to int, x, y float64) {
276286 if _, ok := p.Ship.Pieces[to]; !ok {
277287 return
278288 }
279- if len(p.Ship.Pieces) >= config.Ship.MaxPieces {
280- w.toast(p, "ship is at its size limit")
281- return
282- }
283289 np := Vec2{x, y}
284290 if np.Dist(Vec2{p.Ship.Pieces[to].X, p.Ship.Pieces[to].Y}) > config.Ship.AttachMax {
285291 w.toast(p, "piece is not adjacent")
@@ -17,21 +17,13 @@ func (w *World) radio(p *Player, text string) {
1717
1818 func (w *World) deliver(from *Player, callsign, text string) {
1919 for _, q := range w.players {
20- ch := ""
21- switch {
22- case q == from:
23- ch = "local"
Cut short: this commit's diff is over 1000 lines.