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

space-browser / commits / 63f6f62

feat: baren planets now spit out ore, player can tow

xonecas5 weeks ago63f6f6251250d4b07cffd1ed22b58ca96f75f9c2parent bc7914e5 files changed

client/src/main.ts+29-3
@@ -1,5 +1,5 @@
11 import { connect, type State } from './net';
2-import type { Loose, Ship } from './sim';
2+import type { Loose, Ore, Ship } from './sim';
33 import { View, CELL, CELL_WORLD, ZOOM_MIN, ZOOM_MAX, type Camera } from './view';
44
55 const canvas = document.getElementById('view') as HTMLCanvasElement;
@@ -25,10 +25,12 @@ const net = connect((s) => {
2525 // smooth without ever deciding anything ourselves.
2626 const ships = new Map<number, Ship>();
2727 const loose = new Map<number, Loose>();
28+const ore = new Map<number, Ore>();
2829
2930 const cam: Camera & { follow: boolean } = { x: 0, y: 0, zoom: 0.5, follow: true };
3031 const keys = new Set<string>();
3132 let pan0: { x: number; y: number } | null = null; // right/middle drag moves the camera
33+let down0: { x: number; y: number } | null = null; // where the right button went down
3234 let pulling = false; // left button down: keep reporting where the piece is
3335 let pullTo: { x: number; y: number } | null = null;
3436 let pullIn = 0;
@@ -50,7 +52,7 @@ const at = (e: MouseEvent) => {
5052
5153 addEventListener('pointerdown', (e) => {
5254 if (e.button !== 0) {
53- pan0 = { x: e.clientX, y: e.clientY };
55+ pan0 = down0 = { x: e.clientX, y: e.clientY };
5456 return;
5557 }
5658 const p = at(e);
@@ -69,6 +71,16 @@ addEventListener('pointermove', (e) => {
6971 });
7072
7173 addEventListener('pointerup', (e) => {
74+ // A right click that did not pan is a tow order: the server hooks or releases
75+ // the ore under the cursor.
76+ if (e.button === 2) {
77+ if (down0 && Math.hypot(e.clientX - down0.x, e.clientY - down0.y) < 4) {
78+ const p = at(e);
79+ net.send({ t: 'tow', x: p.x, y: p.y });
80+ }
81+ pan0 = down0 = null;
82+ return;
83+ }
7284 pan0 = null;
7385 if (!pulling) return;
7486 pulling = false;
@@ -149,6 +161,20 @@ function frame(): void {
149161 }
150162 }
151163 for (const id of loose.keys()) if (!looseLive.has(id)) loose.delete(id);
164+
165+ const oreLive = new Set<number>();
166+ for (const o of state.ore) {
167+ oreLive.add(o.id);
168+ const d = ore.get(o.id);
169+ if (!d) ore.set(o.id, { ...o });
170+ else {
171+ d.x = ease(d.x, o.x, k);
172+ d.y = ease(d.y, o.y, k);
173+ d.h = turn(d.h, o.h, k);
174+ d.towed = o.towed;
175+ }
176+ }
177+ for (const id of ore.keys()) if (!oreLive.has(id)) ore.delete(id);
152178 }
153179
154180 const me = state ? ships.get(state.you) : undefined;
@@ -160,7 +186,7 @@ function frame(): void {
160186
161187 // The marker is the order the server is flying: never a click of our own.
162188 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);
189+ view.draw(cam, state?.bodies ?? [], [...ships.values()], state?.you ?? 0, [...loose.values()], [...ore.values()], marker);
164190 requestAnimationFrame(frame);
165191 }
166192 requestAnimationFrame(frame);
client/src/net.ts+2-2
@@ -1,8 +1,8 @@
11 // One socket is one player. The server owns the world; we send intents and are
22 // handed back the state to draw.
3-import type { Body, Loose, Ship } from './sim';
3+import type { Body, Loose, Ore, Ship } from './sim';
44
5-export type State = { you: number; held: number; bodies: Body[]; loose: Loose[]; players: Ship[] };
5+export type State = { you: number; held: number; bodies: Body[]; loose: Loose[]; ore: Ore[]; players: Ship[] };
66
77 export function connect(onState: (s: State) => void): { send: (msg: unknown) => void } {
88 let ws: WebSocket | null = null;
client/src/sim.ts+1-0
@@ -5,6 +5,7 @@ export type Kind = 'gun' | 'armor' | 'cargo' | 'engine';
55 // Piece position is local to the ship: the graph is rigid, so only the hull moves.
66 export type Piece = { id: number; kind: Kind; lx: number; ly: number; parent: number };
77 export type Loose = { id: number; kind: Kind; x: number; y: number; h: number };
8+export type Ore = { id: number; x: number; y: number; h: number; towed: number };
89 export type Body = { id: number; kind: 'star' | 'shipyard' | 'barren'; r: number; x: number; y: number };
910
1011 export type Ship = {
client/src/view.ts+37-2
@@ -2,13 +2,14 @@
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 Body, type Kind, type Loose, type Ship } from './sim';
5+import { toWorld, type Body, type Kind, type Loose, type Ore, type Ship } from './sim';
66
77 export const CELL = 12; // css px per character cell
88 export const CELL_WORLD = 2; // world units per character cell at zoom 1
9-export const ZOOM_MIN = 0.3; // furthest out: far enough to frame a whole system
9+export const ZOOM_MIN = 0.5; // furthest out: far enough to frame a whole system
1010 export const ZOOM_MAX = 2; // closest in
1111 const SHIP_R = 11; // world radius of a hull
12+const ORE_R = 6.5; // world radius of an ore piece
1213
1314 export type Camera = { x: number; y: number; zoom: number };
1415
@@ -110,6 +111,8 @@ const SHADE = {
110111 own: [lum(1, 7), lum(0.5, 7)],
111112 other: [lum(0.8, 6), lum(0.4, 6)],
112113 loose: [lum(0.55, 5), lum(0.28, 5)],
114+ ore: [lum(0.95, 6), lum(0.5, 4)], // ore in a planet's ring
115+ towed: [lum(1, 7), lum(0.55, 6)], // ore on someone's line, bright as a hull
113116 };
114117 export type Role = keyof typeof SHADE;
115118 const shade = (g: THREE.Group, role: Role) => {
@@ -127,6 +130,16 @@ function piece(kind: Kind): THREE.Group {
127130 return g;
128131 }
129132
133+// Ore is a small faceted chunk: a hexagon with a darker core, the one thing in
134+// space that is neither a ship piece nor a body.
135+function oreChunk(): THREE.Group {
136+ const g = new THREE.Group();
137+ g.add(new THREE.Mesh(new THREE.ShapeGeometry(poly(6, ORE_R)), new THREE.MeshBasicMaterial({ color: SHADE.ore[0] })));
138+ g.add(new THREE.Mesh(new THREE.ShapeGeometry(poly(6, ORE_R * 0.55, 0, 0.4)), new THREE.MeshBasicMaterial({ color: SHADE.ore[1] })));
139+ shade(g, 'ore');
140+ return g;
141+}
142+
130143 // A click target: a plus of 5 cells, bright enough to read past the dust.
131144 function crosshair(): THREE.Group {
132145 const g = new THREE.Group();
@@ -219,6 +232,7 @@ export class View {
219232 private pass: THREE.ShaderMaterial;
220233 private quad = new THREE.Scene();
221234 private pieceMeshes = new Map<number, THREE.Group>();
235+ private oreMeshes = new Map<number, THREE.Group>();
222236 private bodyMeshes = new Map<number, THREE.Group>();
223237 private marker = crosshair();
224238 private cols = 0;
@@ -315,6 +329,7 @@ export class View {
315329 ships: Ship[],
316330 ownId: number,
317331 loose: Loose[],
332+ ore: Ore[],
318333 marker: { x: number; y: number } | null,
319334 ): void {
320335 // Zoom is world units per character cell: the raster keeps one texel per
@@ -344,6 +359,26 @@ export class View {
344359 this.scene.remove(g);
345360 this.pieceMeshes.delete(id);
346361 }
362+ // Ore is its own thing: not a piece, so it never snaps onto a hull. Towed ore
363+ // lights up like a hull so a full line reads at a glance.
364+ const oreSeen = new Set<number>();
365+ for (const o of ore) {
366+ oreSeen.add(o.id);
367+ let g = this.oreMeshes.get(o.id);
368+ if (!g) {
369+ g = oreChunk();
370+ this.oreMeshes.set(o.id, g);
371+ this.scene.add(g);
372+ }
373+ shade(g, o.towed ? 'towed' : 'ore');
374+ g.position.set(o.x, o.y, 0);
375+ g.rotation.z = o.h;
376+ }
377+ for (const [id, g] of this.oreMeshes) {
378+ if (oreSeen.has(id)) continue;
379+ this.scene.remove(g);
380+ this.oreMeshes.delete(id);
381+ }
347382 this.marker.visible = marker !== null;
348383 if (marker) {
349384 // Snap to the rendered cell grid, or a one-cell marker lands between four.
server/main.go+218-3
@@ -5,6 +5,7 @@ import (
55 "flag"
66 "log"
77 "math"
8+ "math/rand"
89 "net/http"
910 "sort"
1011 "strconv"
@@ -35,6 +36,18 @@ const (
3536 spawnX = 0.0
3637 spawnY = -70.0
3738 reach = 4000.0 // an order further out than this is ignored
39+
40+ oreGap = 15.0 // closest two ore may sit: also the spacing of the rings
41+ oreRings = 4 // rings a barren planet can park ore on
42+ oreRingMin = 12.0 // first ring's distance beyond the surface
43+ oreBrake = 10.0 // outward deceleration, so a launch coasts out then parks
44+ oreOrbitV = 12.0 // world units per second travelled along a ring
45+ oreGrab = 10.0 // click radius to take an ore piece on a tow line
46+ towReach = 40.0 // how close the ship must be to throw a line on an ore
47+ towGap = 12.0 // distance between ore on a tow line
48+ oreWaitMin = 30.0 // a barren planet throws an ore every 30-60s
49+ oreWaitMax = 60.0
50+ oreHolds = 3 // a barren planet holds 3-6 ore, a fixed count per planet
3851 )
3952
4053 // A hull is a graph of pieces placed relative to the ship. Piece ids are unique
@@ -57,6 +70,23 @@ type loose struct {
5770 held int // player dragging it, 0 = free
5871 }
5972
73+// An ore piece is thrown out of a barren planet and parks in one of its rings.
74+// It lives in the planet's rotating frame (an angle and a radius), so it travels
75+// with the planet around the star, and it is only a world point once placed.
76+type ore struct {
77+ ID int `json:"id"`
78+ X float64 `json:"x"`
79+ Y float64 `json:"y"`
80+ H float64 `json:"h"`
81+ Towed int `json:"towed"` // player hauling it, 0 = loose
82+
83+ planet int // body it orbits, 0 = drifting where it was let go
84+ a float64 // slot angle on its ring, in the planet's frame
85+ r float64 // current distance from the planet centre
86+ vr float64 // outward speed, 0 once it is parked in its ring
87+ ring float64 // radius it settles into
88+}
89+
6090 // A body is a star or a planet. Orbit 0 and speed 0 is the star, which never
6191 // moves; planets revolve and their current place is recomputed every tick.
6292 type body struct {
@@ -68,6 +98,8 @@ type body struct {
6898 orbit float64
6999 a0 float64
70100 speed float64
101+ wait float64 // seconds until a barren planet throws its next ore
102+ cap int // how many ore this barren planet keeps in orbit
71103 }
72104
73105 type player struct {
@@ -85,6 +117,7 @@ type player struct {
85117 ox, oy float64 // ring point, in world space, at the moment of anchoring
86118 anchored float64 // world time of anchoring
87119 held int // loose piece being dragged, 0 = none
120+ tow []int // ore on the tow line, in order behind the ship
88121 }
89122
90123 type client struct {
@@ -98,6 +131,7 @@ type hub struct {
98131 nextID int
99132 bodies []*body
100133 loose []*loose
134+ ore []*ore
101135 nextPiece int
102136 time float64
103137 }
@@ -108,6 +142,7 @@ type state struct {
108142 Held int `json:"held"`
109143 Bodies []*body `json:"bodies"`
110144 Loose []*loose `json:"loose"`
145+ Ore []*ore `json:"ore"`
111146 Players []*player `json:"players"`
112147 }
113148
@@ -124,13 +159,13 @@ func main() {
124159 }
125160
126161 func newHub() *hub {
127- h := &hub{clients: map[*client]bool{}}
162+ h := &hub{clients: map[*client]bool{}, ore: []*ore{}}
128163 // One hand-tuned system: a star, a shipyard planet and a barren planet, both
129164 // revolving. The real galaxy generator replaces this later.
130165 h.bodies = []*body{
131166 {ID: 1, Kind: "star", R: starR},
132167 {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},
168+ {ID: 3, Kind: "barren", R: 28, orbit: 215, a0: 0.6, speed: 0.035, wait: oreWait(), cap: oreHolds + rand.Intn(4)},
134169 }
135170 // Wreckage around the spawn, to build a first hull out of.
136171 for i, k := range []string{"armor", "cargo", "engine", "gun"} {
@@ -189,6 +224,8 @@ func (h *hub) handle(w http.ResponseWriter, r *http.Request) {
189224 h.drag(c.p, *in.X, *in.Y)
190225 case "drop":
191226 h.drop(c.p, *in.X, *in.Y)
227+ case "tow":
228+ h.towLine(c.p, *in.X, *in.Y)
192229 }
193230 h.mu.Unlock()
194231 }
@@ -198,6 +235,11 @@ func (h *hub) handle(w http.ResponseWriter, r *http.Request) {
198235 if l := h.looseByID(c.p.held); l != nil {
199236 l.held = 0
200237 }
238+ for _, id := range c.p.tow {
239+ if o := h.oreByID(id); o != nil {
240+ o.Towed = 0 // the line goes slack where the ship died
241+ }
242+ }
201243 h.mu.Unlock()
202244 ws.Close()
203245 }
@@ -246,6 +288,45 @@ func (h *hub) drop(p *player, x, y float64) {
246288 h.attach(p, l)
247289 }
248290
291+// A right click toggles a tow line on the ore under the cursor: hook a loose one,
292+// or let go of one already behind the ship. The line holds one ore plus one per
293+// cargo piece, so an empty hull can always haul a single ore.
294+func (h *hub) towLine(p *player, x, y float64) {
295+ o := h.oreAt(p, x, y)
296+ if o == nil {
297+ return
298+ }
299+ if o.Towed == p.ID {
300+ p.release(o)
301+ return
302+ }
303+ if o.Towed != 0 || len(p.tow) >= p.towLimit() {
304+ return
305+ }
306+ o.Towed, o.planet = p.ID, 0 // off the ring and onto the line
307+ p.tow = append(p.tow, o.ID)
308+}
309+
310+func (p *player) release(o *ore) {
311+ o.Towed = 0
312+ for i, id := range p.tow {
313+ if id == o.ID {
314+ p.tow = append(p.tow[:i], p.tow[i+1:]...)
315+ return
316+ }
317+ }
318+}
319+
320+func (p *player) towLimit() int {
321+ n := 1
322+ for _, q := range p.Pieces {
323+ if q.Kind == "cargo" {
324+ n++
325+ }
326+ }
327+ return n
328+}
329+
249330 // ---- world ----
250331
251332 // Parking on a body bolts the target to that body's frame: the ring point turns
@@ -361,6 +442,16 @@ func (h *hub) step(dt float64) {
361442 for _, b := range h.bodies {
362443 a := b.a0 + b.speed*h.time
363444 b.X, b.Y = math.Cos(a)*b.orbit, math.Sin(a)*b.orbit
445+ if b.Kind != "barren" {
446+ continue
447+ }
448+ if b.wait -= dt; b.wait <= 0 {
449+ b.wait = oreWait()
450+ h.spawnOre(b)
451+ }
452+ }
453+ for _, o := range h.ore {
454+ h.stepOre(o, dt)
364455 }
365456 for c := range h.clients {
366457 p := c.p
@@ -371,7 +462,102 @@ func (h *hub) step(dt float64) {
371462 p.TY = p.ox*sn + p.oy*cs
372463 }
373464 p.steer(dt)
465+ for i, id := range p.tow {
466+ if o := h.oreByID(id); o != nil {
467+ h.onLine(o, p, float64(i+1))
468+ }
469+ }
470+ }
471+}
472+
473+func oreWait() float64 { return oreWaitMin + rand.Float64()*(oreWaitMax-oreWaitMin) }
474+
475+// A barren planet throws one ore off its surface every 30-60s, aimed straight
476+// out, until it holds its full 3-6. The ore coasts out, braking as it goes, and
477+// parks in a free slot on one of the planet's rings, so no two ore ever overlap.
478+func (h *hub) spawnOre(b *body) {
479+ if h.oreCount(b.ID) >= b.cap {
480+ return // the planet is holding all the ore it will ever hold
481+ }
482+ ring, a, ok := h.oreSlot(b)
483+ if !ok {
484+ return // no room left in orbit, the planet keeps this one
374485 }
486+ o := &ore{ID: h.pieceID(), planet: b.ID, ring: ring, r: b.R + 2, a: a}
487+ o.vr = math.Sqrt(2 * oreBrake * (ring - o.r)) // just enough to reach the ring
488+ h.placeOre(o, b)
489+ h.ore = append(h.ore, o)
490+}
491+
492+// A free parking slot: a ring and a slot angle on it, clear of every ore already
493+// out there. A full planet hands the ore back instead of stacking it.
494+func (h *hub) oreSlot(b *body) (float64, float64, bool) {
495+ for i := 0; i < 32; i++ {
496+ ring := b.R + oreRingMin + float64(rand.Intn(oreRings))*oreGap
497+ a := rand.Float64() * 2 * math.Pi
498+ if h.oreClear(b.ID, ring, a) {
499+ return ring, a, true
500+ }
501+ }
502+ return 0, 0, false
503+}
504+
505+// Ore in orbit around a planet, which is what the planet's cap counts. Ore on a
506+// tow line has left the planet, so hauling some away lets the planet make more.
507+func (h *hub) oreCount(planet int) int {
508+ n := 0
509+ for _, o := range h.ore {
510+ if o.planet == planet {
511+ n++
512+ }
513+ }
514+ return n
515+}
516+
517+func (h *hub) oreClear(planet int, ring, a float64) bool {
518+ for _, o := range h.ore {
519+ if o.planet != planet || math.Abs(o.ring-ring) > 1 {
520+ continue // a different ring is a different radius, so never a clash
521+ }
522+ if math.Abs(wrap(o.a-a))*ring < oreGap {
523+ return false
524+ }
525+ }
526+ return true
527+}
528+
529+func (h *hub) stepOre(o *ore, dt float64) {
530+ if o.Towed != 0 {
531+ return // its ship places it
532+ }
533+ b := h.body(o.planet)
534+ if b == nil {
535+ return // let go in open space, it just drifts where it was dropped
536+ }
537+ if o.vr > 0 {
538+ o.r += o.vr * dt
539+ o.vr = math.Max(0, o.vr-oreBrake*dt)
540+ if o.r >= o.ring {
541+ o.r, o.vr = o.ring, 0 // in orbit now
542+ }
543+ }
544+ h.placeOre(o, b)
545+}
546+
547+// An ore never leaves its slot: the whole ring turns instead, so two ore parked on
548+// one ring stay exactly as far apart as they were placed, forever. The planet's own
549+// angle is folded in too, so the ring rides around the star with its planet.
550+func (h *hub) placeOre(o *ore, b *body) {
551+ a := o.a + (oreOrbitV/o.ring)*h.time + b.a0 + b.speed*h.time
552+ o.X, o.Y = b.X+math.Cos(a)*o.r, b.Y+math.Sin(a)*o.r
553+ o.H = a
554+}
555+
556+// Ore on a tow line trails straight behind the hull, in the order it was hooked.
557+func (h *hub) onLine(o *ore, p *player, n float64) {
558+ d := towGap * n
559+ o.X, o.Y = p.X-math.Cos(p.H)*d, p.Y-math.Sin(p.H)*d
560+ o.H = p.H
375561 }
376562
377563 func (h *hub) tick() {
@@ -387,7 +573,7 @@ func (h *hub) tick() {
387573 for c := range h.clients {
388574 b, err := json.Marshal(state{
389575 T: "state", You: c.p.ID, Held: c.p.held,
390- Bodies: h.bodies, Loose: h.loose, Players: players,
576+ Bodies: h.bodies, Loose: h.loose, Ore: h.ore, Players: players,
391577 })
392578 if err == nil {
393579 out[c] = b
@@ -445,6 +631,35 @@ func (h *hub) freeLooseAt(x, y float64) *loose {
445631 return got
446632 }
447633
634+func (h *hub) oreByID(id int) *ore {
635+ for _, o := range h.ore {
636+ if o.ID == id {
637+ return o
638+ }
639+ }
640+ return nil
641+}
642+
643+// Ore another player already has on their line is not a click target: it is
644+// theirs until they let go. A line is thrown from the ship, so ore far out of
645+// reach cannot be hooked either.
646+func (h *hub) oreAt(p *player, x, y float64) *ore {
647+ var got *ore
648+ best := oreGrab
649+ for _, o := range h.ore {
650+ if o.Towed != 0 && o.Towed != p.ID {
651+ continue
652+ }
653+ if math.Hypot(p.X-o.X, p.Y-o.Y) > towReach {
654+ continue
655+ }
656+ if d := math.Hypot(o.X-x, o.Y-y); d < best {
657+ best, got = d, o
658+ }
659+ }
660+ return got
661+}
662+
448663 func (h *hub) removeLoose(id int) {
449664 for i, l := range h.loose {
450665 if l.ID == id {