space-browser / commits / e23fd65
fix: persist fog of war
@@ -94,7 +94,6 @@ const FOG_FRAG = /* glsl */ `
9494 uniform sampler2D tFog;
9595 uniform float uRadius;
9696 uniform float uTime;
97-uniform float uGrain;
9897 uniform vec3 uMist;
9998 varying vec2 vWorld;
10099 float hash(vec2 p) {
@@ -110,15 +109,14 @@ float noise(vec2 p) {
110109 void main() {
111110 float unknown = texture2D(tFog, vWorld / (2.0 * uRadius) + 0.5).r;
112111 if (unknown < 0.01) discard;
113- // Three glyph-locked octaves: lobes of cloud, puffs inside them and grain,
114- // so the fog reads as drifting vapour at any zoom.
115- vec2 fine = vec2(uTime * 0.10, uTime * -0.07);
116- float lobe = noise(vWorld * uGrain * 0.28 + fine * 0.2);
117- float puff = noise(vWorld * uGrain + fine);
118- float grain = noise(vWorld * uGrain * 3.2 - fine * 2.0);
119- float n = lobe * 0.30 + puff * 0.50 + grain * 0.20;
120- float a = unknown * smoothstep(0.34, 0.60, lobe) * smoothstep(0.40, 0.68, n) * 0.85;
121- a *= 0.85 + 0.15 * sin(uTime * 0.3 + n * 8.0);
112+ // Two octaves sized in world units, so the cloud keeps its place at every
113+ // zoom and only the slow drift moves it. Density rides on a base veil, so
114+ // thin spots still hide space instead of punching holes in the layer.
115+ vec2 drift = vec2(uTime * 120.0, uTime * -90.0);
116+ float lobe = noise((vWorld + drift) * 0.000025);
117+ float puff = noise((vWorld - drift * 0.6) * 0.00007);
118+ float n = lobe * 0.62 + puff * 0.38;
119+ float a = unknown * mix(0.30, 0.95, smoothstep(0.25, 0.75, n));
122120 if (a < 0.01) discard;
123121 gl_FragColor = vec4(uMist, a);
124122 }
@@ -281,7 +279,6 @@ export class Engine {
281279 private fogData: Uint8Array<ArrayBuffer>;
282280 private fogMat: THREE.ShaderMaterial;
283281 private pointMats: THREE.ShaderMaterial[] = [];
284- private lit = new Set<string>();
285282 private projGeom = new THREE.BufferGeometry();
286283 private projPos: Float32Array;
287284 private projCol: Float32Array;
@@ -355,7 +352,6 @@ export class Engine {
355352 tFog: { value: this.fogTex },
356353 uRadius: { value: cfg.galaxy.radius },
357354 uTime: { value: 0 },
358- uGrain: { value: 1 / 8 },
359355 uMist: { value: new THREE.Color(FOG_MIST) },
360356 },
361357 vertexShader: FOG_VERT,
@@ -365,7 +361,7 @@ export class Engine {
365361 depthWrite: false,
366362 });
367363 const fog = new THREE.Mesh(
368- new THREE.PlaneGeometry(cfg.galaxy.radius * 2, cfg.galaxy.radius * 2),
364+ new THREE.PlaneGeometry(cfg.galaxy.radius * 3, cfg.galaxy.radius * 3),
369365 this.fogMat,
370366 );
371367 fog.position.z = -4;
@@ -529,28 +525,36 @@ export class Engine {
529525 col[i * 3 + 2] = c.b;
530526 shape[i] = KIND_SHAPE[p.kind] ?? 0;
531527 phase[i] = (i * 2.399) % 6.28;
532- if (!this.lit.has(p.id)) {
533- this.lit.add(p.id);
534- this.revealFog(p);
535- }
536528 });
537529 this.poiGeom.setAttribute("position", new THREE.BufferAttribute(pos, 3));
538530 this.poiGeom.setAttribute("aSize", new THREE.BufferAttribute(size, 1));
539531 this.poiGeom.setAttribute("aColor", new THREE.BufferAttribute(col, 3));
540532 this.poiGeom.setAttribute("aShape", new THREE.BufferAttribute(shape, 1));
541533 this.poiGeom.setAttribute("aPhase", new THREE.BufferAttribute(phase, 1));
534+ }
535+
536+ // setFog loads the shared explored-space snapshot: one bit per texel, 1
537+ // where space is still unknown.
538+ setFog(bits: string) {
539+ const raw = atob(bits);
540+ for (let i = 0; i < FOG_TEXELS * FOG_TEXELS; i++) {
541+ this.fogData[i * 4] = (raw.charCodeAt(i >> 3) >> (i & 7)) & 1 ? 255 : 0;
542+ }
543+ this.fogTex.needsUpdate = true;
544+ }
545+
546+ // revealFog clears a soft disc of the shared fog: the server owns what has
547+ // been explored, every client just paints the discs it announces.
548+ revealFog(x: number, y: number, worldRadius: number) {
549+ this.clearFog(x, y, worldRadius);
542550 this.fogTex.needsUpdate = true;
543551 }
544552
545- // revealFog clears a soft disc of fog around a discovered POI: the fog is
546- // shared, so every player sees the space anyone has already been near. The
547- // disc is twice the discovery range, so a visited system reads as a clear
548- // island in the cloud.
549- private revealFog(p: POI) {
553+ private clearFog(px: number, py: number, worldRadius: number) {
550554 const span = this.cfg.galaxy.radius * 2;
551- const cx = ((p.x + this.cfg.galaxy.radius) / span) * FOG_TEXELS;
552- const cy = ((p.y + this.cfg.galaxy.radius) / span) * FOG_TEXELS;
553- const r = ((this.cfg.galaxy.discoverRange * 2) / span) * FOG_TEXELS;
555+ const cx = ((px + this.cfg.galaxy.radius) / span) * FOG_TEXELS;
556+ const cy = ((py + this.cfg.galaxy.radius) / span) * FOG_TEXELS;
557+ const r = (worldRadius / span) * FOG_TEXELS;
554558 const x0 = Math.max(0, Math.floor(cx - r));
555559 const x1 = Math.min(FOG_TEXELS - 1, Math.ceil(cx + r));
556560 const y0 = Math.max(0, Math.floor(cy - r));
@@ -723,7 +727,6 @@ export class Engine {
723727 m.uniforms.uTime.value = this.time;
724728 }
725729 this.fogMat.uniforms.uTime.value = this.time;
726- this.fogMat.uniforms.uGrain.value = zoom / 8; // cloud grain stays ~8 cells wide
727730
728731 this.renderer.setRenderTarget(this.rt);
729732 this.renderer.clear();
@@ -124,6 +124,10 @@ class Game {
124124 this.pois.clear();
125125 for (const p of m.pois) this.pois.set(p.id, p);
126126 this.syncPOIs();
127+ this.engine.setFog(m.fog);
128+ break;
129+ case "fog":
130+ for (const [x, y, r] of m.reveals) this.engine.revealFog(x, y, r);
127131 break;
128132 case "explore":
129133 for (const p of m.pois) this.pois.set(p.id, p);
@@ -143,8 +143,9 @@ export type ServerMsg =
143143 positionHz: number;
144144 dotsHz: number;
145145 }
146- | { t: "dots"; pois: POI[] }
146+ | { t: "dots"; pois: POI[]; fog: string }
147147 | { t: "explore"; pois: POI[] }
148+ | { t: "fog"; reveals: [number, number, number][] }
148149 | { t: "named"; id: string; name: string; by: string }
149150 | {
150151 t: "pos";
@@ -0,0 +1,67 @@
1+package main
2+
3+import (
4+ "encoding/base64"
5+ "math"
6+)
7+
8+// fogTexels is the resolution of the shared fog mask over the galaxy square.
9+const fogTexels = 1024
10+
11+// fogMask is the shared record of explored space: 0 where space has been seen,
12+// 255 where it is still unknown, one byte per texel. Players paint it as they
13+// fly and every reveal is broadcast, so exploration is shared by everyone.
14+type fogMask []uint8
15+
16+func newFogMask() fogMask {
17+ m := make(fogMask, fogTexels*fogTexels)
18+ for i := range m {
19+ m[i] = 255
20+ }
21+ return m
22+}
23+
24+// reveal clears a soft disc around a world point and reports whether it
25+// changed anything.
26+func (m fogMask) reveal(x, y, worldRadius float64) bool {
27+ span := 2 * config.Galaxy.Radius
28+ cx := (x + config.Galaxy.Radius) / span * fogTexels
29+ cy := (y + config.Galaxy.Radius) / span * fogTexels
30+ r := worldRadius / span * fogTexels
31+ changed := false
32+ x0 := max(0, int(math.Floor(cx-r)))
33+ x1 := min(fogTexels-1, int(math.Ceil(cx+r)))
34+ y0 := max(0, int(math.Floor(cy-r)))
35+ y1 := min(fogTexels-1, int(math.Ceil(cy+r)))
36+ for ty := y0; ty <= y1; ty++ {
37+ for tx := x0; tx <= x1; tx++ {
38+ d := math.Hypot(float64(tx)+0.5-cx, float64(ty)+0.5-cy) / r
39+ v := uint8(255 * math.Min(1, math.Max(0, (d-0.55)/0.45)))
40+ k := ty*fogTexels + tx
41+ if v < m[k] {
42+ m[k] = v
43+ changed = true
44+ }
45+ }
46+ }
47+ return changed
48+}
49+
50+// load replaces the mask with a persisted copy, if the size matches.
51+func (m fogMask) load(b []byte) {
52+ if len(b) == len(m) {
53+ copy(m, b)
54+ }
55+}
56+
57+// packed encodes the mask as one bit per texel, 1 where space is still
58+// unknown, for the snapshot a joining client receives.
59+func (m fogMask) packed() string {
60+ buf := make([]byte, len(m)/8)
61+ for i, v := range m {
62+ if v > 127 {
63+ buf[i/8] |= 1 << (i % 8)
64+ }
65+ }
66+ return base64.StdEncoding.EncodeToString(buf)
67+}
@@ -30,6 +30,7 @@ func openStore(path string) (*Store, error) {
3030 stmts := []string{
3131 `CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)`,
3232 `CREATE TABLE IF NOT EXISTS poi (id TEXT PRIMARY KEY, name TEXT NOT NULL DEFAULT '', named_by TEXT NOT NULL DEFAULT '', explored INTEGER NOT NULL DEFAULT 0)`,
33+ `CREATE TABLE IF NOT EXISTS fog (id INTEGER PRIMARY KEY, mask BLOB NOT NULL)`,
3334 }
3435 for _, q := range stmts {
3536 if _, err := db.Exec(q); err != nil {
@@ -77,8 +78,10 @@ func (s *Store) checkLayout() error {
7778 if v, ok := s.meta("layout"); ok && v == layoutVersion {
7879 return nil
7980 }
80- if _, err := s.db.Exec(`DELETE FROM poi`); err != nil {
81- return err
81+ for _, q := range []string{`DELETE FROM poi`, `DELETE FROM fog`} {
82+ if _, err := s.db.Exec(q); err != nil {
83+ return err
84+ }
8285 }
8386 return s.setMeta("layout", layoutVersion)
8487 }
@@ -103,6 +106,19 @@ func (s *Store) loadPOIs() (map[string]poiRow, error) {
103106 return out, rows.Err()
104107 }
105108
109+// loadFog returns the persisted fog mask, if there is one.
110+func (s *Store) loadFog() ([]byte, error) {
111+ var b []byte
112+ err := s.db.QueryRow(`SELECT mask FROM fog WHERE id = 0`).Scan(&b)
113+ return b, err
114+}
115+
116+func (s *Store) saveFog(m []byte) error {
117+ _, err := s.db.Exec(`INSERT INTO fog(id, mask) VALUES(0, ?)
118+ ON CONFLICT(id) DO UPDATE SET mask = excluded.mask`, m)
119+ return err
120+}
121+
106122 func (s *Store) savePOI(p *POI) error {
107123 explored := 0
108124 if p.Explored {
@@ -127,6 +127,16 @@ func (w *World) broadcastDots() {
127127 }
128128 w.newPOIs = nil
129129 }
130+ if len(w.fogOut) > 0 {
131+ reveals := make([]any, 0, len(w.fogOut))
132+ for _, r := range w.fogOut {
133+ reveals = append(reveals, []float64{r.X, r.Y, r.R})
134+ }
135+ for c := range w.clients {
136+ c.push(map[string]any{"t": "fog", "reveals": reveals})
137+ }
138+ w.fogOut = nil
139+ }
130140 for _, ev := range w.named {
131141 for c := range w.clients {
132142 c.push(map[string]any{"t": "named", "id": ev.ID, "name": ev.Name, "by": ev.By})
@@ -135,7 +145,8 @@ func (w *World) broadcastDots() {
135145 w.named = nil
136146 }
137147
138-// sendDots sends the whole already-explored galaxy to a joining client.
148+// sendDots sends the whole already-explored galaxy, and the shared fog mask,
149+// to a joining client.
139150 func (w *World) sendDots(c *Client) {
140151 pois := []any{}
141152 for _, poi := range w.galaxy.POIs {
@@ -143,7 +154,7 @@ func (w *World) sendDots(c *Client) {
143154 pois = append(pois, poi)
144155 }
145156 }
146- c.push(map[string]any{"t": "dots", "pois": pois})
157+ c.push(map[string]any{"t": "dots", "pois": pois, "fog": w.fog.packed()})
147158 }
148159
149160 func (w *World) sendSelf(p *Player) {
@@ -2,6 +2,7 @@ package main
22
33 import (
44 "fmt"
5+ "log"
56 "math"
67 "sync"
78 "time"
@@ -41,6 +42,8 @@ type Player struct {
4142 Antennas map[string]bool
4243 Combat float64 // world time until which the player counts as in combat
4344 Stats RunStats
45+ fogAt Vec2 // last fog reveal, so flight paints a trail
46+ fogInit bool
4447
4548 client *Client
4649 disconnectedAt float64
@@ -95,6 +98,9 @@ type World struct {
9598 spawned int
9699 rng *rng
97100 newPOIs []*POI
101+ fog fogMask
102+ fogOut []fogReveal
103+ fogDirty bool
98104 named []namedEvent
99105 radioOut []radioEvent
100106 }
@@ -108,6 +114,11 @@ type radioEvent struct {
108114 Pos Vec2
109115 }
110116
117+// fogReveal is one cleared disc of the shared fog of war.
118+type fogReveal struct {
119+ X, Y, R float64
120+}
121+
111122 func newWorld(store *Store, g *Galaxy) *World {
112123 w := &World{
113124 galaxy: g,
@@ -119,6 +130,18 @@ func newWorld(store *Store, g *Galaxy) *World {
119130 clients: map[*Client]bool{},
120131 cmd: make(chan func(), 1024),
121132 rng: newRNG(g.Seed ^ 0x1234),
133+ fog: newFogMask(),
134+ }
135+ if w.store != nil {
136+ if blob, err := w.store.loadFog(); err == nil {
137+ w.fog.load(blob)
138+ }
139+ }
140+ // bodies discovered since the last mask flush still need their island
141+ for _, poi := range g.POIs {
142+ if poi.Explored {
143+ w.fog.reveal(poi.Pos().X, poi.Pos().Y, config.Galaxy.DiscoverRange*2)
144+ }
122145 }
123146 return w
124147 }
@@ -138,6 +161,7 @@ func (w *World) run() {
138161 go w.loop(tickDt, w.tickOnce)
139162 go w.loop(posDt, w.broadcastPositions)
140163 go w.loop(dotsDt, w.broadcastDots)
164+ go w.loop(15*time.Second, w.flushFog)
141165 }
142166
143167 func (w *World) loop(d time.Duration, fn func()) {
@@ -180,6 +204,29 @@ func (w *World) step(dt float64) {
180204 w.reapPlayers()
181205 }
182206
207+// clearFog lifts the shared fog mask and queues the disc for broadcast.
208+func (w *World) clearFog(pos Vec2, radius float64) {
209+ if w.fog.reveal(pos.X, pos.Y, radius) {
210+ w.fogOut = append(w.fogOut, fogReveal{pos.X, pos.Y, radius})
211+ w.fogDirty = true
212+ }
213+}
214+
215+// flushFog writes the shared mask back to sqlite, so exploration survives a
216+// restart the same way discovered bodies do.
217+func (w *World) flushFog() {
218+ w.mu.Lock()
219+ defer w.mu.Unlock()
220+ if !w.fogDirty || w.store == nil {
221+ return
222+ }
223+ if err := w.store.saveFog(w.fog); err != nil {
224+ log.Printf("save fog: %v", err)
225+ return
226+ }
227+ w.fogDirty = false
228+}
229+
183230 // discovery lifts the shared fog of war: any POI a player gets near becomes
184231 // explored for everyone. Fleets are spotted from further out than the bodies
185232 // they patrol, so a rogue fleet shows up before it starts shooting.
@@ -199,10 +246,18 @@ func (w *World) discovery() {
199246 }
200247 poi.Explored = true
201248 w.newPOIs = append(w.newPOIs, poi)
249+ w.clearFog(poi.Pos(), config.Galaxy.DiscoverRange*2)
202250 if w.store != nil {
203251 _ = w.store.savePOI(poi)
204252 }
205253 }
254+ // flight paints the fog too: every player clears the space it flies
255+ // through, and everyone sees it.
256+ if !p.fogInit || p.Pos.Dist(p.fogAt) >= config.Galaxy.DiscoverRange/5 {
257+ p.fogAt = p.Pos
258+ p.fogInit = true
259+ w.clearFog(p.Pos, config.Galaxy.DiscoverRange)
260+ }
206261 for _, poi := range w.galaxy.nearby(p.Pos, orbitSearch()) {
207262 if poi.Kind != kindComms || !inOrbitOf(p, poi) {
208263 continue