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

space-browser / commits / 067ab57

feat: fuel economy

xonecas5 weeks ago067ab57d8dc199c328765e89bc9eee9716da69c3parent 36c62d35 files changed

GAME_DESIGN.md+2-2
@@ -108,8 +108,8 @@ Combat is frequent, automated, and controlled purely through movement and positi
108108
109109 ## Deep Space Travel & Fuel
110110
111-- **Fuel Economy:** Normal flight burns fuel. Orbiting a Planet with a Shipyard refuels the ship. Fuel capacity only grows with Star pieces, so range is a late-game achievement, not a given.
112-- **Stranded:** Running out of fuel leaves the ship unable to move — it can only talk on the radio and self-destruct. There is no rescue mechanic and no tow service; going out too far with a small tank is a real death.
111+- **Fuel Economy:** Fuel is spent per unit of distance flown, so a ship that is stopped or settled in orbit spends nothing. Orbiting a Shipyard Planet refills the tank for free. Fuel capacity only grows with Star pieces, so range is a late-game achievement, not a given.
112+- **Out Of Fuel Is Death:** A dry tank ends the run on the spot, leaving the hull and its tow line in space as a wreck like any other death. There is no rescue mechanic, no tow service and no self-destruct order; going out too far with a small tank is a real death.
113113 - **Deep Space Travel Mode:** Returning to known shipyards or crossing between systems manually at normal speed is dull. Players open the **Galaxy Map Scene** to plot a multi-point route and engage **Deep Space Mode**:
114114 - The ship travels significantly faster and burns much less fuel.
115115 - **Trade-off:** Weapons do not fire in Deep Space Mode and the hull takes damage without maneuvering to dodge it. Rogue AI cannot follow you, but crossing a system with hostiles in it means being shot at, unable to answer, until you drop out of Deep Space Mode and fight. Routes that pass near stars carry the same risk.
client/src/main.ts+2-0
@@ -136,6 +136,8 @@ function frame(): void {
136136 s.h = turn(s.h, p.h, k);
137137 s.tx = p.tx;
138138 s.ty = p.ty;
139+ s.fuel = p.fuel; // a gauge has to jump, not ease, or it lies about the tank
140+ s.fuelmax = p.fuelmax;
139141 s.pieces = p.pieces; // a hull is never eased: a piece is where the server says
140142 }
141143 }
client/src/sim.ts+2-1
@@ -34,7 +34,8 @@ export type Ship = {
3434 h: number;
3535 tx: number; // where it is flying to, so the marker can show the order
3636 ty: number;
37- fuel: number; // capacity, summed from the hull
37+ fuel: number; // what is in the tank
38+ fuelmax: number; // capacity, summed from the hull
3839 pieces: Piece[];
3940 };
4041
client/src/view.ts+80-10
@@ -10,9 +10,15 @@ export const ZOOM_MIN = 0.6; // furthest out: far enough to frame a whole system
1010 export const ZOOM_MAX = 1.8; // closest in
1111 const SHIP_R = 11; // world radius of a hull
1212 const ORE_R = 6.5; // world radius of an ore piece
13+const FUEL_CELLS = 12; // the fuel gauge is this many cells wide at any zoom
14+const FUEL_WORD = 'FUEL'; // a word, not glyphs: letters are spelled out per cell
1315
1416 export type Camera = { x: number; y: number; zoom: number };
1517
18+// Snap a world point to the centre of the cell that holds it: a one-cell mark has
19+// to land on a glyph, not straddle four of them.
20+const snapCell = (v: number, c: number, wpc: number) => c + (Math.floor((v - c) / wpc) + 0.5) * wpc;
21+
1622 const GLYPHS = ' .:-=+*#%@';
1723 // 0-7 is the amber ramp used for everything that flies. 8-12 are reserved for
1824 // celestial bodies, so a rust planet and a steel planet never read as each other.
@@ -26,17 +32,19 @@ const ATLAS_CELL = 32;
2632 // R = luminance, G = palette index.
2733 const lum = (v: number, idx = 7) => new THREE.Color(v, idx / (PALETTE.length - 1), 0);
2834
29-function glyphAtlas(): THREE.Texture {
35+// One cell of white ink per character, in the same monospace face as the ramp: the
36+// glyph atlas and any hud word are the same kind of texture.
37+function textAtlas(text: string): THREE.Texture {
3038 const c = document.createElement('canvas');
31- c.width = GLYPHS.length * ATLAS_CELL;
39+ c.width = text.length * ATLAS_CELL;
3240 c.height = ATLAS_CELL;
3341 const g = c.getContext('2d')!;
3442 g.font = `700 ${ATLAS_CELL - 1}px ui-monospace, SFMono-Regular, Menlo, monospace`;
3543 g.textAlign = 'center';
3644 g.textBaseline = 'middle';
3745 g.fillStyle = '#fff';
38- for (let i = 0; i < GLYPHS.length; i++) {
39- g.fillText(GLYPHS[i], i * ATLAS_CELL + ATLAS_CELL / 2, ATLAS_CELL / 2);
46+ for (let i = 0; i < text.length; i++) {
47+ g.fillText(text[i], i * ATLAS_CELL + ATLAS_CELL / 2, ATLAS_CELL / 2);
4048 }
4149 const t = new THREE.CanvasTexture(c);
4250 t.minFilter = t.magFilter = THREE.LinearFilter;
@@ -62,6 +70,9 @@ uniform sampler2D uPalette;
6270 uniform vec3 uBg;
6371 uniform vec2 uCells;
6472 uniform float uCellPx;
73+uniform sampler2D uWord; // hud ink, in cells, drawn over the glyphs
74+uniform vec4 uWordCell; // x, y, width, height of the word, in cells from the corner
75+uniform vec3 uWordCol;
6576
6677 void main() {
6778 vec2 uv = gl_FragCoord.xy / uCellPx;
@@ -70,7 +81,12 @@ void main() {
7081 vec3 col = texture2D(uPalette, vec2((s.g * ${PALETTE.length - 1}.0 + 0.5) / ${PALETTE.length}.0, 0.5)).rgb;
7182 vec2 local = clamp(fract(uv), 0.02, 0.98);
7283 float ink = texture2D(uAtlas, vec2((band + local.x) / ${GLYPHS.length}.0, local.y)).a;
73- gl_FragColor = vec4(mix(uBg, col, ink), 1.0);
84+ vec3 outCol = mix(uBg, col, ink);
85+ vec2 w = (uv - uWordCell.xy) / uWordCell.zw;
86+ if (w.x >= 0.0 && w.x < 1.0 && w.y >= 0.0 && w.y < 1.0) {
87+ outCol = mix(outCol, uWordCol, texture2D(uWord, w).a);
88+ }
89+ gl_FragColor = vec4(outCol, 1.0);
7490 }
7591 `;
7692
@@ -99,7 +115,7 @@ function pieceGeometry(kind: Kind, scale: number): THREE.BufferGeometry {
99115 return new THREE.ShapeGeometry(poly(3, r));
100116 }
101117
102-function plate(w: number, h: number, v: number): THREE.Mesh {
118+function plate(w: number, h: number, v: number): THREE.Mesh<THREE.PlaneGeometry, THREE.MeshBasicMaterial> {
103119 return new THREE.Mesh(new THREE.PlaneGeometry(w, h), new THREE.MeshBasicMaterial({ color: lum(v) }));
104120 }
105121
@@ -257,6 +273,10 @@ export class View {
257273 private oreMeshes = new Map<number, THREE.Group>();
258274 private bodyMeshes = new Map<number, THREE.Group>();
259275 private marker = crosshair();
276+ private hud = new THREE.Scene();
277+ private hudCam = new THREE.OrthographicCamera(-1, 1, 1, -1, 0.1, 100);
278+ private fuelBar = new THREE.Group();
279+ private fuelCells: Part[] = [];
260280 private cols = 0;
261281 private rows = 0;
262282
@@ -265,6 +285,17 @@ export class View {
265285 this.renderer = new THREE.WebGLRenderer({ canvas, antialias: false });
266286 this.renderer.outputColorSpace = THREE.LinearSRGBColorSpace;
267287 this.scene.add(this.marker);
288+ // The fuel gauge is geometry in a HUD layer, not a page overlay: it is built
289+ // from the same cells as everything else, so it reads as part of the game,
290+ // and it is measured in cells rather than in the world, so flying cannot make
291+ // it hop from one cell to the next.
292+ this.hudCam.position.z = 10;
293+ this.hud.add(this.fuelBar);
294+ for (let i = 0; i < FUEL_CELLS; i++) {
295+ const m = plate(1, 1, 1);
296+ this.fuelCells.push(m);
297+ this.fuelBar.add(m);
298+ }
268299 this.rt = new THREE.WebGLRenderTarget(1, 1, {
269300 samples: 4,
270301 depthBuffer: false,
@@ -277,11 +308,14 @@ export class View {
277308 fragmentShader: FRAG,
278309 uniforms: {
279310 uScene: { value: this.rt.texture },
280- uAtlas: { value: glyphAtlas() },
311+ uAtlas: { value: textAtlas(GLYPHS) },
281312 uPalette: { value: paletteTexture() },
282313 uBg: { value: new THREE.Color(PALETTE[0]) },
283314 uCells: { value: new THREE.Vector2() },
284315 uCellPx: { value: CELL },
316+ uWord: { value: textAtlas(FUEL_WORD) },
317+ uWordCell: { value: new THREE.Vector4() },
318+ uWordCol: { value: new THREE.Color(PALETTE[5]) },
285319 },
286320 });
287321 const quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), this.pass);
@@ -327,6 +361,12 @@ export class View {
327361 this.canvas.style.height = `${h}px`;
328362 this.rt.setSize(this.cols, this.rows);
329363 this.pass.uniforms.uCells.value.set(this.cols, this.rows);
364+ // One HUD unit is one cell, so a plate of size 1 covers exactly one glyph.
365+ this.hudCam.left = -this.cols / 2;
366+ this.hudCam.right = this.cols / 2;
367+ this.hudCam.top = this.rows / 2;
368+ this.hudCam.bottom = -this.rows / 2;
369+ this.hudCam.updateProjectionMatrix();
330370 this.pass.uniforms.uCellPx.value = CELL * dpr;
331371 }
332372
@@ -354,6 +394,34 @@ export class View {
354394 g.rotation.z = h;
355395 }
356396
397+ // The fuel gauge is a row of cells two rows off the bottom of the screen, in a
398+ // layer that only knows about cells. Gold while there is plenty, and a red pulse
399+ // that quickens as the tank empties.
400+ private fuel(own: Ship | undefined, t: number): void {
401+ this.fuelBar.visible = !!own && own.fuelmax > 0;
402+ this.pass.uniforms.uWordCell.value.set(0, 0, 0, 0); // no tank, no word
403+ if (!own || own.fuelmax <= 0) return;
404+ const start = Math.floor((this.cols - FUEL_CELLS) / 2);
405+ const ratio = Math.max(0, Math.min(1, own.fuel / own.fuelmax));
406+ const lit = Math.ceil(ratio * FUEL_CELLS);
407+ const low = ratio <= 0.25;
408+ // The pulse never dims a lit cell into the same glyph band as the empty
409+ // track, or the gauge would look shorter than it is while it warns.
410+ const blink = 0.45 + 0.55 * (0.5 + 0.5 * Math.sin(t * (6 + 120 * (0.25 - ratio))));
411+ // A cell t is centred on t+0.5 measured from the edge, so this lands on glyphs.
412+ const x = start - this.cols / 2 + 0.5;
413+ const y = 2 - this.rows / 2 + 0.5;
414+ // The label sits on the same row, one cell clear of the bar.
415+ const w = Math.max(0, start - 1 - FUEL_WORD.length);
416+ this.pass.uniforms.uWordCell.value.set(w, 2, FUEL_WORD.length, 1);
417+ for (let i = 0; i < FUEL_CELLS; i++) {
418+ const m = this.fuelCells[i];
419+ m.position.set(x + i, y, 0);
420+ m.scale.set(0.85, 0.85, 1);
421+ m.material.color.copy(i < lit ? lum(low ? blink : 1, low ? 14 : 6) : lum(0.22, 2));
422+ }
423+ }
424+
357425 draw(
358426 cam: Camera,
359427 bodies: Body[],
@@ -412,15 +480,17 @@ export class View {
412480 }
413481 this.marker.visible = marker !== null;
414482 if (marker) {
415- // Snap to the rendered cell grid, or a one-cell marker lands between four.
416- const snap = (v: number, c: number) => c + (Math.floor((v - c) / wpc) + 0.5) * wpc;
417- this.marker.position.set(snap(marker.x, cam.x), snap(marker.y, cam.y), 0.5);
483+ this.marker.position.set(snapCell(marker.x, cam.x, wpc), snapCell(marker.y, cam.y, wpc), 0.5);
418484 }
485+ this.fuel(ships.find((s) => s.id === ownId), performance.now() / 1000);
419486
420487 this.camera.position.set(cam.x, cam.y, 10);
421488 this.renderer.setRenderTarget(this.rt);
422489 this.renderer.clear();
423490 this.renderer.render(this.scene, this.camera);
491+ this.renderer.autoClear = false; // the HUD draws over the world, cell for cell
492+ this.renderer.render(this.hud, this.hudCam);
493+ this.renderer.autoClear = true;
424494 this.renderer.setRenderTarget(null);
425495 this.renderer.render(this.quad, new THREE.Camera());
426496 }
server/main.go+35-14
@@ -56,6 +56,9 @@ const (
5656 maxTier = 2 // a piece can be upgraded twice
5757 yardOre = 3 // ore a shipyard takes for one service
5858 yardGap = 1.0 // seconds between services, so a full line drains visibly
59+
60+ fuelPer = 900.0 // world units of travel one unit of fuel buys
61+ refuel = 1.0 // fuel a second a docked shipyard puts back in the tank
5962 )
6063
6164 // A hull is a graph of pieces placed relative to the ship. Piece ids are unique
@@ -117,15 +120,16 @@ type body struct {
117120 }
118121
119122 type player struct {
120- ID int `json:"id"`
121- Name string `json:"name"`
122- X float64 `json:"x"`
123- Y float64 `json:"y"`
124- H float64 `json:"h"`
125- TX float64 `json:"tx"`
126- TY float64 `json:"ty"`
127- Pieces []piece `json:"pieces"`
128- Fuel float64 `json:"fuel"` // capacity, summed from the hull every tick
123+ ID int `json:"id"`
124+ Name string `json:"name"`
125+ X float64 `json:"x"`
126+ Y float64 `json:"y"`
127+ H float64 `json:"h"`
128+ TX float64 `json:"tx"`
129+ TY float64 `json:"ty"`
130+ Pieces []piece `json:"pieces"`
131+ Fuel float64 `json:"fuel"` // what is in the tank, spent by flying
132+ FuelMax float64 `json:"fuelmax"` // capacity, summed from the hull every tick
129133
130134 vx, vy float64
131135 orbit int // body the ship is anchored to, 0 = none
@@ -234,6 +238,8 @@ func (h *hub) handle(w http.ResponseWriter, r *http.Request) {
234238 c := &client{ws: ws, p: &player{ID: h.nextID, X: spawnX, Y: spawnY, TX: spawnX, TY: spawnY}}
235239 c.p.Name = "P" + strconv.Itoa(c.p.ID)
236240 c.p.Pieces = []piece{h.fitted("triangle", 0)} // every run starts from one triangle
241+ c.p.FuelMax = c.p.capacity()
242+ c.p.Fuel = c.p.FuelMax
237243 h.clients[c] = true
238244 h.mu.Unlock()
239245
@@ -369,7 +375,7 @@ func (p *player) docked() bool {
369375
370376 // Fuel capacity is summed from the hull: every piece carries a little and the
371377 // star carries most of it, so range is a decision about what you bolt on.
372-func (p *player) fuel() float64 {
378+func (p *player) capacity() float64 {
373379 f := 0.0
374380 for _, q := range p.Pieces {
375381 _, u := stats(q.Kind, q.Tier)
@@ -378,6 +384,19 @@ func (p *player) fuel() float64 {
378384 return f
379385 }
380386
387+// Fuel is spent by the distance flown, so a stopped ship spends nothing, and a
388+// ship settled in orbit is carried by the body for free. A docked shipyard fills
389+// the tank back up for free.
390+func (h *hub) drive(p *player, dt float64) {
391+ if p.orbit != 0 && p.docked() {
392+ if b := h.body(p.orbit); b != nil && b.Kind == "shipyard" {
393+ p.Fuel = math.Min(p.FuelMax, p.Fuel+refuel*dt)
394+ }
395+ return
396+ }
397+ p.Fuel = math.Max(0, p.Fuel-math.Hypot(p.vx, p.vy)*dt/fuelPer)
398+}
399+
381400 // A shipyard services one load of ore at a time: three ore patch the whole hull
382401 // up, and once nothing is damaged the load buys a tier on a random piece that can
383402 // still take one. A whole, fully upgraded ship has nothing to buy, so it keeps
@@ -547,7 +566,8 @@ func (h *hub) respawn(p *player) *player {
547566 q := &player{ID: h.nextID, Name: p.Name, // the callsign outlives the ship
548567 X: spawnX, Y: spawnY, TX: spawnX, TY: spawnY}
549568 q.Pieces = []piece{h.fitted("triangle", 0)} // every life starts from one triangle
550- q.Fuel = q.fuel()
569+ q.FuelMax = q.capacity()
570+ q.Fuel = q.FuelMax
551571 return q
552572 }
553573
@@ -645,7 +665,8 @@ func (h *hub) step(dt float64) {
645665 p.steer(dt)
646666 h.burn(p, dt)
647667 h.haul(p)
648- p.Fuel = p.fuel()
668+ p.FuelMax = p.capacity()
669+ h.drive(p, dt)
649670 if b := h.body(p.orbit); b != nil && b.Kind == "shipyard" && p.docked() {
650671 h.yard(p, dt)
651672 }
@@ -654,8 +675,8 @@ func (h *hub) step(dt float64) {
654675 h.onLine(o, p, float64(i+1))
655676 }
656677 }
657- if p.Pieces[0].HP == 0 {
658- c.p = h.respawn(p) // the root piece is the run itself
678+ if p.Pieces[0].HP == 0 || p.Fuel == 0 {
679+ c.p = h.respawn(p) // the root piece is the run itself, and so is the tank
659680 }
660681 }
661682 }