Live & Playable — Pablo

StellarFronts

A real-time multiplayer 4X space strategy game. Claim a country, explore the galaxy, expand with starbases and districts, manage a full economy, research 60+ technologies, and compete with up to 15 simultaneous factions. Built on React 19, BabylonJS 7, Node.js WebSocket, and a custom orchestrator that runs multiple game versions in parallel without downtime.

Play Now →
StellarFronts login screen
139
Git Commits
76K+
Lines of TypeScript
113
Source Files
4mo
Active Development
15
Factions / Players
64+
Technologies

At a glance

3
Server processes
V20
Current schema version
500+
Star systems per game
2D+3D
Galaxy + system views

StellarFronts is built around logistics, expansion, economy, research, and market trading — not direct combat. The full stack starts with a single npm run dev:all that brings up the React client, the HTTP auth server, the WebSocket game server, and the orchestrator together.

Galaxy map — fully explored
Galaxy map after sustained expansion — territory carved out, starbases placed, systems connected.

Architecture

The codebase is split clean down the middle: src/ is the React UI, shared gameplay types, and the BabylonJS scene layer; server/ is the auth server, the game server, and the orchestrator that ties everything together behind one public gateway. Each process has a single clear responsibility — and they fail independently.

BROWSER CLIENT React 19 + Vite · useAppFlow · GameServerClient.ts · SceneManager.ts App.tsx routing: / · /home · /game/:id · /dev · /news · Singleton WS with auto-reconnect + protocol version check BabylonJS 7 · WebGPU → WebGL2 auto-fallback · GalaxyScene (500+ stars, ownership overlay) · SystemScene (5,200 lines, 10 GLB models) AUTH FLOW GAME STREAM POST /auth HttpOnly cookie WSS + cookie snapshot + delta updates AUTH SERVER auth-server.ts :8788 Login · Signup · session tokens News / blog · game catalog API sf_session 7d · sf_dev_session 12h Procedural flag generator · CORS gated OAuth stubs (Google/Microsoft) → 501 WS GATEWAY Public endpoint :8787 Routes WS client → correct game-server version by game ID · transparent proxy forwards binary frames intact — no re-encoding overhead · WS upgrade negotiation + protocol-version gate reads / writes version lookup PERSISTENCE — AUTH SQLite · auth.sqlite PBKDF2-SHA512 · 210,000 iterations 64-byte keys · timing-safe compare accounts · sessions · game catalog · dev stats ORCHESTRATOR orchestrator.ts :8790 (control API · token-gated) git worktree per version · spawns + monitors game-server Node processes · auto crash-recovery on active games backup before destructive ops (reset/update/rollback) · compatibility-gated schema updates · port base 8810+ git checkout worktree → isolated binary per version → live games stay pinned · new games get latest game catalog spawn GAME SERVER (dev) :8809 Dev branch · latest code 100ms tick · 10,516-line server/index.ts admin cmd handler · token-gated new games default here GAME SERVER (v1) :8810 Pinned git worktree Older live games stay here old code · preserved state GAME SERVER (vN) :8811+ Additional isolated versions Each owns its worktree scales to N parallel versions 30s dirty-write PERSISTENCE — GAME STATE game_states/{id}/state.json Schema V20 · backward-compatible to V1 · timestamped backup before any destructive operation 15 factions · 500 stars · planets · fleets · ships · market history · diplomacy state research progress · events queue · combat log · species + pop groups · construction queue game state broadcasts (snapshot + delta) crash recovery
Zero-downtime updates: The orchestrator checks each game version out as an isolated git worktree and runs it as its own Node process on a separate internal port. A live game that started on v0.8 stays pinned to that worktree's binary while new games start on v0.9. The public WS gateway on :8787 is the only thing clients ever talk to — it routes transparently. This means Pablo can ship new code without ending anyone's active session.

WebSocket Protocol (V2 / Schema V20)

Client → Server
"join"Initial connection with session token and game ID
"command"Game action: move fleet, build, research, trade, declare war…
"subscribeDetails"Request full detail payload for a specific scope (system, planet, fleet, market)
"unsubscribeDetails"Stop receiving detail updates for a scope
Server → Client
"snapshot"Full game state on connect — filtered to client's faction visibility
"update"Incremental tick delta — only changed fields, keeps bandwidth low
"detail"Deep payload for subscribed scope (planet economy, market history, fleet orders…)
"commandResult"Success or structured error response per command
"serverInfo"Admin broadcast messages and system notifications

Game loop & time compression

The server runs a setInterval tick every 100ms. Each tick advances the game clock by a configurable amount — from 1 game-hour per second (detail mode) up to 360 game-days per second (fast-forward). Everything — economy production, fleet movement, construction progress, combat resolution — is calculated against elapsed game-time, so the simulation is consistent regardless of speed.

Game Loop

100ms server tick

Game state advances every 100ms real-time. All simulation — fleet movement, economy, combat, events — resolves in each tick against elapsed game-days.

Time Control

9 speed presets

1hr/s through 360 days/s. Clock is always in game-years + fractional days. Client interpolates displayed year from last-known server clock to avoid stale reads.

Persistence

30s dirty-write save

State is only written to disk when marked dirty. Full JSON snapshot per game in game_states/{id}/state.json. Timestamped backups before any destructive operation.

Fog of War

Faction-scoped snapshots

Server computes visible star IDs via BFS up to N hyperlane jumps from faction territory. Snapshot and update messages are filtered per client — other factions' unseen territory is never sent.

Clock sync

Client-side interpolation

The client doesn't wait for a server tick to update the displayed game year — it calls estimateClockYear() to linearly interpolate from the last known server timestamp and speed setting. The UI always feels live, even at 100ms tick intervals.

Event system

In-game events & situations

Events (short-term: one-off modifiers, crises, opportunities) and Situations (long-running: persistent states that evolve over time) fire based on game state conditions each tick. They dynamically alter demand, dispute risk, research rates, and deal difficulty — no two games play the same.

Economy simulation

Every planet runs a full job-and-building economy. Six strategic resources flow through production chains, population grows under demographic pressure, and buildings unlock via a 64-technology research tree. The economy resolves at two cadences: per-hour for resource flows and per-quarter for population growth.

🌾
Food
Consumed by population (1.1 / 1M people/month). Farms, processors, hydroponic bays.
⛏️
Minerals
Raw construction material. Miners and purification plants. Feeds alloy production.
Energy
Powers the grid. Not tradeable — strategic chokepoint. Generators and solar arrays.
📦
Goods
Consumer products. Amenity multiplier — shortage tanks happiness and growth.
🔩
Alloys
Military and construction. Ships, starbases, districts all consume alloys per day.
🔬
Research
Not tradeable. Produced by researchers and labs. Divided across active tech queue.
Jobs

12 job types · 3 classes

Upper (admin, researcher), Middle (artisan, metallurgist, entertainer, technician, clerk), Lower (farmer, miner, enforcer). Unemployment and crime are modelled as job types with negative effects.

Buildings

14 building types · 5 levels

Four district types (City, Mining, Generator, Agriculture) each host specific buildings. Unlocking level 2–5 requires matching research. Higher levels multiply job output rather than add slots.

Population

6-factor growth model

Housing, amenities, stability, crime, employment, and capacity pressure all feed a monthly growth rate. 1 pop unit = 1 million people. New colonies start at 500M; developed worlds at 10B.

Shortage system

Penalty modifiers on scarcity

When a resource runs critically low, output penalties propagate — a food shortage cuts farm output further, tightening the squeeze. Forces players to prioritise supply chains.

Districts

4 district types · land-use zoning

City, Mining, Generator, and Agriculture districts each host specific building sets. District slots are finite on each planet — choosing which to build shapes the planet's economic identity for the whole game.

Species & habitability

10+ species · trait modifiers

Each species has a habitability modifier per planet class, a growth rate multiplier, and production trait bonuses. Civil rights level (enslaved → full) affects happiness, job distribution, and faction-wide output.

Resolution order matters: Economy recalculates planets first (local production and consumption), then aggregates to faction totals, then runs market auto-trades. This prevents factions from getting credit for resources they haven't physically produced yet.

Research & technology tree

64+ technologies across seven categories. Research isn't a flat rate — it's a dynamic modifier system where your military strength, fleet size, active wars, resource surpluses, and job counts all feed live multipliers on your research speed, making the rate a direct reflection of your empire's current state.

Agriculture Industry Military Logistics Energy Computing Society
Modifier system

Context-aware speed

Active war → research bonus. Large fleet → bonus. High researcher job count → multiplier. All modifier contributions are reported in a breakdown so the player sees exactly why their speed is what it is.

Split allocation

80% active · 20% passive

Each tech receives active focus allocation from the queue, plus a passive bleed. Passive progress is capped at 80% of active pace, so you can't finish techs purely via passive — maintaining queue priority matters.

Unlocks

Buildings, hulls, modules

Technologies unlock building levels 1–5, ship hulls (corvette → battleship), ship modules (weapons/defense/utilities), starbase buildings, and job output multipliers.

Caps

1.0× min · 2.0× max

Research multipliers are bounded to prevent degenerate fast or slow states. Even a fully isolated empire produces research; even a warring one can't infinitely accelerate.

Default unlocks

Start-of-game tech baseline

Every empire starts with Spacefaring Foundations (corvettes, construction ships, colonisation ships), Directed Energy Weapons (lasers), Missile Ordnance, and Defensive Systems (shields, armour, sensors) — playable from turn one.

Infrastructure

Research Campus building

A dedicated building type that unlocks Research Annex slots on starbases. Stacks with researcher job count and leader bonuses. The campus is the primary way to push the research rate past its baseline.

Market & trade dynamics

The galactic market uses a dual-decay pressure system: every trade causes immediate price impact that decays quickly, plus a slower persistent trend that reflects long-run supply/demand. Prices are bounded (0.25× – 4.0× base) and carry a 5% fee. Energy and research are intentionally non-tradeable — they're internal chokepoints that force infrastructure investment.

Pricing

Base prices per resource

Food 1.1 · Minerals 1.4 · Goods 3.2 · Alloys 5.5 · Research 6.5 (non-tradeable). Multiplier shifts with trade pressure, bounded at 0.25×–4.0× base.

Pressure decay

Two-speed decay model

Temporary pressure (per-trade impact) decays at 0.96× per hour. Persistent pressure (trend) decays at 0.995× per hour. Large trades have outsized impact scaled by √(amount/liquidity).

Liquidity

1,200–10,000 units per resource

Base liquidity determines how much a trade moves the price. Small empires can't whale the market; large coordinated trading does shift prices meaningfully.

History

180 price snapshots · 6hr interval

30 days of market history per resource stored server-side. Clients subscribe to receive market detail updates and can render price trend graphs.

Auto-trading

Server-side hourly resolution

Factions can set standing buy/sell orders that resolve automatically each hour. Auto-trade pressure impact (0.01× √(amount/liquidity)) is gentler than manual trades, keeping AI participation from dominating price signals.

Fees & limits

5% fee · 320 transaction history

All trades carry a 5% market fee — a consistent sink that drains wealth from hyperactive traders. Transaction history is capped at 320 entries per resource; oldest trades are evicted to prevent unbounded memory growth.

Internal modifier (0.85× – 1.18×): Each player has a personal price modifier relative to the galactic market. This acts as a subtle difficulty/advantage lever and means two players trading the same resource don't necessarily see the same price.

Combat engine

Combat resolves in discrete rounds. Weapons hit based on range-band accuracy rolls modified by dodge chance and range-to-optimal distance. Damage penetrates a three-layer defence stack: shields (regenerating), armour (permanent until repaired), and hull (ship destroyed at 0). Fleet tactics — stance, formation, retreat policy — meaningfully alter engagement outcomes.

Weapon Range bands Cooldown Characteristic
LaserClose–Medium (6–30u)1 roundHigh accuracy, rapid fire, balanced damage
MissileMedium–Long (16–46u)2 roundsFlight time, interceptable, high burst damage
Point DefencePoint blank–Close (0–16u)1 roundAnti-projectile, degrades incoming missile salvos
RailgunClose–Long (6–46u)1 roundArmour penetration, effective against hardened hulls
PlasmaMedium–Long (16–64u)2 roundsHybrid shield + hull damage, high energy cost
6 range bands

Distance → mechanic mapping

Point blank (0–6u), Close (6–16u), Medium (16–30u), Long (30–46u), Extreme (46–64u), Out of range. Each weapon has an optimal band where accuracy peaks; performance degrades outside it.

Defence layers

Shield → Armour → Hull

Shields regenerate slowly over time. Armour is permanent damage until ship is repaired at a starbase. Hull hits are crits — ship destroyed at 0. Weapon types have different penetration profiles against each layer.

Fleet stances

5 combat behaviours

Artillery (long-range standoff), Line (coordinated broadside), Brawler (close-range mass), Swarm (redundancy through numbers), Defender (hold position, prioritise survival). Stance affects effective DPS and positioning.

Retreat policies

Configurable withdrawal threshold

None · Low (20% HP) · Medium (40% HP) · High (60% HP). Combined with chase policy (pursue into friendly/neutral/enemy systems) — lets you build aggressive or defensive fleet doctrines.

Ship design

Hull + module system

Six hull classes (corvette → destroyer → cruiser → battleship → construction → colonisation). Each hull has weapon, defence, and utility module slots. Unlocking higher hulls and modules via research shapes your fleet's tactical role.

Fleet leaders

Leader traits → combat multipliers

Each fleet can be assigned a leader with trait bonuses — e.g. "Genius" adds +25% to speed, attack, or shields. Leader assignment is a non-trivial optimisation: the right trait on the right fleet significantly changes engagement outcomes.

3D rendering pipeline

The game switches between two scenes: a galaxy view showing the full star map with faction ownership overlays, and a system view where you zoom into a single star system with 3D ships, starbases, planets, and live combat effects. BabylonJS automatically selects WebGPU if the browser supports it, falling back to WebGL2 — no configuration needed.

Engine

WebGPU → WebGL2 auto-fallback

SceneManager.ts detects WebGPU support at startup. If available, the modern API runs with better GPU utilisation. WebGL2 handles everything else. Single code path handles both.

Galaxy scene

500+ stars · ownership overlay

Stars rendered as sprites with type-specific colours. Hyperlane connections drawn as dynamic 2D lines. Faction ownership painted onto a 2400×2400 procedural texture updated per-tick. Fog of war fades unseen territory.

System scene

5,200-line renderer

Orbital ring meshes, planet spheres with procedural textures, star coronas and particle effects (including pulsar beams and black hole accretion disks), ship model trails, weapon beam effects, and dynamic label overlays — all in one scene.

3D Assets

10 GLB models — ships + starbases

6 ship hulls (corvette, destroyer, cruiser, battleship, construction, colonisation) and 4 starbase tiers. SystemAssetRegistry.ts loads and normalises each model to a target size via bounding-box scaling, then clones on demand — no re-loading per spawn.

Procedural

Perlin-noise skybox

Both scenes generate their space background procedurally from a seed — no external texture asset. The nebula colours vary with the nearby star type, giving each system a distinct atmosphere without artist-authored sky assets.

Performance

Asset instancing + lazy scenes

GLB templates loaded once, cloned on-demand. Asset warm-up runs on the auth screen so the first system view boots instantly. Only the active scene runs a render loop — the inactive one is fully disposed.

Galaxy map — unexplored at game start
Galaxy at game start — dark, unclaimed, waiting.
In-game system view with starbases and ships
Zoomed into a system — starbases, ships, and resource nodes in the 3D view.
Market trading panel
Live market — commodity prices, trade history, auto-trading configuration.
Ship designer panel
Ship designer — select hull, mount weapons, set fleet role and upgrade path.
System view with starbase
System view — orbital starbase with docked fleet and construction queue.

What you can do in-game

Claim a country

Normal accounts pick from generated factions on join — each with a procedurally generated flag, species, and home system. Observers and admins enter without claiming.

Explore the galaxy

BabylonJS 7 command view with a procedural skybox, loaded GLB ship and starbase models, and HUD overlays. Fog of war limits visibility to 3 hyperlane jumps from your territory.

Expand with starbases

Build Outpost → Starbase → Starhold → Starfortress. Each tier adds building slots. Starbases produce resources, host ship construction queues, and assert territorial control.

Run an economy

Manage 6 resources across 14 building types on every colony. Assign jobs, build districts, keep population happy, and route surpluses to the galactic market.

Research technologies

Queue 64+ techs across 7 categories. Unlock ship hulls, building levels, module types, and job bonuses. Research speed reflects your current empire state dynamically.

Trade on the market

Buy and sell 4 tradeable resources on the galactic market. Price impact scales with trade volume. Watch 30 days of price history to time your moves.

Build and command fleets

Design ships from hull + module combinations. Set stances, formations, and retreat thresholds. Assign a fleet leader with traits that multiply speed, attack, and shields.

Manage diplomacy

Declare wars, negotiate peace terms (reparations, system transfers, vassalage), propose trade treaties, and set border policies. Faction reputation affects AI responses.

Hold sessions

Game state persists per-game on a dirty-write timer. Leave and return — your country, fleets, and economy are exactly where you left them.

Diplomacy panel
Diplomacy — declare war, negotiate peace terms, set border policy and trade agreements.
Planet economy panel
Planet view — building grid, job assignments, pop groups, resource production and amenity balance.

Accounts & visibility

Role Can claim country Map visibility Debug commands
Player Yes — one generated country per game Scoped to held territory (3-jump BFS) No
Observer No Full read-only No
Admin Optional Full Yes — in-game console + /dev panel

Seeded accounts on a fresh setup: observer / observer, an admin account at the configured admin password, and color_1 through color_15 as player accounts.

Full stack

Frontend

React 19 + Vite + TypeScript

Pathname-driven routing in App.tsx. Single useAppFlow hook owns auth state, loading progress, and scene transitions. No external state library — React state + WS events are sufficient.

3D

BabylonJS 7

WebGPU/WebGL2 auto-selection. GalaxyScene and SystemScene each 2,600–5,200 lines. GLB asset loading with bounding-box normalisation and clone-on-demand instancing.

Realtime

Node.js WebSocket server

Long-lived Node process. Auth and game servers are separate — login can't take the game server down. Incremental update protocol keeps bandwidth low at scale.

Auth

PBKDF2-SHA512 · 210,000 iterations

64-byte keys. Session tokens hashed with SHA-256. Timing-safe comparison on every login. HttpOnly cookies with 7-day TTL. CORS-gated endpoints. Enterprise-grade security for a game project.

Persistence

SQLite + JSON state

Accounts and dev stats in SQLite (auth.sqlite). Per-game world state written to JSON on a 30s dirty-write timer. Schema versioned to V20 with backward-compatible migration path to V1.

Ops

Git-worktree orchestrator

Multi-version process management. Each version = isolated git worktree + Node process. Public WS gateway proxies to correct version. Crash recovery, backup-before-destructive-ops, compatibility-gated updates.

Testing

16 test files · 92 test cases

Every major server system has its own test file: economy, market, state, diplomacy, combat, government, species, technology, events, tactical-formation, ship-designs, versioning, auth-store, admin-commands, system-view, and system-view-store. All 92 pass before any merge. Catches balance regressions and protocol breaks before they ship to live games.

Analytics

Vercel Analytics

Lightweight client-side analytics on the React app for usage signals. No custom telemetry — keeps the codebase lean and privacy-safe.

Procedural gen

Galaxy · skybox · flags · planets

Star maps seeded per-game (500+ systems, procedural hyperlane graph). Perlin-noise skybox per scene — no texture assets. Faction flags generated via SVG from pattern + colour presets. Planet textures derived from class type. Zero art assets for environments.

Development progress

139 commits, Feb 26 – Jun 17 2026. The real story isn't the total — it's the shape: a slow start while the 3D prototype proved the concept, then a single month (May) that delivered 102 commits and the entire game engine. That's sustained focus: the commit log shows 8–10 pushes on individual days, week after week, for the entire month.

Commits by week · peak week: 31 commits (May 5–11)
0 15 30 Feb 26 2 Mar 1 1 Apr 13 Apr 20 5 Apr 27 2 May 4 10 May 11 31 ★ May 18 27 May 25 19 Jun 1 17 Jun 8 18 Jun 15 7 Jun 17 3 Feb Mar – mid Apr Apr May — 102 commits Jun (in progress)
Feb 26 – Jun 17, 2026  ·  139 commits  ·  16 test files  ·  92 test cases  ·  peak day: Jun 7 (14 commits — diplomacy, species, skybox, 3D models all shipped in one day)
10
Commits in a day
May 19 — ship designer revamp, fleet manager, tech icons, Cloudflare deploy fixes, admin commands, dev logging. All in one session.
14
Commits in a day
Jun 7 — diplomacy + wars + treaties, species system, government overhaul, procedural skybox, new 3D models, login page rewrite. One day.
92
Tests all passing
Jun 13 commit message: "all 83 tests pass" (count has since grown to 92). 16 test files covering every server system — no merge lands without a green suite.
V20
Schema versions shipped
State schema versioned from V1 to V20 across the build. Backward-compatible migration path means no live game is ever broken by a server update.
Feb 26, 2026 · 1 commit
"Initial commit: 3D space strategy prototype with seamless zoom"
Day one and already 3D — the first commit includes BabylonJS, seamless galaxy-to-system zoom, and the procedural star map. The architecture was established before any game logic was written.
Mar – Apr 2026 · 6 commits
Galaxy view, territory, star types, UI foundations
Low commit volume — deliberate. Apr 20–25: galaxy view revamp, improved star type rendering, territory system. The architectural decisions made here (server-side game loop, WS protocol shape) paid dividends when May hit.
May 3, 2026 · 9 commits in one day
Sprint starts: starbases, fog of war, ship functionality
May 3 alone ships fog-of-war prototype, ownership overlay renderer, player ship positioning, starbase system (added twice — once right, once better). The sprint doesn't stop here.
May 8–19, 2026 · 31+ commits — peak week
Full game engine: combat, fleet pathfinding, ship designer, tech tree
The core engine takes shape in one relentless stretch: fleet pathfinding + orbit system, planet economy integration, combat revamped three times until the range-band system felt right, ship designer rebuilt, tech tree added, admin command system. Eight commits on May 10, 11, and 12 independently.
May 25–31, 2026
Leaders, flags, market system, versioned state cache
Flags (procedural SVG generation), leader traits, economy balancing, market system shipped May 28. Same day: fleet order handling overhauled and tooltip manager added. May 26: gameplay state rewritten to versioned summaries with per-panel subscriptions — a significant architecture cleanup that stopped unnecessary re-renders.
Jun 7, 2026 · 14 commits — most productive single day
Diplomacy wars, species system, new skybox, 3D models, login rewrite
One day, across multiple PRs: full diplomacy system (wars, treaties, peace terms), species creator with rights/laws/pop groups, government window overhaul, new procedural space-3d skybox, new ship GLB models, login page rewritten and grounded in actual server code. This single day shipped more named features than most projects ship in a sprint.
Jun 13–17, 2026
All 92 tests green, events system, orchestrator finalised, gateway fix
Jun 13: "fixed issues 1, 2, and 8 — all 83 tests pass." Jun 14: events and situations system, shared interaction layer rebuilt for both galaxy and system scenes. Jun 15: orchestrator refactored to support multiple game versions with full isolation. Jun 17: WS gateway proxy binary-frame bug fixed and shipped to production.

Status

Actively in development and live at stellarfronts.com. The full loop — login, claim, explore, expand, run an economy, research, trade, persist — is wired end-to-end. Systems and balance are explicitly still a work in progress. Google and Microsoft OAuth endpoints are stubbed and return 501 until turned on. Next priorities: OAuth, balance passes, and expanding the content pool.

Play it. Read the code.

The game is live at stellarfronts.com. The full source — including the orchestrator, game server, auth server, and React client — is on GitHub.

Play Now View on GitHub