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

space-browser / commits / 4b993f2

fix(galaxy gen): fixes to make more galaxy-like

- proper scale
- no overlapping
- galaxy spiralling

xonecas5 weeks ago4b993f2188f23b7cc150d953a1588c8cdc9efe83parent 182a7c08 files changed

client/src/config.ts+24-4
@@ -10,14 +10,34 @@ export interface GameConfig {
1010 seedFallback: number;
1111 radius: number;
1212 starCount: number;
13- centerDensityPower: number;
1413 starSpacing: { min: number; max: number };
1514 discoverRange: number;
1615 orbitRange: number;
17- planets: { chance: number; max: number; orbitMin: number; orbitMax: number };
16+ shape: {
17+ discScale: number;
18+ bulgeScale: number;
19+ arms: number;
20+ armPitchDegrees: number;
21+ armWidth: number;
22+ armStrength: number;
23+ armCompression: number;
24+ bulgeWeight: number;
25+ systemRadiusFraction: number;
26+ };
1827 starRadius: { min: number; max: number };
19- planetRadius: { min: number; max: number };
20- extras: {
28+ planet: {
29+ radius: { min: number; max: number };
30+ baseCount: number;
31+ coreBonus: number;
32+ orbitMinFactor: number;
33+ orbitMaxFactor: number;
34+ };
35+ poi: {
36+ radius: { min: number; max: number };
37+ hostOrbitMinFactor: number;
38+ hostOrbitMaxFactor: number;
39+ starOrbitMinFactor: number;
40+ starOrbitMaxFactor: number;
2141 asteroidChance: number;
2242 commsChance: number;
2343 shipyardChance: number;
client/src/engine.ts+77-18
@@ -1,4 +1,5 @@
11 import * as THREE from "three";
2+import type { GameConfig } from "./config";
23 import { buildGlyphAtlas, CELL_H, CELL_W, PAL, RAMP } from "./palette";
34 import type { ItemView, NPCView, PlayerView, POI, ProjView, Shape } from "./protocol";
45
@@ -100,6 +101,50 @@ void main() {
100101 }
101102 `;
102103
104+type GalaxyShape = GameConfig["galaxy"]["shape"];
105+
106+// mulberry32: same seed, same dust, every reload.
107+function seeded(seed: string): () => number {
108+ let a = 2166136261;
109+ for (let i = 0; i < seed.length; i++) {
110+ a = Math.imul(a ^ seed.charCodeAt(i), 16777619);
111+ }
112+ return () => {
113+ a = (a + 0x6d2b79f5) | 0;
114+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
115+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
116+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
117+ };
118+}
119+
120+function wrapPi(a: number): number {
121+ a = (((a + Math.PI) % (2 * Math.PI)) + 2 * Math.PI) % (2 * Math.PI);
122+ return a - Math.PI;
123+}
124+
125+// armTerm is 1 on an arm centreline and falls off between the arms.
126+function armTerm(x: number, y: number, r: number, sh: GalaxyShape, radius: number): number {
127+ const r0 = sh.bulgeScale * radius;
128+ const angle = Math.atan2(y, x);
129+ const pitch = Math.tan((sh.armPitchDegrees * Math.PI) / 180);
130+ let best = 0;
131+ for (let k = 0; k < sh.arms; k++) {
132+ const d = wrapPi(angle - (k * 2 * Math.PI) / sh.arms - Math.log(Math.max(r, r0) / r0) / pitch);
133+ best = Math.max(best, Math.exp(-0.5 * (d / sh.armWidth) ** 2));
134+ }
135+ return best;
136+}
137+
138+// galaxyShape is the same surface density the server bakes its stars from: a
139+// bulge, a disc, and log-spiral arms.
140+function galaxyShape(x: number, y: number, sh: GalaxyShape, radius: number): number {
141+ const r = Math.hypot(x, y);
142+ if (r > radius) return 0;
143+ const disc = Math.exp(-r / (sh.discScale * radius));
144+ const b = r / (sh.bulgeScale * radius);
145+ return disc * (1 + sh.armStrength * armTerm(x, y, r, sh, radius)) + sh.bulgeWeight * Math.exp(-b * b);
146+}
147+
103148 function polyGeom(n: number, rot: number): THREE.BufferGeometry {
104149 const pts: number[] = [];
105150 for (let i = 0; i < n; i++) {
@@ -174,13 +219,15 @@ export class Engine {
174219 private quat = new THREE.Quaternion();
175220 private scale = new THREE.Vector3(1, 1, 1);
176221 private time = 0;
222+ private cfg: GameConfig;
177223
178224 viewWidth = 2000;
179225 viewHeight = 2000;
180226 centerX = 0;
181227 centerY = 0;
182228
183- constructor(canvas: HTMLCanvasElement, galaxyRadius: number) {
229+ constructor(canvas: HTMLCanvasElement, cfg: GameConfig) {
230+ this.cfg = cfg;
184231 THREE.ColorManagement.enabled = false;
185232 this.renderer = new THREE.WebGLRenderer({ canvas, antialias: false, alpha: false });
186233 this.renderer.outputColorSpace = THREE.LinearSRGBColorSpace;
@@ -230,7 +277,7 @@ export class Engine {
230277 this.scene.add(this.poiPoints);
231278
232279 const dustMat = poiMat.clone();
233- this.dust = new THREE.Points(this.buildDust(galaxyRadius), dustMat);
280+ this.dust = new THREE.Points(this.buildDust(cfg.galaxy.seedFallback.toString()), dustMat);
234281 this.dust.frustumCulled = false;
235282 this.scene.add(this.dust);
236283
@@ -268,28 +315,35 @@ export class Engine {
268315 this.resize();
269316 }
270317
271- private buildDust(galaxyRadius: number): THREE.BufferGeometry {
272- const n = 1400;
273- const r = galaxyRadius * 1.15;
318+ // dust fills the disc evenly; its brightness carries the galaxy shape, so
319+ // the spiral and the bulge read as denser glyphs under the fog.
320+ private buildDust(seed: string): THREE.BufferGeometry {
321+ const sh = this.cfg.galaxy.shape;
322+ const radius = this.cfg.galaxy.radius;
323+ const rnd = seeded(seed);
324+ const n = 14000;
325+ const peak = 1 + sh.armStrength + sh.bulgeWeight;
274326 const pos = new Float32Array(n * 3);
275327 const size = new Float32Array(n);
276328 const col = new Float32Array(n * 3);
277329 const shape = new Float32Array(n);
278330 const phase = new Float32Array(n);
279331 const c = new THREE.Color("#2a1d10");
280- for (let i = 0; i < n; i++) {
281- const a = Math.random() * Math.PI * 2;
282- const d = Math.sqrt(Math.random()) * r;
283- pos[i * 3] = Math.cos(a) * d;
284- pos[i * 3 + 1] = Math.sin(a) * d;
285- pos[i * 3 + 2] = -2;
286- size[i] = 3 + Math.random() * 6;
287- const b = 0.25 + Math.random() * 0.6;
288- col[i * 3] = c.r * b;
289- col[i * 3 + 1] = c.g * b;
290- col[i * 3 + 2] = c.b * b;
291- shape[i] = 0;
292- phase[i] = Math.random() * 6.28;
332+ for (let k = 0; k < n; k++) {
333+ const a = rnd() * Math.PI * 2;
334+ const r = radius * Math.sqrt(rnd());
335+ const x = Math.cos(a) * r;
336+ const y = Math.sin(a) * r;
337+ pos[k * 3] = x;
338+ pos[k * 3 + 1] = y;
339+ pos[k * 3 + 2] = -2;
340+ size[k] = 3 + rnd() * 6;
341+ const b = 1.3 + 3.4 * Math.pow(galaxyShape(x, y, sh, radius) / peak, 0.35);
342+ col[k * 3] = c.r * b;
343+ col[k * 3 + 1] = c.g * b;
344+ col[k * 3 + 2] = c.b * b;
345+ shape[k] = 0;
346+ phase[k] = rnd() * 6.28;
293347 }
294348 const g = new THREE.BufferGeometry();
295349 g.setAttribute("position", new THREE.BufferAttribute(pos, 3));
@@ -300,6 +354,11 @@ export class Engine {
300354 return g;
301355 }
302356
357+ setDustSeed(seed: string) {
358+ this.dust.geometry.dispose();
359+ this.dust.geometry = this.buildDust(seed);
360+ }
361+
303362 setPOIs(pois: Iterable<POI>) {
304363 const list = [...pois];
305364 const n = list.length;
client/src/main.ts+2-1
@@ -72,7 +72,7 @@ class Game {
7272
7373 async start() {
7474 this.cfg = await loadConfig();
75- this.engine = new Engine(this.canvas, this.cfg.galaxy.radius);
75+ this.engine = new Engine(this.canvas, this.cfg);
7676 this.camera = new Camera(this.cfg.galaxy.radius);
7777 this.hud.onRadioSend = (t) => this.send({ t: "radio", text: t });
7878 this.hud.onEject = (slot) => this.send({ t: "eject", slot });
@@ -112,6 +112,7 @@ class Game {
112112 onMessage(m: ServerMsg) {
113113 switch (m.t) {
114114 case "welcome":
115+ this.engine.setDustSeed(m.seed);
115116 break;
116117 case "joined":
117118 this.selfId = m.id;
server/config.go+41-23
@@ -18,38 +18,56 @@ type Config struct {
1818 DotsHz int `json:"dotsHz"`
1919 ReconnectSeconds float64 `json:"reconnectSeconds"`
2020 Galaxy struct {
21- SeedFallback uint64 `json:"seedFallback"`
22- Radius float64 `json:"radius"`
23- StarCount int `json:"starCount"`
24- CenterDensityPower float64 `json:"centerDensityPower"`
25- StarSpacing struct {
21+ SeedFallback uint64 `json:"seedFallback"`
22+ Radius float64 `json:"radius"`
23+ StarCount int `json:"starCount"`
24+ StarSpacing struct {
2625 Min float64 `json:"min"`
2726 Max float64 `json:"max"`
2827 } `json:"starSpacing"`
2928 DiscoverRange float64 `json:"discoverRange"`
3029 OrbitRange float64 `json:"orbitRange"`
31- Planets struct {
32- Chance float64 `json:"chance"`
33- Max int `json:"max"`
34- OrbitMin float64 `json:"orbitMin"`
35- OrbitMax float64 `json:"orbitMax"`
36- } `json:"planets"`
30+ Shape struct {
31+ DiscScale float64 `json:"discScale"`
32+ BulgeScale float64 `json:"bulgeScale"`
33+ Arms int `json:"arms"`
34+ ArmPitchDegrees float64 `json:"armPitchDegrees"`
35+ ArmWidth float64 `json:"armWidth"`
36+ ArmStrength float64 `json:"armStrength"`
37+ ArmCompression float64 `json:"armCompression"`
38+ BulgeWeight float64 `json:"bulgeWeight"`
39+ SystemRadiusFraction float64 `json:"systemRadiusFraction"`
40+ } `json:"shape"`
3741 StarRadius struct {
3842 Min float64 `json:"min"`
3943 Max float64 `json:"max"`
4044 } `json:"starRadius"`
41- PlanetRadius struct {
42- Min float64 `json:"min"`
43- Max float64 `json:"max"`
44- } `json:"planetRadius"`
45- Extras struct {
46- AsteroidChance float64 `json:"asteroidChance"`
47- CommsChance float64 `json:"commsChance"`
48- ShipyardChance float64 `json:"shipyardChance"`
49- WreckChance float64 `json:"wreckChance"`
50- FleetChance float64 `json:"fleetChance"`
51- EdgeFade float64 `json:"edgeFade"`
52- } `json:"extras"`
45+ Planet struct {
46+ Radius struct {
47+ Min float64 `json:"min"`
48+ Max float64 `json:"max"`
49+ } `json:"radius"`
50+ BaseCount int `json:"baseCount"`
51+ CoreBonus int `json:"coreBonus"`
52+ OrbitMinFactor float64 `json:"orbitMinFactor"`
53+ OrbitMaxFactor float64 `json:"orbitMaxFactor"`
54+ } `json:"planet"`
55+ POI struct {
56+ Radius struct {
57+ Min float64 `json:"min"`
58+ Max float64 `json:"max"`
59+ } `json:"radius"`
60+ HostOrbitMinFactor float64 `json:"hostOrbitMinFactor"`
61+ HostOrbitMaxFactor float64 `json:"hostOrbitMaxFactor"`
62+ StarOrbitMinFactor float64 `json:"starOrbitMinFactor"`
63+ StarOrbitMaxFactor float64 `json:"starOrbitMaxFactor"`
64+ AsteroidChance float64 `json:"asteroidChance"`
65+ CommsChance float64 `json:"commsChance"`
66+ ShipyardChance float64 `json:"shipyardChance"`
67+ WreckChance float64 `json:"wreckChance"`
68+ FleetChance float64 `json:"fleetChance"`
69+ EdgeFade float64 `json:"edgeFade"`
70+ } `json:"poi"`
5371 } `json:"galaxy"`
5472 Ship struct {
5573 PieceBaseHP float64 `json:"pieceBaseHP"`
server/config/game.json+38-20
@@ -6,34 +6,52 @@
66 "galaxy": {
77 "seedFallback": 11702656774886230293,
88 "radius": 300000,
9- "starCount": 1500,
10- "centerDensityPower": 1.0,
9+ "starCount": 1000,
1110 "starSpacing": {
12- "min": 3000,
13- "max": 15000
11+ "min": 5000,
12+ "max": 9000
1413 },
1514 "discoverRange": 8000,
1615 "orbitRange": 700,
17- "planets": {
18- "chance": 0.7,
19- "max": 8,
20- "orbitMin": 300,
21- "orbitMax": 4000
16+ "shape": {
17+ "discScale": 0.20,
18+ "bulgeScale": 0.04,
19+ "bulgeWeight": 2,
20+ "arms": 2,
21+ "armPitchDegrees": 30,
22+ "armWidth": 0.16,
23+ "armStrength": 25,
24+ "armCompression": 0.65,
25+ "systemRadiusFraction": 0.44
2226 },
2327 "starRadius": {
24- "min": 120,
25- "max": 420
28+ "min": 160,
29+ "max": 340
2630 },
27- "planetRadius": {
28- "min": 30,
29- "max": 120
31+ "planet": {
32+ "radius": {
33+ "min": 45,
34+ "max": 95
35+ },
36+ "baseCount": 3,
37+ "coreBonus": 2,
38+ "orbitMinFactor": 1.7,
39+ "orbitMaxFactor": 0.62
3040 },
31- "extras": {
32- "asteroidChance": 0.5,
33- "commsChance": 0.25,
34- "shipyardChance": 0.2,
35- "wreckChance": 0.35,
36- "fleetChance": 0.3,
41+ "poi": {
42+ "radius": {
43+ "min": 14,
44+ "max": 34
45+ },
46+ "hostOrbitMinFactor": 1.6,
47+ "hostOrbitMaxFactor": 2.6,
48+ "starOrbitMinFactor": 0.68,
49+ "starOrbitMaxFactor": 0.94,
50+ "asteroidChance": 0.6,
51+ "commsChance": 0.35,
52+ "shipyardChance": 0.3,
53+ "wreckChance": 0.45,
54+ "fleetChance": 0.4,
3755 "edgeFade": 0.15
3856 }
3957 },
server/galaxy.go+403-115
@@ -3,6 +3,7 @@ package main
33 import (
44 "fmt"
55 "math"
6+ "sort"
67 )
78
89 const (
@@ -15,10 +16,12 @@ const (
1516 kindFleet = "fleet"
1617 )
1718
18-// POI is a place of interest. Some kinds orbit a star, others are anchors.
19+// POI is a place of interest: a star, a planet, or something in orbit of
20+// either. Sys names the star that owns it, Star its direct parent.
1921 type POI struct {
2022 ID string `json:"id"`
2123 Kind string `json:"kind"`
24+ Sys string `json:"sys,omitempty"` // owning star
2225 X float64 `json:"x"`
2326 Y float64 `json:"y"`
2427 Radius float64 `json:"r"`
@@ -39,22 +42,30 @@ type POI struct {
3942
4043 func (p *POI) Pos() Vec2 { return Vec2{p.X, p.Y} }
4144
42-// orbitAround re-derives world position from the parent star.
43-func (p *POI) orbitAround(star *POI) {
44- p.X = star.X + p.Orbit*math.Cos(p.Angle)
45- p.Y = star.Y + p.Orbit*math.Sin(p.Angle)
45+// orbitAround re-derives world position from the parent body.
46+func (p *POI) orbitAround(parent *POI) {
47+ p.X = parent.X + p.Orbit*math.Cos(p.Angle)
48+ p.Y = parent.Y + p.Orbit*math.Sin(p.Angle)
4649 }
4750
4851 type Galaxy struct {
49- Seed uint64
50- POIs []*POI
51- byID map[string]*POI
52- Stars []*POI
53- Home *POI
52+ Seed uint64
53+ POIs []*POI
54+ byID map[string]*POI
55+ Stars []*POI
56+ Home *POI
57+ counts map[string]int
5458 }
5559
5660 func (g *Galaxy) get(id string) *POI { return g.byID[id] }
5761
62+// nextID mints a stable per-kind id ("planet:7").
63+func (g *Galaxy) nextID(kind string) string {
64+ id := fmt.Sprintf("%s:%d", kind, g.counts[kind])
65+ g.counts[kind]++
66+ return id
67+}
68+
5869 // remove deletes a POI from the galaxy (used when a fleet is destroyed).
5970 func (g *Galaxy) remove(id string) {
6071 p := g.byID[id]
@@ -79,140 +90,417 @@ func (g *Galaxy) add(poi *POI) *POI {
7990 return poi
8091 }
8192
82-// generateGalaxy builds the deterministic shared galaxy. Density decreases
83-// outward from the center so the core is populated and the rim is sparse.
93+// ---- generation ----------------------------------------------------------
94+
95+// poiKinds are the non-star kinds, in placement order.
96+var poiKinds = []string{kindAsteroid, kindComms, kindShipyard, kindWreck, kindFleet}
97+
98+// generateGalaxy builds the deterministic shared galaxy: a spiral disc of star
99+// systems with a dense core. Systems are laid out hierarchically
100+// (star > planets > POIs) and never overlap each other or spill outside their
101+// own system.
84102 func generateGalaxy(seed uint64) *Galaxy {
85103 r := newRNG(seed ^ 0xA5A5A5A5A5A5A5A5)
86- g := &Galaxy{Seed: seed, byID: map[string]*POI{}}
87-
88- radius := config.Galaxy.Radius
89- power := config.Galaxy.CenterDensityPower
90- counts := map[string]int{}
91-
92- for i := 0; i < config.Galaxy.StarCount; i++ {
93- u := r.Float64()
94- dist := radius * math.Pow(u, power)
95- angle := r.Float64() * 2 * math.Pi
96- star := &POI{
97- ID: fmt.Sprintf("star:%d", counts["star"]),
98- Kind: kindStar,
99- X: dist * math.Cos(angle),
100- Y: dist * math.Sin(angle),
101- Radius: r.Range(config.Galaxy.StarRadius.Min, config.Galaxy.StarRadius.Max),
104+ g := &Galaxy{Seed: seed, byID: map[string]*POI{}, counts: map[string]int{}}
105+ stars := g.placeStars(r)
106+ g.Home = nearestToCore(stars)
107+ for _, s := range stars {
108+ g.populate(r, s, s == g.Home)
109+ }
110+ return g
111+}
112+
113+// densityAt is 1 at the core and 0 at the rim; it fades out how rich (and how
114+// dangerous) a region is.
115+func densityAt(x, y float64) float64 {
116+ return 1 - math.Min(1, math.Hypot(x, y)/config.Galaxy.Radius)
117+}
118+
119+// discSpacing grows from the centre to the rim: how far apart systems sit
120+// between the arms.
121+func discSpacing(x, y float64) float64 {
122+ sp := config.Galaxy.StarSpacing
123+ f := math.Min(1, math.Hypot(x, y)/(config.Galaxy.Radius*config.Galaxy.Shape.DiscScale*2))
124+ return sp.Min + (sp.Max-sp.Min)*f
125+}
126+
127+// starSpacing is the smallest centre-to-centre distance the local density
128+// allows: systems crowd the core, thin out toward the rim, and pack tighter
129+// along the spiral arms, which is what makes the arms dense enough to see.
130+func starSpacing(x, y float64) float64 {
131+ sh := config.Galaxy.Shape
132+ return discSpacing(x, y) * (1 - sh.ArmCompression*armTerm(x, y, math.Hypot(x, y)))
133+}
134+
135+// systemRadius is the disc a system may occupy, small enough that neighbouring
136+// systems can never reach each other.
137+func systemRadius(s *POI) float64 {
138+ return starSpacing(s.X, s.Y) * config.Galaxy.Shape.SystemRadiusFraction
139+}
140+
141+func nearestToCore(stars []*POI) *POI {
142+ var best *POI
143+ bestD := math.Inf(1)
144+ for _, s := range stars {
145+ if d := math.Hypot(s.X, s.Y); d < bestD {
146+ bestD, best = d, s
147+ }
148+ }
149+ return best
150+}
151+
152+// placeStars scatters stars over the disc model, rejecting any candidate that
153+// lands closer to a neighbour than the local minimum spacing allows.
154+func (g *Galaxy) placeStars(r *rng) []*POI {
155+ d := buildDensityGrid()
156+ span := int(math.Ceil(config.Galaxy.StarSpacing.Max / d.cell))
157+ cells := make([][]*POI, d.n*d.n)
158+ stars := make([]*POI, 0, config.Galaxy.StarCount)
159+ for tries := 0; tries < config.Galaxy.StarCount*20 && len(stars) < config.Galaxy.StarCount; tries++ {
160+ x, y := d.sample(r)
161+ if math.Hypot(x, y) > config.Galaxy.Radius {
162+ continue
102163 }
103- counts["star"]++
104- g.add(star)
105-
106- // extras become more common toward the galactic core
107- density := 1 - math.Min(1, dist/radius)
108- fade := config.Galaxy.Extras.EdgeFade + (1-config.Galaxy.Extras.EdgeFade)*density
109-
110- // planets
111- if r.Chance(config.Galaxy.Planets.Chance * fade) {
112- n := 1 + r.Intn(config.Galaxy.Planets.Max)
113- for j := 0; j < n; j++ {
114- p := &POI{
115- ID: fmt.Sprintf("planet:%d", counts["planet"]),
116- Kind: kindPlanet,
117- Star: star.ID,
118- Orbit: r.Range(config.Galaxy.Planets.OrbitMin, config.Galaxy.Planets.OrbitMax),
119- Angle: r.Float64() * 2 * math.Pi,
120- Radius: r.Range(config.Galaxy.PlanetRadius.Min, config.Galaxy.PlanetRadius.Max),
164+ cx, cy := d.index(x, y)
165+ spacing := starSpacing(x, y)
166+ free := true
167+ for dy := -span; dy <= span && free; dy++ {
168+ for dx := -span; dx <= span && free; dx++ {
169+ for _, o := range d.at(cells, cx+dx, cy+dy) {
170+ if math.Hypot(o.X-x, o.Y-y) < math.Max(spacing, starSpacing(o.X, o.Y)) {
171+ free = false
172+ break
173+ }
121174 }
122- counts["planet"]++
123- p.orbitAround(star)
124- g.add(p)
125175 }
126176 }
127- if r.Chance(config.Galaxy.Extras.AsteroidChance * fade) {
128- p := g.orbitPOI(kindAsteroid, "asteroid", star, counts, r)
129- p.Ore = config.Cargo.FieldOre
130- p.Radius = 260
177+ if !free {
178+ continue
179+ }
180+ s := &POI{
181+ ID: g.nextID(kindStar),
182+ Kind: kindStar,
183+ X: x,
184+ Y: y,
185+ Radius: r.Range(config.Galaxy.StarRadius.Min, config.Galaxy.StarRadius.Max),
186+ }
187+ cells[cy*d.n+cx] = append(cells[cy*d.n+cx], s)
188+ stars = append(stars, s)
189+ g.add(s)
190+ }
191+ return stars
192+}
193+
194+// densityGrid is the target star mass distribution, sampled to draw candidate
195+// star positions. The mass follows the galaxy shape until it hits the local
196+// packing limit, so the arms stay overdense and the core saturates into a bulge.
197+type densityGrid struct {
198+ n int
199+ cell float64
200+ cdf []float64
201+ total float64
202+}
203+
204+// densityCells is the resolution the density field is baked at.
205+const densityCells = 192
206+
207+// fill caps the mass at a fraction of the hexagonal packing limit.
208+const fill = 0.6
209+
210+func buildDensityGrid() *densityGrid {
211+ n := densityCells
212+ cell := 2 * config.Galaxy.Radius / float64(n)
213+ area := cell * cell
214+ shape := make([]float64, n*n)
215+ limit := make([]float64, n*n)
216+ sum := 0.0
217+ for cy := 0; cy < n; cy++ {
218+ for cx := 0; cx < n; cx++ {
219+ x, y := cellCenter(cx, cy, cell)
220+ s := galaxyShape(x, y) * area
221+ shape[cy*n+cx] = s
222+ limit[cy*n+cx] = fill / (0.866 * starSpacing(x, y) * starSpacing(x, y)) * area
223+ sum += s
224+ }
225+ }
226+ alpha := float64(config.Galaxy.StarCount) / sum
227+ mass := make([]float64, n*n)
228+ for iter := 0; iter < 4; iter++ {
229+ total := 0.0
230+ for i := range mass {
231+ mass[i] = math.Min(alpha*shape[i], limit[i])
232+ total += mass[i]
233+ }
234+ alpha *= float64(config.Galaxy.StarCount) / total
235+ }
236+ d := &densityGrid{n: n, cell: cell, cdf: make([]float64, n*n)}
237+ for i, m := range mass {
238+ d.total += m
239+ d.cdf[i] = d.total
240+ }
241+ return d
242+}
243+
244+// galaxyShape is the target surface density: a central bulge, a smooth disc,
245+// and log-spiral arms, all falling off toward the rim.
246+func galaxyShape(x, y float64) float64 {
247+ sh := config.Galaxy.Shape
248+ r := math.Hypot(x, y)
249+ if r > config.Galaxy.Radius {
250+ return 0
251+ }
252+ disc := math.Exp(-r / (sh.DiscScale * config.Galaxy.Radius))
253+ bulge := sh.BulgeWeight * math.Exp(-(r/(sh.BulgeScale*config.Galaxy.Radius))*(r/(sh.BulgeScale*config.Galaxy.Radius)))
254+ return disc*(1+sh.ArmStrength*armTerm(x, y, r)) + bulge
255+}
256+
257+// armTerm is 1 on an arm centreline and falls off between the arms.
258+func armTerm(x, y, r float64) float64 {
259+ sh := config.Galaxy.Shape
260+ angle := math.Atan2(y, x)
261+ bulge := sh.BulgeScale * config.Galaxy.Radius
262+ best := 0.0
263+ for k := 0; k < sh.Arms; k++ {
264+ d := wrapPi(angle - armPhase(float64(k), r, bulge))
265+ best = math.Max(best, math.Exp(-0.5*(d/sh.ArmWidth)*(d/sh.ArmWidth)))
266+ }
267+ return best
268+}
269+
270+// wrapPi reduces an angle to [-pi, pi).
271+func wrapPi(a float64) float64 {
272+ a = math.Mod(a+math.Pi, 2*math.Pi)
273+ if a < 0 {
274+ a += 2 * math.Pi
275+ }
276+ return a - math.Pi
277+}
278+
279+// armPhase is the logarithmic spiral phase of arm n at a given radius.
280+func armPhase(arm, dist, r0 float64) float64 {
281+ if dist < r0 {
282+ dist = r0
283+ }
284+ pitch := config.Galaxy.Shape.ArmPitchDegrees * math.Pi / 180
285+ return arm*2*math.Pi/float64(config.Galaxy.Shape.Arms) + math.Log(dist/r0)/math.Tan(pitch)
286+}
287+
288+func cellCenter(cx, cy int, cell float64) (float64, float64) {
289+ return -config.Galaxy.Radius + (float64(cx)+0.5)*cell, -config.Galaxy.Radius + (float64(cy)+0.5)*cell
290+}
291+
292+func (d *densityGrid) index(x, y float64) (int, int) {
293+ cx := int((x + config.Galaxy.Radius) / d.cell)
294+ cy := int((y + config.Galaxy.Radius) / d.cell)
295+ return clampCell(cx, d.n), clampCell(cy, d.n)
296+}
297+
298+func clampCell(c, n int) int {
299+ if c < 0 {
300+ return 0
301+ }
302+ if c >= n {
303+ return n - 1
304+ }
305+ return c
306+}
307+
308+func (d *densityGrid) at(cells [][]*POI, cx, cy int) []*POI {
309+ if cx < 0 || cy < 0 || cx >= d.n || cy >= d.n {
310+ return nil
311+ }
312+ return cells[cy*d.n+cx]
313+}
314+
315+// sample draws a position proportional to the baked mass distribution.
316+func (d *densityGrid) sample(r *rng) (float64, float64) {
317+ i := sort.SearchFloat64s(d.cdf, r.Float64()*d.total)
318+ if i >= len(d.cdf) {
319+ i = len(d.cdf) - 1
320+ }
321+ cx, cy := i%d.n, i/d.n
322+ return -config.Galaxy.Radius + (float64(cx)+r.Float64())*d.cell,
323+ -config.Galaxy.Radius + (float64(cy)+r.Float64())*d.cell
324+}
325+
326+// populate lays out one star system: planets on separate orbits, then POIs in
327+// orbit of a planet (or of the star when no planet has room).
328+func (g *Galaxy) populate(r *rng, star *POI, home bool) {
329+ sysR := systemRadius(star)
330+ placed := []*POI{star}
331+ commit := func(p *POI) { placed = append(placed, p); g.add(p) }
332+
333+ density := densityAt(star.X, star.Y)
334+ planets := []*POI{}
335+ want := config.Galaxy.Planet.BaseCount + int(float64(config.Galaxy.Planet.CoreBonus)*density)
336+ for i := 0; i < want; i++ {
337+ if p := g.planet(r, star, sysR, placed); p != nil {
338+ commit(p)
339+ planets = append(planets, p)
131340 }
132- if r.Chance(config.Galaxy.Extras.CommsChance * fade) {
133- p := g.orbitPOI(kindComms, "comms", star, counts, r)
134- p.Radius = 120
135- p.Linked = map[string]bool{}
341+ }
342+ hosts := append(append([]*POI{}, planets...), star)
343+
344+ // the home system always gets a shipyard and some ore to start on
345+ if home {
346+ if p := g.satellite(r, star, kindShipyard, hosts, sysR, placed); p != nil {
347+ commit(p)
136348 }
137- if r.Chance(config.Galaxy.Extras.ShipyardChance * fade) {
138- p := g.orbitPOI(kindShipyard, "shipyard", star, counts, r)
139- p.Radius = 180
349+ }
350+ for _, kind := range poiKinds {
351+ chance := poiChance(kind) * (config.Galaxy.POI.EdgeFade + (1-config.Galaxy.POI.EdgeFade)*density)
352+ if home {
353+ if kind == kindShipyard {
354+ continue
355+ }
356+ if kind == kindAsteroid {
357+ chance = 1
358+ }
140359 }
141- if r.Chance(config.Galaxy.Extras.WreckChance * fade) {
142- p := g.orbitPOI(kindWreck, "wreck", star, counts, r)
143- p.Radius = 160
144- p.Wreck = randomWreckPieces(r, config.Cargo.WreckPieces)
360+ if !r.Chance(chance) {
361+ continue
145362 }
146- if r.Chance(config.Galaxy.Extras.FleetChance * fade) {
147- p := g.orbitPOI(kindFleet, "fleet", star, counts, r)
148- p.Radius = 0
149- p.Hostile = r.Chance(0.45 + 0.35*density)
150- p.FleetCap = config.NPC.MinFleetSize + r.Intn(config.NPC.MaxFleetSize-config.NPC.MinFleetSize+1)
363+ if p := g.satellite(r, star, kind, hosts, sysR, placed); p != nil {
364+ commit(p)
151365 }
152366 }
367+}
153368
154- g.homeSystem()
155- return g
369+func poiChance(kind string) float64 {
370+ switch kind {
371+ case kindAsteroid:
372+ return config.Galaxy.POI.AsteroidChance
373+ case kindComms:
374+ return config.Galaxy.POI.CommsChance
375+ case kindShipyard:
376+ return config.Galaxy.POI.ShipyardChance
377+ case kindWreck:
378+ return config.Galaxy.POI.WreckChance
379+ default:
380+ return config.Galaxy.POI.FleetChance
381+ }
156382 }
157383
158-func (g *Galaxy) orbitPOI(kind, prefix string, star *POI, counts map[string]int, r *rng) *POI {
159- p := &POI{
160- ID: fmt.Sprintf("%s:%d", prefix, counts[prefix]),
161- Kind: kind,
162- Star: star.ID,
163- Orbit: r.Range(config.Galaxy.Planets.OrbitMin, config.Galaxy.Planets.OrbitMax),
164- Angle: r.Float64() * 2 * math.Pi,
165- Radius: 100,
384+// poiRadius keeps every POI smaller than the smallest planet.
385+func poiRadius(kind string, r *rng) float64 {
386+ lo, hi := 0.0, 1.0 // fraction of the configured POI radius range
387+ switch kind {
388+ case kindAsteroid:
389+ lo = 0.5
390+ case kindShipyard:
391+ lo, hi = 0.35, 0.75
392+ case kindWreck:
393+ lo, hi = 0.25, 0.65
394+ case kindComms:
395+ hi = 0.45
396+ case kindFleet:
397+ hi = 0.5
166398 }
167- counts[prefix]++
168- p.orbitAround(star)
169- return g.add(p)
399+ rmin, rmax := config.Galaxy.POI.Radius.Min, config.Galaxy.POI.Radius.Max
400+ return rmin + (rmax-rmin)*r.Range(lo, hi)
170401 }
171402
172-// homeSystem picks the star closest to the core and guarantees a shipyard so
173-// new players have somewhere to spawn and refuel.
174-func (g *Galaxy) homeSystem() {
175- var best *POI
176- bestD := math.Inf(1)
177- for _, s := range g.Stars {
178- d := Vec2{s.X, s.Y}.Len()
179- if d < bestD {
180- bestD, best = d, s
403+// planet places one planet on its own orbit around the star.
404+func (g *Galaxy) planet(r *rng, star *POI, sysR float64, placed []*POI) *POI {
405+ gc := config.Galaxy
406+ inner := math.Max(star.Radius*gc.Planet.OrbitMinFactor, star.Radius+gc.Planet.Radius.Max)
407+ outer := math.Max(inner, sysR*gc.Planet.OrbitMaxFactor)
408+ for try := 0; try < 8; try++ {
409+ p := &POI{
410+ ID: g.nextID(kindPlanet),
411+ Kind: kindPlanet,
412+ Sys: star.ID,
413+ Star: star.ID,
414+ Orbit: r.Range(inner, outer),
415+ Angle: r.Float64() * 2 * math.Pi,
416+ Radius: r.Range(gc.Planet.Radius.Min, gc.Planet.Radius.Max),
417+ }
418+ p.orbitAround(star)
419+ if fits(p, star, sysR, placed) {
420+ return p
181421 }
182422 }
183- g.Home = best
184- for _, p := range g.POIs {
185- if p.Kind == kindShipyard && p.Star == best.ID {
186- return
423+ return nil
424+}
425+
426+// satellite places a POI in orbit of one of the system's hosts.
427+func (g *Galaxy) satellite(r *rng, star *POI, kind string, hosts []*POI, sysR float64, placed []*POI) *POI {
428+ gc := config.Galaxy
429+ start := r.Intn(len(hosts))
430+ for i := 0; i < len(hosts); i++ {
431+ h := hosts[(start+i)%len(hosts)]
432+ inner, outer := h.Radius*gc.POI.HostOrbitMinFactor, h.Radius*gc.POI.HostOrbitMaxFactor
433+ if h.Kind == kindStar {
434+ inner, outer = sysR*gc.POI.StarOrbitMinFactor, sysR*gc.POI.StarOrbitMaxFactor
187435 }
436+ inner = math.Max(inner, h.Radius+gc.POI.Radius.Max)
437+ outer = math.Max(outer, inner)
438+ for try := 0; try < 6; try++ {
439+ p := &POI{
440+ ID: g.nextID(kind),
441+ Kind: kind,
442+ Sys: star.ID,
443+ Star: h.ID,
444+ Orbit: r.Range(inner, outer),
445+ Angle: r.Float64() * 2 * math.Pi,
446+ Radius: poiRadius(kind, r),
447+ }
448+ switch kind {
449+ case kindAsteroid:
450+ p.Ore = config.Cargo.FieldOre
451+ case kindComms:
452+ p.Linked = map[string]bool{}
453+ case kindWreck:
454+ p.Wreck = randomWreckPieces(r, config.Cargo.WreckPieces)
455+ case kindFleet:
456+ p.Hostile = r.Chance(0.45 + 0.35*densityAt(star.X, star.Y))
457+ p.FleetCap = config.NPC.MinFleetSize + r.Intn(config.NPC.MaxFleetSize-config.NPC.MinFleetSize+1)
458+ }
459+ p.orbitAround(h)
460+ if fits(p, star, sysR, placed) {
461+ return p
462+ }
463+ }
464+ }
465+ return nil
466+}
467+
468+// fits reports whether p stays inside the system and clear of everything
469+// already placed in it.
470+func fits(p *POI, star *POI, sysR float64, placed []*POI) bool {
471+ if math.Hypot(p.X-star.X, p.Y-star.Y)+p.Radius > sysR {
472+ return false
188473 }
189- y := &POI{
190- ID: fmt.Sprintf("shipyard:home"),
191- Kind: kindShipyard,
192- Star: best.ID,
193- Orbit: 900,
194- Angle: 0,
195- Radius: 180,
474+ for _, q := range placed {
475+ if math.Hypot(q.X-p.X, q.Y-p.Y) < q.Radius+p.Radius {
476+ return false
477+ }
196478 }
197- y.orbitAround(best)
198- g.add(y)
479+ return true
199480 }
200481
201-// spawnPos returns a position in orbit around the home shipyard, offset
202-// outward from the star so a fresh ship never spawns inside it.
482+// spawnPos returns a clear starting point in orbit of the home shipyard,
483+// nudged outward until it is not inside a star.
203484 func (g *Galaxy) spawnPos() (Vec2, string) {
204485 for _, p := range g.POIs {
205- if p.Kind == kindShipyard && p.Star == g.Home.ID {
206- off := Vec2{p.X - g.Home.X, p.Y - g.Home.Y}
207- if off.Len() == 0 {
208- off = Vec2{1, 0}
209- }
210- dir := off.Norm()
211- d := config.Galaxy.OrbitRange * 0.8
212- return Vec2{p.X + dir.X*d, p.Y + dir.Y*d}, p.ID
486+ if p.Kind != kindShipyard || (g.Home != nil && p.Sys != g.Home.ID) {
487+ continue
213488 }
489+ dir := Vec2{p.X - g.Home.X, p.Y - g.Home.Y}
490+ if dir.Len() == 0 {
491+ dir = Vec2{1, 0}
492+ }
493+ dir = dir.Norm()
494+ pos := Vec2{p.X, p.Y}.Add(dir.Mul(config.Galaxy.OrbitRange * 0.8))
495+ for i := 0; i < 40 && g.starAt(pos, 120) != nil; i++ {
496+ pos = pos.Add(dir.Mul(120))
497+ }
498+ return pos, p.ID
499+ }
500+ if g.Home != nil {
501+ return Vec2{g.Home.X + config.Galaxy.OrbitRange, g.Home.Y}, g.Home.ID
214502 }
215- return Vec2{g.Home.X + config.Galaxy.OrbitRange, g.Home.Y}, g.Home.ID
503+ return Vec2{}, ""
216504 }
217505
218506 func randomWreckPieces(r *rng, n int) []*Piece {
server/main.go+3-0
@@ -36,6 +36,9 @@ func main() {
3636 galaxy := generateGalaxy(seed)
3737
3838 // restore the shared exploration / naming progress
39+ if err := store.checkLayout(); err != nil {
40+ log.Fatalf("store: %v", err)
41+ }
3942 if rows, err := store.loadPOIs(); err == nil {
4043 explored := 0
4144 for id, row := range rows {
server/persist.go+14-0
@@ -69,6 +69,20 @@ func (s *Store) seed() (uint64, error) {
6969 return v, nil
7070 }
7171
72+// layoutVersion identifies the galaxy layout. Exploration rows written for an
73+// older layout would name the wrong places, so they are dropped on a change.
74+const layoutVersion = "2"
75+
76+func (s *Store) checkLayout() error {
77+ if v, ok := s.meta("layout"); ok && v == layoutVersion {
78+ return nil
79+ }
80+ if _, err := s.db.Exec(`DELETE FROM poi`); err != nil {
81+ return err
82+ }
83+ return s.setMeta("layout", layoutVersion)
84+}
85+
7286 func (s *Store) loadPOIs() (map[string]poiRow, error) {
7387 rows, err := s.db.Query(`SELECT id, name, named_by, explored FROM poi`)
7488 if err != nil {