xonecas.ioDon't click! Sean Caetano Martin Sign in
space-browser / client / src / view / index.ts 357 lines14.2 kB Raw
1// The renderer: one render target at one texel per character cell, then the
2// fullscreen pass that turns it into glyphs. It draws what it is handed and keeps
3// only the meshes that belong to an id, so a piece keeps its mesh for its whole life.
4import * as THREE from 'three';
5import { hostile, toWorld, type Body, type Kind, type Loose, type Ore, type Ship, type Shot, type System } from '../sim';
6import { barrenMesh, shipyardMesh, starMesh } from './bodies';
7import { Galaxy } from './galaxy';
8import { CELL, CELL_WORLD, snapCell } from './grid';
9import { FRAG, GLYPHS, PALETTE, VERT, lum, paletteTexture, textAtlas } from './ink';
10import { crosshair, reticle, TONE } from './marks';
11import { oreChunk, paint, piece, shade, type Part, type Role, type Wear } from './pieces';
12import { free, plate } from './shapes';
13
14export { CELL, CELL_WORLD, GALAXY_MAX, GALAXY_MIN, ZOOM_MAX, ZOOM_MIN } from './grid';
15export { TONE } from './marks';
16export { PIECE_R } from './shapes';
17
18const SHOT_LEN = 13; // world units of laser line behind a round
19const SHOT_W = 1.6; // world units thick: one bright cell wide
20const FUEL_CELLS = 12; // the fuel gauge is this many cells wide at any zoom
21const FUEL_WORD = 'FUEL'; // a word, not glyphs: letters are spelled out per cell
22const MAP_WORD = '[M]AP'; // the hint that there is a second scene, under the bar
23
24export type Camera = { x: number; y: number; zoom: number };
25export class View {
26  private renderer: THREE.WebGLRenderer;
27  private scene = new THREE.Scene();
28  private camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0.1, 100);
29  private rt: THREE.WebGLRenderTarget;
30  private pass: THREE.ShaderMaterial;
31  private quad = new THREE.Scene();
32  private pieceMeshes = new Map<number, THREE.Group>();
33  private oreMeshes = new Map<number, THREE.Group>();
34  private shotMeshes = new Map<number, Part>();
35  private bodyMeshes = new Map<number, THREE.Group>();
36  private marker = crosshair();
37  private cursor = reticle();
38  private hud = new THREE.Scene();
39  private hudCam = new THREE.OrthographicCamera(-1, 1, 1, -1, 0.1, 100);
40  private galaxy = new Galaxy();
41  private fuelBar = new THREE.Group();
42  private fuelCells: Part[] = [];
43  private cols = 0;
44  private rows = 0;
45
46  constructor(private canvas: HTMLCanvasElement) {
47    THREE.ColorManagement.enabled = false;
48    this.renderer = new THREE.WebGLRenderer({ canvas, antialias: false });
49    this.renderer.outputColorSpace = THREE.LinearSRGBColorSpace;
50    this.scene.add(this.marker);
51    // The fuel gauge is geometry in a HUD layer, not a page overlay: it is built
52    // from the same cells as everything else, so it reads as part of the game,
53    // and it is measured in cells rather than in the world, so flying cannot make
54    // it hop from one cell to the next.
55    this.hudCam.position.z = 10;
56    this.hud.add(this.fuelBar);
57    this.cursor.visible = false;
58    this.hud.add(this.cursor);
59    for (let i = 0; i < FUEL_CELLS; i++) {
60      const m = plate(1, 1, 1);
61      this.fuelCells.push(m);
62      this.fuelBar.add(m);
63    }
64    this.rt = new THREE.WebGLRenderTarget(1, 1, {
65      depthBuffer: false,
66      stencilBuffer: false,
67      minFilter: THREE.LinearFilter,
68      magFilter: THREE.LinearFilter,
69    });
70    this.pass = new THREE.ShaderMaterial({
71      vertexShader: VERT,
72      fragmentShader: FRAG,
73      uniforms: {
74        uScene: { value: this.rt.texture },
75        uAtlas: { value: textAtlas(GLYPHS) },
76        uPalette: { value: paletteTexture() },
77        uBg: { value: new THREE.Color(PALETTE[0]) },
78        uCells: { value: new THREE.Vector2() },
79        uCellPx: { value: CELL },
80        uWord: { value: textAtlas(FUEL_WORD) },
81        uWordCell: { value: new THREE.Vector4() },
82        uWordCol: { value: new THREE.Color(PALETTE[5]) },
83        uWord2: { value: textAtlas(MAP_WORD) },
84        uWord2Cell: { value: new THREE.Vector4() },
85        uWord2Col: { value: new THREE.Color(PALETTE[4]) },
86      },
87    });
88    const quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), this.pass);
89    quad.frustumCulled = false;
90    this.quad.add(quad);
91    this.resize();
92  }
93
94  // Built once: a body keeps an identity for the whole run, only its place moves.
95  // The mesh is rebuilt if that identity ever changes: a galaxy is generated per
96  // server boot, and a client that stays connected through a restart must not keep
97  // drawing the old planet under the new one.
98  private bodies(bs: Body[], t: number): void {
99    const seen = new Set<number>();
100    for (const b of bs) {
101      seen.add(b.id);
102      let m = this.bodyMeshes.get(b.id);
103      if (m && (m.userData.kind !== b.kind || m.userData.r !== b.r)) {
104        free(m);
105        this.scene.remove(m);
106        this.bodyMeshes.delete(b.id);
107        m = undefined;
108      }
109      if (!m) {
110        m = b.kind === 'star' ? starMesh(b.r) : b.kind === 'shipyard' ? shipyardMesh(b.r) : barrenMesh(b.r);
111        m.position.z = -1;
112        m.userData.spin = b.kind === 'star' ? 0.08 : 0.15; // slow enough to read as alive
113        m.userData.kind = b.kind;
114        m.userData.r = b.r;
115        this.scene.add(m);
116        this.bodyMeshes.set(b.id, m);
117      }
118      m.position.set(b.x, b.y, -1);
119      m.rotation.z = t * m.userData.spin;
120    }
121    for (const [id, m] of this.bodyMeshes) {
122      if (seen.has(id)) continue;
123      free(m);
124      this.scene.remove(m);
125      this.bodyMeshes.delete(id);
126    }
127  }
128
129  resize(): void {
130    // Whole cells only: the canvas, the frustum and the glyph grid must describe
131    // the same rectangle, or world positions land half a cell off their glyph.
132    const dpr = Math.min(devicePixelRatio, 2);
133    this.cols = Math.max(1, Math.floor(innerWidth / CELL));
134    this.rows = Math.max(1, Math.floor(innerHeight / CELL));
135    const w = this.cols * CELL;
136    const h = this.rows * CELL;
137    this.renderer.setPixelRatio(dpr);
138    this.renderer.setSize(w, h, false);
139    this.canvas.style.width = `${w}px`;
140    this.canvas.style.height = `${h}px`;
141    this.rt.setSize(this.cols, this.rows);
142    this.pass.uniforms.uCells.value.set(this.cols, this.rows);
143    // One HUD unit is one cell, so a plate of size 1 covers exactly one glyph.
144    this.hudCam.left = -this.cols / 2;
145    this.hudCam.right = this.cols / 2;
146    this.hudCam.top = this.rows / 2;
147    this.hudCam.bottom = -this.rows / 2;
148    this.hudCam.updateProjectionMatrix();
149    this.pass.uniforms.uCellPx.value = CELL * dpr;
150  }
151
152  // One mesh per piece, whether it is bolted to a hull or drifting loose: ids are
153  // unique across the world, so a torn-off piece stays the same mesh.
154  private place(
155    id: number,
156    kind: Kind,
157    role: Role,
158    x: number,
159    y: number,
160    h: number,
161    w: Wear,
162    hostile: boolean,
163    seen: Set<number>,
164  ): void {
165    seen.add(id);
166    let g = this.pieceMeshes.get(id);
167    if (!g) {
168      g = piece(kind);
169      this.pieceMeshes.set(id, g);
170      this.scene.add(g);
171    }
172    paint(g, role, w, hostile);
173    g.position.set(x, y, 0);
174    g.rotation.z = h;
175  }
176
177  // The pointer, in cells from the top left corner: one cell is one glyph, so the
178  // mark sits on the cell the click will resolve to and nowhere between them. The
179  // tone says what that cell holds.
180  setPointer(cx: number | null, cy = 0, tone: THREE.Color = TONE.space): void {
181    this.cursor.visible = cx !== null;
182    if (cx === null) return;
183    this.cursor.position.set(cx - this.cols / 2 + 0.5, this.rows / 2 - cy - 0.5, 1);
184    for (const p of this.cursor.children) (p as Part).material.color.copy(tone);
185  }
186
187  // The fuel gauge is a row of cells two rows off the bottom of the screen, in a
188  // layer that only knows about cells. Gold while there is plenty, and a red pulse
189  // that quickens as the tank empties. To its right, the map hint, which is a
190  // reminder of a control and not a control of its own.
191  private fuel(own: Ship | undefined, t: number, hint = true): void {
192    this.fuelBar.visible = !!own && own.fuelmax > 0;
193    this.pass.uniforms.uWordCell.value.set(0, 0, 0, 0); // no tank, no word
194    this.pass.uniforms.uWord2Cell.value.set(0, 0, 0, 0);
195    if (!own || own.fuelmax <= 0) return;
196    const start = Math.floor((this.cols - FUEL_CELLS) / 2);
197    const ratio = Math.max(0, Math.min(1, own.fuel / own.fuelmax));
198    const lit = Math.ceil(ratio * FUEL_CELLS);
199    const low = ratio <= 0.25;
200    // The pulse never dims a lit cell into the same glyph band as the empty
201    // track, or the gauge would look shorter than it is while it warns.
202    const blink = 0.45 + 0.55 * (0.5 + 0.5 * Math.sin(t * (6 + 120 * (0.25 - ratio))));
203    // A cell t is centred on t+0.5 measured from the edge, so this lands on glyphs.
204    const x = start - this.cols / 2 + 0.5;
205    const y = 2 - this.rows / 2 + 0.5;
206    // The label sits on the same row, one cell clear of the bar, and the hint sits
207    // one cell clear of the bar's other end.
208    const w = Math.max(0, start - 1 - FUEL_WORD.length);
209    this.pass.uniforms.uWordCell.value.set(w, 2, FUEL_WORD.length, 1);
210    if (hint) {
211      const h = Math.min(start + FUEL_CELLS + 1, this.cols - MAP_WORD.length);
212      this.pass.uniforms.uWord2Cell.value.set(h, 2, MAP_WORD.length, 1);
213    }
214    for (let i = 0; i < FUEL_CELLS; i++) {
215      const m = this.fuelCells[i];
216      m.position.set(x + i, y, 0);
217      m.scale.set(0.85, 0.85, 1);
218      m.material.color.copy(i < lit ? lum(low ? blink : 1, low ? 14 : 6) : lum(0.22, 2));
219    }
220  }
221
222  draw(
223    cam: Camera,
224    bodies: Body[],
225    ships: Ship[],
226    ownId: number,
227    shots: Shot[],
228    loose: Loose[],
229    ore: Ore[],
230    marker: { x: number; y: number } | null,
231  ): void {
232    // Zoom is world units per character cell: the raster keeps one texel per
233    // cell, so zooming only changes how much world a cell covers.
234    const wpc = this.frame(cam);
235    // Bodies sit behind the ships: the server says where, we only draw them.
236    this.bodies(bodies, performance.now() / 1000);
237
238    const seen = new Set<number>();
239    const me = ships.find((s) => s.id === ownId);
240    for (const s of ships) {
241      const role: Role = s.id === ownId ? 'own' : s.side === 'rogue' ? 'rogue' : s.ai ? 'ai' : 'other';
242      // A ship is an enemy by the server's own rule: a rogue always, anyone else
243      // the moment one of the two has declared it.
244      const enemy = hostile(me, s);
245      for (const p of s.pieces) {
246        const w = toWorld(s, p);
247        this.place(p.id, p.kind, role, w.x, w.y, s.h, p, enemy, seen);
248      }
249    }
250    for (const l of loose) this.place(l.id, l.kind, 'loose', l.x, l.y, l.h, l, false, seen);
251    for (const [id, g] of this.pieceMeshes) {
252      if (seen.has(id)) continue;
253      free(g);
254      this.scene.remove(g);
255      this.pieceMeshes.delete(id);
256    }
257    // Ore is its own thing: not a piece, so it never snaps onto a hull. Towed ore
258    // lights up like a hull so a full line reads at a glance.
259    const oreSeen = new Set<number>();
260    for (const o of ore) {
261      oreSeen.add(o.id);
262      let g = this.oreMeshes.get(o.id);
263      if (!g) {
264        g = oreChunk();
265        this.oreMeshes.set(o.id, g);
266        this.scene.add(g);
267      }
268      shade(g, o.towed ? 'towed' : 'ore');
269      g.position.set(o.x, o.y, 0);
270      g.rotation.z = o.h;
271    }
272    for (const [id, g] of this.oreMeshes) {
273      if (oreSeen.has(id)) continue;
274      free(g);
275      this.scene.remove(g);
276      this.oreMeshes.delete(id);
277    }
278    // A round is a laser line lying along its heading, so a dodged shot is read as
279    // a line passing by the hull rather than a dot that vanished. It is never eased:
280    // a round has to be where the server says or it cannot be trusted to dodge.
281    const shotSeen = new Set<number>();
282    for (const s of shots) {
283      shotSeen.add(s.id);
284      let m = this.shotMeshes.get(s.id);
285      if (!m) {
286        m = plate(SHOT_LEN, SHOT_W, 1);
287        m.material.color.copy(lum(1, 7));
288        m.renderOrder = 1;
289        this.shotMeshes.set(s.id, m);
290        this.scene.add(m);
291      }
292      // One cell wide at every zoom, like every other thing that is a mark rather
293      // than a body: at the far zoom a world-sized line would be a dim smudge.
294      m.scale.set(1, wpc / SHOT_W, 1);
295      m.position.set(s.x - Math.cos(s.h) * SHOT_LEN * 0.5, s.y - Math.sin(s.h) * SHOT_LEN * 0.5, 0);
296      m.rotation.z = s.h;
297    }
298    for (const [id, m] of this.shotMeshes) {
299      if (shotSeen.has(id)) continue;
300      free(m);
301      this.scene.remove(m);
302      this.shotMeshes.delete(id);
303    }
304    this.marker.visible = marker !== null;
305    if (marker) {
306      // The marker is one cell per plate, so it is scaled into cells and snapped to
307      // the cell it is on, exactly like the pointer ring.
308      this.marker.scale.setScalar(wpc);
309      this.marker.position.set(
310        snapCell(marker.x, cam.x, wpc, this.cols),
311        snapCell(marker.y, cam.y, wpc, this.rows, -1),
312        0.5,
313      );
314    }
315    this.fuel(ships.find((s) => s.id === ownId), performance.now() / 1000);
316
317    this.present(this.scene);
318  }
319
320  // Scene 2: the map. Nothing of local space is drawn: at a hundred world units to
321  // the cell a hull, an ore or a round is not a glyph, it is noise.
322  drawGalaxy(cam: Camera, systems: System[], ships: Ship[], ownId: number): void {
323    const wpc = this.frame(cam);
324    this.galaxy.show(cam, systems, ships, ownId, wpc, this.cols, this.rows);
325    // No map hint on the map itself: you are already there.
326    this.fuel(ships.find((s) => s.id === ownId), performance.now() / 1000, false);
327    this.present(this.galaxy.scene);
328  }
329
330  // The frustum is one rectangle of whole cells in either scene: only how much
331  // world a cell covers changes.
332  private frame(cam: Camera): number {
333    const wpc = CELL_WORLD / cam.zoom;
334    const hw = (this.cols / 2) * wpc;
335    const hh = (this.rows / 2) * wpc;
336    this.camera.left = -hw;
337    this.camera.right = hw;
338    this.camera.top = hh;
339    this.camera.bottom = -hh;
340    this.camera.updateProjectionMatrix();
341    this.camera.position.set(cam.x, cam.y, 10);
342    return wpc;
343  }
344
345  // Down to one texel per cell, the HUD over it, then the pass that turns every
346  // texel into a glyph. Both scenes end here.
347  private present(scene: THREE.Scene): void {
348    this.renderer.setRenderTarget(this.rt);
349    this.renderer.clear();
350    this.renderer.render(scene, this.camera);
351    this.renderer.autoClear = false; // the HUD draws over the world, cell for cell
352    this.renderer.render(this.hud, this.hudCam);
353    this.renderer.autoClear = true;
354    this.renderer.setRenderTarget(null);
355    this.renderer.render(this.quad, new THREE.Camera());
356  }
357}