Galaxy Generation¶
Purpose¶
The galaxy-generation pipeline builds the universe from a few configuration parameters: a Galaxy metadata row, then per-Region content (zones, clusters, sectors, warps, stations, planets, resource seeding). It is run at game initialization (Central Nexus + Terran Space) and again every time a player subscribes to a region (player-owned region creation). The pipeline is deterministic given a seed, idempotent at the region level, and re-runnable without leaving partial state.
Inputs¶
The generator reads:
- A configuration dict (max_sectors, density values, zone profile, optional seed).
- The Region row to populate (created separately by the regional service or admin tool).
- For player-owned regions: the owner's User row, region size tier (purchased), aesthetic preferences.
- The sw2102-bang dataset (precomputed sector layouts, planet seeds, port templates) — fed in as JSON for reproducible previews.
The system fires on:
- POST /api/v1/admin/galaxy/generate — initial galaxy create (Central Nexus + Terran Space).
- POST /api/v1/admin/regions/{id}/generate-content — create or re-create a region's content.
- Subscription activation — the regional service triggers content generation for a new player region.
- The sw2102-bang CLI — generates static dataset files that the gameserver imports.
Process¶
Step 1 — Galaxy metadata¶
generate_galaxy(name, config) creates exactly one Galaxy row:
- max_sectors — total capacity across all regions (default 10,000).
- statistics — counters initialized to zero (updated as regions populate).
- density — default station/planet/warp percentages.
Step 2 — Regions¶
Three region types with distinct profiles:
| Region type | Sectors | Zones | Station density | Planet density | Warp tunnel × |
|---|---|---|---|---|---|
| Central Nexus | 5,000 | 1 (Expanse) | 5% | 10% | 0.3 |
| Terran Space | 300 | 3 (Fed/Border/Frontier) | 15% | 25% | 1.0 |
| Player-owned | 100–1,000 | 3 (default) | 15% | 25% | 1.0 |
Step 3 — Zones¶
_generate_zones_for_region(region) partitions sector numbers into security zones:
- Central Nexus → single
EXPANSEzone (sectors 1–5000), policing 3, danger 6. - Other regions → three zones split by sector number:
FEDERATION— first 33% — policing 9, danger 1.BORDER— middle 34% — policing 5, danger 4.FRONTIER— last 33% — policing 2, danger 8.
Step 4 — Clusters¶
_create_clusters_for_region(region, n) partitions the region's sector budget:
- Central Nexus → 20 clusters (~250 sectors each).
- Terran Space → 6 clusters (~50 sectors each).
- Player regions →
max(2, total_sectors // 50).
Each cluster carries:
- A type drawn from a region-appropriate set (Standard, Resource Rich, Population Center, Trade Hub, Military Zone, Frontier Outpost, Contested, Special Interest).
- Variable size (±33% from average).
- Optional nebula property (~20% of clusters) — defines the nebula type and coverage applied to member sectors.
Step 5 — Sectors¶
_create_sectors_for_cluster(cluster, region, zones) creates Sector rows incrementally:
- Sector numbers sequential within the region, starting at 1.
- 85% generated as
STANDARD; 15% chosen from cluster's allowed special types (NEBULA,ASTEROID_FIELD,BLACK_HOLE,RADIATION_ZONE,WARP_STORM). - 3D coordinates from
_generate_cluster_coordinates. - Both
zone_id(sector-number range) andcluster_id(creation grouping) set. - Resource seeds, hazard level, radiation level derived per type.
Step 6 — Warp graph¶
_create_warps_between_sectors() builds adjacency:
- Every sector connects to 2–4 neighbors (proximity-based).
- Warp cost = 1 turn for standard sector pairs.
- Stability factor accounts for hazard levels.
_create_warp_tunnels_enhanced(num_sectors, density_multiplier) adds long-distance tunnels:
- Density multiplier: 0.3 for Central Nexus, 1.0 elsewhere.
- Mix of one-way and bidirectional (default ~10% one-way).
- 10–20% of clusters intentionally left unconnected via tunnels (reachable only by Warp Jumper quantum jump).
Step 7 — Stations & planets¶
_populate_sectors_with_ports(probability, region_id):
- Iterates sectors; rolls against probability.
- On hit, creates a Station of a region/zone-appropriate class (0–11).
- Initializes commodities JSONB with capacity/quantity/base_price/production_rate per the class trading pattern.
- Creates initial MarketPrice rows (see market-pricing.md).
_populate_sectors_with_planets(probability, region_id):
- Similar; creates Planet rows.
- Habitability, resource richness, type weighted by region/zone.
Step 8 — Region starter sector (Sector 1)¶
_ensure_region_starter_sector(region):
- Guarantees Sector 1 has a population hub planet (is_population_hub = True).
- Class-0 trading station that sells colonists (only place to buy population).
- Public, well-policed, non-destructible.
Step 9 — SpaceDock¶
_create_spacedock_for_region(region):
- Places a special station at sector 10 (or nearest available).
- Sells genesis devices and special equipment.
- Counterpart to TradeDock for late-game logistics.
Step 10 — Statistics roll-up¶
_update_galaxy_statistics(galaxy) recomputes the galaxy-level counters (total_sectors, station_count, planet_count, warp_tunnel_count).
sw2102-bang integration¶
The sw2102-bang repo (TypeScript) generates a deterministic dataset for offline previews:
- bigbang.ts — orchestrator (mirrors the steps above).
- graph.ts — warp graph generation.
- nebulae.ts, planets.ts, ports.ts, special.ts — content seeding.
- serialize.ts / db-writer.ts — output as JSON or directly into the gameserver DB.
The gameserver can either generate live (above pipeline) or import from a bang dataset. When importing: 1. Read JSON manifest. 2. Bulk-insert sectors, warps, stations, planets within a single transaction per region. 3. Run the same starter-sector and SpaceDock guards so any imported data is normalized.
Outputs / state changes¶
Per generation run:
- Galaxy row inserted (or stats updated).
- Region rows touched (one populated, others untouched in incremental runs).
- Zone, Cluster, Sector rows inserted for the region.
- sector_warps adjacency rows.
- WarpTunnel rows.
- Station, Planet, Resource, Market, MarketPrice rows.
Events emitted:
- region_generation_started (admin feed).
- region_generation_progress (per-step ticks).
- region_generation_completed — final summary.
- galaxy_updated — global broadcast for player-facing stats.
Invariants¶
- Every region has exactly one Sector 1 with a population hub and a Class-0 station.
- Every region has at least one SpaceDock (sector 10 or fallback).
- Sector numbers are unique within a region.
- Every sector has at least one warp neighbor (no orphaned sectors).
Galaxy.statistics.total_sectorsmatchesSUM(Region.total_sectors)after every run.- No partial region state on failure — generation transactions roll back cleanly.
- Re-running region content generation on an already-populated region either is a no-op (idempotency check) or fully replaces (admin "force" flag); never mixed.
- Player-owned regions cannot reach into Central Nexus or Terran Space at generation time — connectivity goes through the warp gateway model only.
Failure modes¶
| Mode | Target handling |
|---|---|
| Generation fails mid-region | Single transaction per region; rollback to pre-run state. Admin notified. |
Sector budget exhausted (would exceed Galaxy.max_sectors) |
Pre-flight check rejects before mutation. |
| Idempotent re-run | If Region.is_populated, skip unless force=true. |
| Bang dataset corrupt / version mismatch | Import refuses; admin sees a structured error with the bang version expected. |
| Random seed not provided | Use a server-generated UUID seed; record it on Region.generation_seed for reproducibility. |
| Starter sector already exists with conflicting state | _ensure_region_starter_sector upserts: existing planet/station preserved, missing pieces filled in. |
| Player-region size out of bounds | Clamped to [100, 1000]; admin override extends bounds with audit log. |
| Concurrent generation requests on same region | Region-level advisory lock; second request returns 409 Conflict. |
Source map¶
| Concern | Path (target) |
|---|---|
| Generator | services/gameserver/src/services/galaxy_service.py:GalaxyGenerator |
| Galaxy / Region / Zone / Cluster / Sector models | services/gameserver/src/models/galaxy.py, region.py, zone.py, cluster.py, sector.py |
| Warp tunnel model | services/gameserver/src/models/warp_tunnel.py |
| Station / planet seed | _populate_sectors_with_ports, _populate_sectors_with_planets |
| Starter sector + SpaceDock | _ensure_region_starter_sector, _create_spacedock_for_region |
| Market price backfill | services/gameserver/src/services/galaxy_service.py:backfill_market_prices |
| Nexus generation alternative | services/gameserver/src/services/nexus_generation_service.py |
| Admin generation API | services/gameserver/src/api/routes/admin.py, admin_comprehensive.py |
| Bang generator | sw2102-bang/src/bigbang.ts (CLI: bigbang) |
| Bang DB writer | sw2102-bang/src/db-writer.ts |
Related¶
- DATA_MODELS:
../DATA_MODELS/galaxy.md,../DATA_MODELS/economy.md. - FEATURES:
../FEATURES/galaxy/generation.md,../FEATURES/galaxy/sectors.md. - SYSTEMS: market-pricing.md, genesis-deploy.md, regional-governance.md.
- ARCHITECTURE:
../ARCHITECTURE/multi-regional.md.