FLATLAND
⚖️ 213 laws 🌐 42 routes 🎯 7 presets
The Sphere sets laws, never a life 🌐 Landing Page ↗ 📄 Swagger /docs ← Demo

Flatland Wiki & Encyclopedia

> Landing Page: /

> Source Repositories: flws (Backend) · flws-web (Web Frontend) · flws-page (Landing Page)

> Developed by Long Phan ([email protected] · Demo: /demo/)

> Built and refined using OpenCode and Antigravity · Developed from the core ideas of *Edwin A. Abbott's Flatland: A Romance of Many Dimensions*** (1884).

Flatland is an autonomous 2D artificial life and world simulation developed from the foundational mathematical and spatial ideas of Edwin A. Abbott's 1884 classic Flatland.

Design Philosophy

This project is developed from the Flatland idea rather than mimicking the book literally. It adopts Abbott's core premises — 2D planar constraints, geometric vertex hierarchies, atmospheric perception, and higher-dimensional observation — as a foundation to create a living, evolutionary artificial life ecosystem that organically changes and expands over time.

Core Architecture & Systems

  • The Sphere (God Model): The Sphere (God) sets global laws of nature (carrying capacity, food growth, metabolism, disease, climate) from Spaceland, never intervening in individual lives. Configured via a dedicated 🎯 Presets selector and 6 streamlined ⚖️ Macro Domains with live search and dual sliders. Organisms navigate continuously via 16-sensor raycasts and Micro-RNN neural actuators.
  • Botanical Ecology & Functional Nutrition: 6 diverse plant species (grass, grain, berry, medicinal_herb, mushroom, poisonous) with distinct caloric densities, decay clocks, infection remedy effects, and targeted health-based foraging preferences.
  • Cognitive Agency & Clan Social Intelligence: Multi-objective utility AI replaces rigid if/else trees (evaluating survival, duty, traits, and kin needs); spatial waypoint mental maps; tactical soldier phalanxes, line kiting maneuvers, interpersonal trust-based buddy pairing, autonomous clan task boards (dynamic labor division), governance archetypes (Monarchy, Theocracy, Junta, Republic), adaptive bylaws (winter rationing, martial law), calculated Casus Belli, inter-clan trade caravans, and annual autumn harvest festivals.
  • Autonomous Evolution & Culture: 6 heritable personality archetypes (brave, cautious, altruistic, greedy, explorer, builder), craftable tools (spears, baskets, herb poultices, chieftain crowns), 4 mastery skills (Farming 🌾, Combat ⚔️, Foraging 🦴, Healing 🌿), earned dynamic titles, oral lore passed from elders to youth in houses, and live thought bubbles.
  • Realistic Energy & Metabolism: Infant low metabolism ($0.45\times$ energy decay), combat stamina expenditure, and autonomous field food reserve management via baskets.
  • Settlements & Diplomacy: Walled houses with creature-sized doors, multi-house clan territories, settlement food larders, mutual coalitions, tributary pacts, and schisms.
  • Geometric Physics & Morphological Evolution (K∈[3,24]): Polar genomes $(r_i,\phi_i)$ $K\in[3,24]$ (KMAX 24, morphology_engine.py) with SoA physical_traits trait baking ($A,P,I_{zz},\theta_{\min},asym,D_{mult}$) and SAT narrowphase (broadphase $r_{\max}$ + circle fallback $K\ge24$ & $asym<0.05$ + edge normals); annealing $\lambda(g)$ blends Abbott templates → free evolution, energetic asymmetry, neural courtship, and extinction safeguards ($\eta(N)$, Tier1/2/3 genesis, mercy).
  • Evolutionary Genome Mirror : Dynamic visual phenotype rendering where each creature's body, corolla aura, and chromatic luminescence directly mirror its living genome, generational depth (Gen 0 → 2000+), and physical mutations across millennia.
  • Real-Time Synchronization: Deterministic fixed-rate engine loop streaming state over WebSocket (/ws) at ~30–60 FPS with durable SQLite historical chronicle storage.

Flatland: The Novella vs. The Simulation

A comparative study between *Edwin A. Abbott’s 1884 satirical classic Flatland: A Romance of Many Dimensions*** and this autonomous artificial life simulation.

---

1. Caste, Geometry & Social Hierarchy

| Dimension | Abbott’s Book (Flatland, 1884) | Our Application (Flatland Simulator) |

| :--- | :--- | :--- |

| Hierarchy Principle | "Configuration makes the man." Social status is strictly determined by the number of sides and regularity of angles. | Entities inherit exact geometric castes based on vertex count (N-gons) and regularity. |

| Women (Lines) | Straight lines with no angular width. Because they are practically invisible head-on and razor-sharp, they are legally required to make a continuous "peace cry" and use dedicated side doors. | Rendered as 1D segments (shape: 'line'). Distinct agility, movement, and domestic shelter dynamics. |

| Working Class / Soldiers | Isosceles triangles with narrow, sharp vertex angles (dangerous, volatile, prone to rebellions). | Soldiers (#ff7b72): Sharp combatants with boosted attack, military discipline, and perimeter defense behavior. |

| Artisans & Middle Class | Equilateral triangles (3 equal sides) — stable and respectable tradespeople. | Artisans (3–4 sides, #f2cc60): Farmers, foragers, and builders responsible for harvesting and maintaining houses. |

| Gentlemen & Professionals | Squares (4 sides) and Pentagons (5 sides) — the middle/upper administrative classes. | Gentlemen (4 sides, #ffa657) and Professionals (5 sides, #d2a8ff): Administrative and specialized roles. |

| Nobility | Hexagons (6 sides) and higher polygons — aristocrats and statesmen. | Nobles (6–8 sides, #79c0ff): High influence and lineage priority. |

| Priesthood (Circles) | Polygons with so many sides (≥ 24 to hundreds) that their vertices are imperceptible, forming smooth circles. They govern religion, law, and morality. | Priests (≥ 24 sides, #e6edf3): Emit soothing auras, heal injured or infected clanmates, and resist disease. |

---

2. The "Law of Nature" & Generational Ascent

  • In the Book:
  • - Abbott establishes the "Law of Upward Development": A male child of a regular polygon almost always inherits one more side than his father (e.g., a Square fathers a Pentagon, whose son becomes a Hexagon), lifting the lineage toward circular Priesthood over generations.

    - Rare "Irregulars" (whose sides/angles do not match) are viewed as societal threats and sent to state institutions or executed.

  • In the App:
  • - Generational Evolution: Offspring inherit ancestral traits with a probabilistic side increment (sides += 1), simulating the gradual generational ascent toward circular perfection.

    - Irregularity & Demotion: Entities that develop genetic irregularity or undergo trauma have their irregularity tracked and are judged/demoted or marked with distinct visual indicators.

    - Dynastic Lineage: The Family Tree tracks mother, father, and generational pedigree across decades of world history.

---

3. Sight Recognition, Weather & Perception

  • In the Book:
  • - In a 2D world, all inhabitants look like flat lines from the edge!

    - In the Foggy South, Flatlanders rely on "Sight Recognition" — judging the angle and distance of an approaching polygon by how quickly its edges fade into the atmospheric fog.

    - In the Clear North, they must rely on "Feeling" (touching vertices with fingertips).

  • In the App:
  • - Dynamic Weather Engine: Simulates Clear, Fog, Rain, and Storm states.

    - Atmospheric Vision: Fog and storms dynamically restrict creature vision radii (sight_radius), forcing entities to rely on local spatial queries and nearby auditory alarms (signals).

    - Day/Night & Lighting: The ambient illuminance curves shift through dawn, noon, dusk, and pitch-black night, restricting wandering and driving creatures into their shelters.

---

4. Housing, Settlements & Territorial Architecture

  • In the Book:
  • - Houses are strictly pentagonal or hexagonal, with specific entrances: a smaller rear entrance for lines (women) and a main entrance for polygons.

  • In the App:
  • - Settlement Economy: Houses are physical 2D structures with precise interior boundaries, oriented doors (north, east, south, west), and bed capacities.

    - Single Main House Invariant: Each clan establishes exactly one Main House / HQ (the Leader's residence) with surrounding outpost shelters.

    - Shelter Dynamics: Creatures seek refuge inside houses to sleep at night, protect against winter frostbite, heal from chills, and educate infant offspring.

    - Doorway Entry & Exit Navigation: Creatures calculate vector standoff waypoints to transition smoothly through doorway openings when entering shelter at dusk or exiting to forage and explore at dawn, preventing indoor wall trapping.

---

5. Clan Diplomacy, Totems & Autonomous Society

While Abbott’s book portrays a centralized Victorian government, our app layers an evolutionary social simulation:

  • Sacred Avatars & Specialization: Each clan bears one of the 8 Sacred Avatars of the Sphere (⭕ Radiant Circle, ⚡ Celestial Strike, 👁️ All-Seeing Vertex, 🛡️ Indomitable Monolith, 🌿 Sacred Spiral, ⚖️ Cosmic Scales, 🌀 Dimensional Rift, 🕯️ Eternal Hearth), each granting a distinct divine buff and biasing the clan's balance of warriors, farmers, and scavengers.
  • Diplomacy, Tributes & War: Dynamic clan relations with wars, peace treaties, tribute subjugation, and schisms.
  • Personal Autonomy & Inventory: Independent personality archetypes (Brave, Cautious, Altruistic, Greedy, Explorer, Builder) with personal foraging baskets, tools (spears, crowns, herb poultices), and emergency self-preservation eating.

---

6. The Higher Dimension: The User as "The Sphere"

The most profound connection between the app and the book is the role of the user:

  • In Flatland, the protagonist A Square is visited by A Sphere from the 3D Spaceland, who can look down from the Z-axis, see into locked rooms, view internal organs, and manipulate the 2D world with god-like omnipresence.
  • In our App:
  • - You are the Sphere (God): As the observer on your screen, you look down on Flatland from Spaceland (the third dimension).

    - The Sphere Panel: You hold the power of The Sphere to alter the "Laws of Nature" in real-time — toggling famine, changing food growth multipliers, curing or spreading plagues, introducing winter freezes, or blessing clans with prosperity.


Configuration & ops

Env vars (FLATWORLD_*)

| Variable | Default | Description |

|---|---|---|

| FLATWORLD_WIDTH | 400 | World width (grid units) |

| FLATWORLD_HEIGHT | 300 | World height |

| FLATWORLD_BOUNDARY | wrap | wrap or clamp |

| FLATWORLD_SEED | 42 | RNG seed |

| FLATWORLD_TICK_RATE | 10 | Ticks per second |

| FLATWORLD_DB | backend/flatworld.db | SQLite path |

| FLATWORLD_GOD_KEY | — | Seed/override the god passkey at boot |

God passkey (auth)

POST /api/laws, POST /api/presets/{name}, POST /api/control and WebSocket control messages need the god passkey (X-God-Key header, key field on the socket). No credential yet → any god call answers 409 and the web UI asks to create one (POST /api/auth/setup). Lost it? Recover on the server only: cd backend && uv run python -m app.godkey reset <new> (or clear). The TUI takes no prompt: ./run.sh tui ws://host/ws <passkey> or export FLATWORLD_GOD_KEY. Only a PBKDF2 hash is stored.

Persistence (db.py:20)

SQLite flatworld.db (WAL, thread lock). Tables:

  • worlds(id, seed, width, height, boundary, started_at, ended_at)
  • events(id, world_id, tick, type, entity_id, caste, cause, x, y, payload, created_at)
  • law_changes(id, world_id, tick, name, value, created_at)
  • creatures(id, world_id, entity_id, caste, clan_id, generation, mother_id, father_id, born_tick, died_tick)
  • snapshots(id, world_id, tick, payload, created_at)

History survives restarts; reset closes old world row and opens new.

Concurrency stance & SimEngine

The simulation core is strictly deterministic (one seeded RNG stream, one fixed tick order). Run uvicorn with 1 worker (more workers = several disconnected worlds, not a faster one). Under SimEngine (main.py:446), simulation advancement runs on its own dedicated background OS thread. State stepping occurs under RT.lock while JSON snapshot serialization runs outside the lock (advance_world_lockless), so heavy state dumps and WebSocket broadcasts never block REST endpoints or hold the GIL. Key operational & diagnostic endpoints:

  • GET /healthz — Live server health, current TPS, memory usage, uptime, and active WebSocket client count.
  • GET /api/perf/telemetry — Rolling telemetry rings: tick duration, lock wait time, and broadcast latencies.
  • GET /api/analytics/summary — High-level macro demographics, biomass, and trophic distribution.

How the world works

The Sphere (God model): The Sphere (God) sets laws from Spaceland, never touches individual creatures. Everything else emerges.

The deterministic tick

s = Simulation(Config(seed))s.step() is fully deterministic (one random.Random per world). Same seed ⇒ same world. Tick loop (backend/app/simulation/core.py Simulation.step()) order: weather → plants → rebuild index → creatures → disease → war → reproduce → relations → food law → corpses → settlements → tick+=1. Simulation advances on a dedicated OS thread (SimEngine) with lockless serialization, streaming snapshots over WebSocket state every tick.

Life cycle & stages (§A)

Creature.age ticks + caste-based lifespan (Woman 4800 → Priest 9000). Stage by age/lifespan: infant <15%, juvenile <30%, adult <75%, else elder. Stage scales speed & sight (infant 0.6×, elder 0.85×) and fertility (elder ×0.5). Death causes: starvation, old_age, euthanasia, disease.

Health core (§AT-4 H-0)

Health is a resource, not a constant. Regeneration demands an energy surplus: below 40% of energy_max (HEALTH_REGEN_MIN_ENERGY) wounds stop closing — awake or asleep; sheltered rest heals at 0.15×rest_recovery_mult, waking regen is 0.1/tick (+Indomitable Monolith defense). Below 20% energy the body cannibalizes itself: −0.05 health/tick (HEALTH_SELF_DRAIN_*) until death by starvation — famine now kills twice. Weakness slows every stride (HEALTH_SPEED_TIERS): health <80 ×0.95, <60 ×0.85, <40 ×0.70, <20 ×0.50. Sickly bodies cannot beget children: mating requires health ≥ REPRO_MIN_HEALTH (50), so a plague suppresses births without touching birth laws.

Damage variety & healing economy (§AT-4 H-1)

Chronic hunger gnaws: below 20% energy for more than EXHAUSTION_TICKS 30 ticks drains EXHAUSTION_DRAIN 0.08 health/tick (death cause exhaustion). Age withers: elders lose ELDER_DECAY_RATE 0.02/tick passively. Sickness dims the eyes (HEALTH_SIGHT_TIERS: <60 ×0.90, <30 ×0.75) and blunts the harvest (_forage_mult: −20% under 60 HP, −50% under 30) so decline feeds on itself. The badly wounded (<30 HP) or grievously wounded never start a duel, though they can still be attacked; blows above WOUND_MIN_DAMAGE 15 leave a lingering wound (50–100 ticks, severity 1–2 by damage ≥40) that halves or quarters regen and hobbles speed (×0.85/×0.70). Where a body stands decides how fast it mends: waking regen runs at ×0.5 outdoors (REGEN_OUTDOOR_MULT) vs ×0.8 sheltered-awake vs full strength asleep indoors. And supper keeps working: berries set +0.3 health/tick for 20 ticks, grain +0.2×30, medicinal herbs +0.8×40 (FOOD_HEAL_BONUS) — a hurt creature even seeks herbs on a full stomach (herb targeting ignores the sated gate under 60 HP). Bodies differ in depth, too (CASTE_MAX_HP): Soldiers/Artisans pool 130 HP, Nobles/Predators 120, Women 110, Gentlemen/Herbivores 100, Professionals/Priests a delicate 90 — regeneration and healing cap at each body's own pool.

Physics axioms (§AQ PH-0)

Energy is the universal currency. Sunlight is the world's only income: _sun_factor() follows the day cycle — zero through the night, full strength at noon — and gates both plant growth and seed spread, so nothing grows for free in the dark (winter's bite remains the season table). Every body pays upkeep by its geometric complexity (METABOLIC_COST): triangles 1.0×, squares 1.1×, pentagons 1.2×, hexagons/nobles 1.3×, women and priests 1.5× (a priest burns energy maintaining the aura) — applied to the per-tick decay on top of stage/lifestyle multipliers. And mending is a conversion, not a miracle: each point of regenerated health costs HEALING_ENERGY_COST 0.5 energy (charged only when healing actually happens).

Thermodynamics & heat (§AQ PH-1)

A coarse ambient heat field (TEMP_CELL 25-unit cells, _update_temperature) relaxes toward a target each tick: the seasonal base (SEASON_BASE_TEMP spring 12° / summer 24° / autumn 8° / winter −4°) swept across the map from an edge — cold fronts enter from the west, warm fronts from the east — plus the day cycle (DAY_HEAT_AMPLITUDE ±5°), weather (rain −2°, storm −3°, fog −1°) and open flame (FIRE_HEAT 60° within 8 units). Every creature carries body_temp (on the wire) that drifts toward the local ambient at BODY_TEMP_DRIFT; standing indoors replaces ambient with indoor_ambient(), where the house material insulates (INSULATION_BY_MATERIAL: straw 0.15 < wood 0.35 < stone 0.55) toward HOUSE_COMFORT_TEMP 18°, and larger floors shed heat faster (HOUSE_REF_SIDE/size). Extreme heat is always physics: past HYPERTHERMIA_TEMP 36° health drains with the excess (HYPERTHERMIA_DRAIN) until death by hyperthermia. Extreme cold feeds §R chill below HYPOTHERMIA_TEMP 2° when the weather-sickness law is on.

Wind (§AQ PH-2)

The sky has a breath: a wind vector (wind_angle/wind_speed, on every snapshot payload) whose strength follows the weather — calm 0.25, rain 0.55, storm howls at 1.0 (WIND_*_SPEED, relaxed each tick) — and whose direction re-rolls near the season's prevailing bearing whenever the weather turns (WIND_SEASON_BIAS). Fire obeys it: both random ignition and plant-to-plant spread multiply by a tailwind factor (WIND_FIRE_MULT × speed × alignment), so flame races downwind while upwind groves stand longer.

Nature's Law inheritance (§B)

Sex: polygons male, lines female (entities.py:137). Sons sides = father.sides+1 capped at max_sides (24→Priest per new spec; K∈[3,24]); daughters lines. Mutation mutation_rate ±1 side → irregularity 0.3–1.0. Isosceles triangles: iso_angle+0.5° per generation, ≥60° promotes Soldier→Artisan. Fertility: per-caste table × crowding carrying_capacity/max_population. When morphology_annealing_enabled (morphology_engine), polar $(r_i,\phi_i)$ annealing supersedes side-count: $\lambda(g)$ blends Abbott template $K\in[3,24]$ with parental noisy genome, topo $p\cdot(1-\lambda)$.

Geometric Physics (Morphology Engine, K∈[3,24])

Polar genomes $K\in[3,24]$ SoA morph_radii/morph_angles/morph_k/physical_traits (A,P,I_{zz},\theta_{\min},asym,Dmult) — vectorized morphology_engine.py KMAX 24 (morphology.py shim). $\lambda(g)=morph\_lambda\_override ?? clamp(1-(g-g_{start})/g_{decay})$ (g_start 50 g_decay 150, override -1.0 = auto). Baking $E_{\max}\cdot clamp(A/A_{ref},0.5,2.5)$ $decay\cdot clamp(P/P_{ref},0.7,2.0)$ $steer\Delta\theta$ $D_{mult}$ $asym$→$irregularity$ with safeguard_morph_mercy ($\eta>0.3$ suspends euthanasia), SAT broadphase $r_{\max}$ + circle fallback ($K\ge24$ & $asym<0.05$) + edge normals + $D_{mult}$ impulse. Telemetry /api/metrics/morphology and /api/metrics/safeguards (N,\eta,tier,miracles,mercy) live.

World History, Chronicle & AI Storytelling (§BM)

Flatland features an end-to-end multi-era historiography, timeline analytics, and AI storytelling suite:

  • Major Moments & Chronicle Jumps: Top dramatic days (casualties, conquests, schisms) are automatically highlighted as jump chips above the chronicle feed. Users can jump directly to any specific tick timestamp.
  • Epoch Bar & Population Sparkline: Interactive temporal navigation with color-coded world epochs (Genesis, Age of Tribes, Feudal Era, Classical Zenith, Era of Ruin) and population curves overlaid with war and plague crisis markers.
  • Records & Legends Leaderboard: Hall of fame for Sovereign of War, Deadliest Single Day, Greatest Realm, Divine Architects, Largest Schism, and Hero/Villain notables.
  • History Analytics: Clan Rivalry Heatmap Matrix, Mortality Breakdown (combat, famine, disease, age) across 10-day eras, and Faith Devotion Index over time.
  • In-App AI Story Generator: Integrated browser-based LLM narrative generator using Google Gemini 1.5 Flash or OpenAI GPT-4o-mini with client-side API keys in localStorage. Supports 4 narrative styles (Saga, Chronicle, Mythos, Tragedy) in EN, VI, and FR.
  • Deep Linking: Shareable URLs with ?history=42 to auto-open specific world days or ?clan=7 to auto-open clan biographies.

Irregularity & caste (§C)

Mutated children's irregularity judged at adult_age: ≥euthanasia_threshold → consumed (euthanasia), else demoted to Soldier. CASTE_TRAITS (entities.py:39) gives lifespan/speed/sight_mult/fertility. BC maps $asymmetry$ → $irregularity$ for same gate.

Disease (§D)

disease_enabled, disease_outbreak_rate starts new disease_id, spreads within disease_radius at disease_rate (winter ×1.5), drains disease_energy_drain + health 2×disease_lethality, recovers recovery_rate. Disabling freezes instantly.

Environment (§E)

Clock from tick: time_of_day (day_length cycle, starts sunrise), day, season (season_length). Night night_sight_mult, fog fog_sight_mult stack. SEASON_FOOD_MULT spring 1.0/summer 1.2/autumn 1.0/winter 0.5; spring ×1.25 birth, winter ×1.5 disease. Weather FSM clear/rain/fog/storm at weather_change_rate: rain/storm rain_speed_mult, storm storm_wander_bonus.

Clans & social order (§C/I/P/V)

Settlements seed clans (§V): every non-ruin house founds a clan led by the founding creature nearest its centre, and every founding creature joins its nearest house's clan — soldiers, women, nobles and priests mix inside one settlement (simulation/settlement.py _found_founding_clans, deterministic given the seed). God law max_clans caps society granularity: -1 = one clan per house; N ≥ 1 clusters the founders into N spatial clans (greedy k-centre) instead — a pinned value applies at world creation. A clan's settlement IS its anchor house: claims match the clustering (_assign_house_claims/_claim_house_for_clan pick the free house nearest a clan's people, never round-robin), and territory/totem/crest anchor there. Children inherit mother's clan_id; orphans found new clans that settle at the nearest free house (or build one, §L). Procedural name (CLAN_ADJECTIVES/NOUNS) + Sacred Avatar of the Sphere (§AP: ⭕ Radiant Circle, ⚡ Celestial Strike, 👁️ All-Seeing Vertex, 🛡️ Indomitable Monolith, 🌿 Sacred Spiral, ⚖️ Cosmic Scales, 🌀 Dimensional Rift, 🕯️ Eternal Hearth — emoji on the map) if totems_enabled (config.py:59, simulation/theology.py AVATARS/TOTEM_BUFF, renderCore.tsx pole + shrine). Clan crest color on snapshot, totem pole + glowing shrine beside the main house, StateMessage.clans carries name/totem/faith/shrine_level/leader_id/color. Clan stats & history (§P): GET /api/clans roster with leader_id/population/house/war_wins/losses/territory_radius, polled by ClanPanel.tsx under trophic chart. Relations −100..+100 drift relation_drift_rate →0, threshold alliance_threshold/rivalry_thresholdalliance/rivalry events; shared feeding within flock_radius +2. Boids cohesion_weight/alignment_weight/separation_weight blended after food-seeking; social yielding YIELD_RADIUS 2.5. Territory (§P): each settlement anchors a territory_radius 14 circle (config.py:49, simulation/society.py _update_territory, CanvasRenderer.tsx:514) — members steer home when outside (0.35×steer), trespass inside a rival's circle sours relations trespass_decay (protocol.py:127) via _bump_relation. Totem buffs (§AP): eight Sacred Avatars with divine aspects — ⭕ Radiant Circle +30% harvest/+20% fertility, ⚡ Celestial Strike +25% warrior damage, 👁️ All-Seeing Vertex +40% sight + nocturnal clarity, 🛡️ Indomitable Monolith −30% damage/cold immunity, 🌿 Sacred Spiral herbs ×2/plague recovery/composting, ⚖️ Cosmic Scales reliable peace/refuses kin-eating, 🌀 Dimensional Rift faster promotion/adaptive mutation/elder lore, 🕯️ Eternal Hearth nocturnal calm. Theology (§AP): settled clans consecrate a shrine beside the main house (_update_faith); the devout tithe tithe_rate at dawn & dusk into the clan faith pool; the aura mends the faithful; faith overflowing at a season turn works a miracle (bloom + mending); temple_faith_cost raises a Temple whose aura covers all territory (temple event); when God sets laws every shrine chimes and priests preach doctrinal sermons (on_law_change from POST /api/laws); same/complementary-avatar clans sympathise (+1 relation, holy alliances); crisis ages convene the Great synod (+relations, sacred truce); and rarely an elder priest receives the 3D epiphany — all strife stills (truce_ticks). Leadership (§P): founder is leader_id (simulation/society.py), death triggers succession to oldest living member → succession event (protocol.py:129, simulation/lifecycle.py) if succession_enabled (config.py:54).

Food economy (§H/N/O)

Food is a living plant growth 0.15→1.0 (plant_growth_rate), spreads plant_spread_rate within SPREAD_RADIUS 6.0 if below seasonal bounty food_count×SEASON_FOOD_MULT. Winter die-back removes youngest first. A meal whose straight path is blocked by a rock circle or a house wall is abandoned for food_giveup_ticks — the hungry give up and seek food somewhere else instead of grinding against the obstacle until they starve; eating anything clears the grudge, 0 disables giving up (_segment_hits_circle, _give_up_on). Death leaves Corpse (corpse_ttl, corpse_energy) edible like food; decay boosts nearby plants NUTRIENT_BOOST×nutrient_cycle_rate within NUTRIENT_RADIUS. §O biodiversity: Food.variant grass/berry/mushroom/poisonous (entities.py:169) — plant_variants_enabled/poison_rate (config.py:44), VARIANT_ENERGY grass 32/berry 48/mushroom 24/poison 8 and VARIANT_HEALTH berry +1/poison -30 (simulation/constants.py), growth VARIANT_GROWTH_MULT×VARIANT_SEASON_MULT (simulation/ecology.py), spawn picks berry burst in autumn / mushroom on corpses/rocks (simulation/ecology.py), poisonous mutates via poison_rate; bloom carries variant (simulation/ecology.py). Wild herbivores (§O): Herbivore clanless grazers (entities.py:40, is_herbivore) spawn area×density×beast_ratio (config.py:46, simulation/lifecycle.py), graze plants and are hunted by predators (plants → herbivores → predators); beast_ratio/diet_strictness GodLaws (protocol.py:123). Diet & preference (§O): diet_strictness (config.py:46) filters perceived meals (simulation/creature_update.py) — herbivore ignores corpse when strict, predator ignores food, higher castes skip low-energy grass when strict (berry preferred), herbivore avoids poisonous; test_synergies.py:test_diet_preference_respects_strictness verifies.

Communication & knowledge (§Q/X)

Signals (§Q): food calls and alarm calls ripple within signal_radius; clan-mates respond strongly, strangers weakly. Knowledge (§X): creatures learn typed facts from experience — food spots seen/eaten, danger at predator sightings, safe roofs while sheltered, enemy clans that struck them (Creature.facts, decay after knowledge_ttl). Teaching: knowledge_share_rate chance/tick to broadcast the freshest fact to clan-mates; heard facts land at half confidence — retold knowledge is vaguer than firsthand sighting, only better news overwrites. Mobbing: an attacked creature emits a help call; clan-mates within help_radius converge on the attacker (warriors first via caste rank, the peaceful lag behind, high castes only when bold), and every defender inside earshot softens the attacker's blows by defense_weight. Clan memory: /api/clans surfaces each clan's remembered enemies/danger zones/food spots (clan_knowledge()), and clans that remember each other as enemies plot wars faster (§S foreshadowing). Full history (§AT-1): GET /api/clans/{id}/history?page=&size= paginates the clan's entire filtered event stream (newest first, total/has_more) alongside the internal milestone log; the durable chronicle filters by clan at the SQL level — GET /api/history?clan_id=N matches any clan-bearing payload key (a/b/clan_id/conquest/schism/takeover pairs) so events stay queryable after rolling off the in-memory deque; ClanDetails renders a lazy "Full History" panel with load older. Senses interact (§AR S-0): sleeping bodies are fully deaf — a sleeper never processes signals and never counts as a mob defender (_mob_defenders skips the asleep), so predators may stalk a silent village. Ripe plants smell through the dark: a hungry or starving creature with no visual target catches the scent of any mature plant (growth 1.0) within FOOD_SCENT_RADIUS 8.0 at night — blind starvation is cured by the nose. And starvation dulls fear: _effective_fear_radius halves fear_radius for the starving (traits paranoid +4 / bold −2.5 still apply first), so the desperate walk toward death chasing scented food.

Politics (§AB)

Coalitions: a leader folds friendly unaligned clans (relation ≥ coalition_threshold) into a named bloc (coalition_formed/coalition_joined); soured or shrunken blocs dissolve (coalition_dissolved). Mutual defence — strike one member and every mate's relations with the attacker sour −12, dragging them into the war. Leader agency: leaders act on their heritable trait — bold declares war on a remembered enemy (§X), peaceful sues for peace when weakened (peace event), paranoid betrays an ally (betrayal event + treason: false enemy knowledge seeded into nearby third clans). Strong clans demand tribute: vassals pay from their larder every 240 ticks (tribute events). Resource sharing: each settlement keeps a larder capped by larder_capacity — well-fed members deposit surplus, starving members withdraw; full-bellied allies top up starving allies at aid_rate. Defection: unhappy members (starving or homeless) walk to the healthiest nearby banner, even a rival's (defection events). /api/clans exposes coalition_id, larder, tribute_to; ClanPanel shows 🤝 pact / 🛡️ vassal / 🏺 larder chips. The leader is leverage (§AS L-0): kin within LEADER_AURA_RADIUS 15 of the living leader gain +10% sight (LEADER_SIGHT_BONUS), −5% energy burn (LEADER_DECAY_MULT) and a calmer hand (fear radius −1); with no living leader the whole clan glooms — sight −10%, burn +5% (LEADERLESS_DECAY_MULT), food gain ×0.85 (LEADERLESS_GAIN_MULT), bylaws and task boards pause, war declarations stop, and members drift cautious at LEADERLESS_CAUTIOUS_CHANCE. The death itself shocks: every member instantly loses 10 energy (LEADER_SHOCK_ENERGY), panics for 20 ticks (+0.3 flee urge), the larder loses 20% to looting, and a grey grief ripple marks the spot.

Desperation cannibalism (§AC)

Only the desperate eat the living: below cannibalism_hunger_ratio energy a creature perceives eligible prey — enemy-clan members (negative relation) and the weak (starving, elder, wounded) of any clan; never predators, wild beasts, infants or indoor refugees. On contact within eat_radius the prey dies (cause cannibalism), the eater gains cannibalism_energy and leaves a partial corpse, and a cooldown separates kills. Kin-eating carries a terrible price (eat_kin_enabled): the kin-slayer is exiled (exile_on_kin_eat) to found a one-being outcast band, witnesses remember the band as an enemy (§X), and relations between former clan and band sink by kin_stigma — rivalry, plots, war.

Food decay (§AE)

Nothing lasts forever: a mature plant lives food_lifespan_ticks × its variant's pace (mushroom 0.4×, grass ×1, berry 1.5×, poisonous 3×) before it withers — sprouts and growing plants never rot. Withered plants fade brown in the renderer, release half a corpse's nutrient boost to nearby plants (§H death feeds life), then vanish (wither events stay in-memory like blooms, never the DB). The bounty law respawns replacement growth, so plant counts now churn instead of freezing.

Shelter & Settlements (§L/N)

Houses (entities.py:184) squares with doorway; walls block except door — doorway too small for Carnivore predators (§L refuge) so houses are safe havens. Exposure exposure_drain outdoors in rain/storm or night unless indoors. Beds scale with floor area: house_capacity counts beds in an average 8×8 hall (HOUSE_REF_AREA), small huts have fewer beds, and large houses are strictly capped at 16 beds max (HOUSE_MAX_BEDS). Clans can settle across multiple houses, with the leader residing in the primary Main House marked with a golden crown. Abandoned houses decay to ruins (is_ruin). One house, one clan (§AT-2/AT-3): a creature sleeps only under its own clan's roof or an unclaimed one — _house_for() never returns a foreign house, so rival bodies cannot poison occupancy caps. A growing clan with no free roof may take over a weak rival's spare house (non-main, nobody sleeping there tonight, rival population under half its bed count — _try_house_takeover): the invader claims it outright, relations sour −25 and a takeover event hits the chronicle with an expanding crest-ring flash on the map; conquest-by-war transfers houses too (winner repoints the loser's seat). An audit pass each settlement tick (_audit_house_claims) clears claims whose clan died so no house ends a tick owned by a ghost.

Autonomous Evolution & Tools (§AG)

Evolution emerges 100% autonomously without god interventions:

  • Personality Archetypes: brave, cautious, altruistic, greedy, explorer, builder (65% heritability). Altruistic creatures feed starving kin with basket food.
  • Dynamic Equipment & Tools: Soldiers/Predators wield Spears (+20% combat damage & reach); Farmers/Artisans/Herbivores carry Baskets (haul up to 3 food units for field snacks or clan larder deposits); Priests carry Herb Poultices (+25 HP healing & infection cure); Chieftains wear the golden Crown.
  • Skill Mastery & Dynamic Titles: 4 skills (Farming 🌾, Combat ⚔️, Foraging 🦴, Healing 🌿) progress from Novice to Master, unlocking titles (the Slayer, the Fearless Champion, the Grand Harvester, the Wise Shaman, the Pathfinder).
  • Oral Lore: Elders sleeping in houses transmit their highest skill mastery XP to resting youth.
  • Floating Emote Thoughts: Real-time mood balloons (🍖, ❤️, ⚔️, 🌿, 🏆, 💤, 🧺, 😱) above creature heads.

Energy Dynamics & Stage Metabolism (§AH)

  • Stage-Aware Metabolism: Born infants burn 55% less energy per tick (0.45x), juveniles burn 25% less (0.75x), adults standard (1.0x), elders 0.85x.
  • Combat Stamina: Duels and war clashes expend energy (winner -6, loser -10); low energy (<20%) causes an exhaustion penalty (30% less damage).
  • Food Reserves & Field Eating: Roaming creatures with <45 energy autonomously eat carried food from their basket. Full creatures (>85% energy) never eat or destroy food plants.

Cognitive Agency & Clan Social Intelligence (§AL)

  • Multi-Objective Utility AI Engine: Dynamic utility scoring evaluating survival energy, caste duty, personality weights, and kin emergency signals.
  • Mental Map & Purposeful Waypoints: Coordinates for home, rich_food, danger, and patrol enable purposeful foraging and perimeter circuits over random Brownian noise.
  • Tactical Combat Formations: Allied Soldiers in combat align into disciplined phalanxes; 1D lines (women) execute evasive tangential kiting; outnumbered creatures execute organized retreats to shelter.
  • Interpersonal Trust Matrix: Pairs develop affinity from healing (+15) and feeding (+20), forming loyal buddy pairs for shared foraging.
  • Clan Division of Labor & Task Board: Dynamic macro priorities (balanced, food_security, defense, quarantine_healing) boost harvester (2.0×) and guard (2.5×) action weights.
  • Governance Archetypes: Distinct institutional succession models (Monarchy royal dynasty, Theocracy priest succession, Junta combat mastery, Republic council of elders).
  • Dynamic Bylaws: Automated policies including winter food rationing (<35 energy threshold) and wartime martial law curfews.
  • Macro Geopolitics & Casus Belli: Intentional war declarations based on famine food raids, blood feuds, and territorial friction with documented Casus Belli.
  • Inter-Clan Trade Caravans: Economic specialization barter transferring surplus grain from agrarian clans to martial clans in exchange for combat training and diplomatic goodwill (+12 relations).
  • Tribal Traditions & Harvest Festivals: Annual autumn celebrations at clan Main Houses boosting energy (+25), mood emotes, leader trust (+10), and oral lore transmission (+2.0 skill XP).

Food & Botanical Ecology (§AM)

  • Crop Diversity & Botanical Variants: 6 distinct flora species (grass, grain, berry, medicinal_herb, mushroom, poisonous).
  • Functional Nutrition:
  • - Golden Grain: Dense calorie staple (+45 Energy), slow decay rate ($2.5\times$ lifespan), foundational for settlement security.

    - Sun Berry: Energy burst (+48 Energy) and +15% movement speed surge.

    - Medicinal Herb: Healing remedy (+18 Energy, $+30\text{ HP}$), cures infections, grants heal emotes.

    - Fungi / Mushroom: Decomposer thriving near corpses, rocks, and during winter (+24 Energy).

  • Targeted Dietary Selection: Injured and infected creatures actively seek medicinal herbs (0.2× effective distance weighting); starving creatures seek golden grain (0.4× distance weighting).

Terminal User Interface (§AI)

A complete Textual terminal interface (backend/tui/) attaches to running worlds with:

  • Camera follow mode (w) tracking moving creatures.
  • Category-filtered Chronicle (t) (All, Birth, Death, War, Politics, Settlement).
  • Full creature dossier inspector (enter / i) and clan details modal (c).
  • God laws manager (g) and ASCII/half-block renderer (a / f).

Micro-Neural Network & Evolutionary Engine (BA)

Every creature carries a micro Elman RNN (16 → 12 → 7, 295 float32 weights, fixed) evolved by selection — always on. Sensors (16): vitals, three raycasts ±35°, audio, scent, collision, slope and hidden state. Outputs (7): thrust/steer (movement + energy drain), interact (consume/attack), social (mating readiness replaces §B gating), vocal_amp/vocal_freq, recurrent_out (writes hidden_state). Physics 60 Hz, inference at nn_inference_hz (default 15 Hz, every 4th tick latched, zero-alloc inputs_buf/outputs_buf). Genomes init N(0,0.5) clipped [-4,4]; mating via spatial query when energy > mate_energy_min and social > 0.5; uniform crossover 50/50 + Gaussian mutation N(0,0.08²) p=0.03 (mutation_sigma/crossover_rate laws). Always-on 295. See backend/app/agent_soa.py, neural_engine.py, agent_pipeline.py, evolution.py, sim_loop.py, spatial_grid.py.


Sustainability — Multi-Generational Balance

The world self-balances across hundreds of days and multi-generational dynastic flourishing under tuned ecological and social equilibrium.

Curated Presets

  • balance ⚖️ (Default) — Goldilocks harmony tuned for 200–350 inhabitants with 380 food, carrying capacity 400 (max 500), gentle wars, rare predation, agriculture, density damping ($\xi$), extinction safeguards ($\eta$), and flourishing multi-generational clans.
  • sustainable 🌿 — 1000-day prosperous peace: abundant food (550), carrying capacity 550 (max 600), rich granaries, harvest festivals, banquets, and gentle damping.
  • theocracy 🔮 — Age of the Sphere: sacred avatars, glowing temples, avatar miracles, 3D epiphanies, holy synods, and divine tithes.
  • warlords ⚔️ — Clash of clans: imperial conquests, granary raids, house takeovers, territorial expansion, and defensive coalitions.
  • chaos 🔥 — High predator ratio, lethal wars, wildfires, earthquakes, frequent plagues, and fast seasonal turnover.
  • extinction 💀 — Severe famine (120 food), harsh winter (0.30×), high exposure decay, testing societal resilience under collapse.
  • boom 🚀 — High reproduction, 440 food, carrying capacity 800 (max 850) for monumental metropolis testing.

Use: curl -X POST localhost:8000/api/presets/balance?reset=true or use The Sphere (God Panel) preset selector.

Dynamic Homeostasis & Extinction Prevention

Flatland includes two complementary closed-loop homeostatic feedback engines:

1. Density-Dependent Soft-Cap Damping ($\xi$)

When population $N$ exceeds carrying capacity $K_{cap}$, the overshoot ratio $\xi = (N - K_{cap}) / K_{cap}$ acts as a non-linear brake:

  • Birth Suppression: $R_{birth} = R_0 / (1 + \text{damping\_steepness} \cdot \xi^2)$
  • Crowding Metabolic Stress: $M_{decay} = M_0 \cdot (1 + \text{crowding\_stress\_mult} \cdot \xi)$
  • Resource Strain: Plant growth and spread slow down proportionally to ecosystem saturation.

2. Extinction Safeguards & Genesis Miracles ($\eta$)

When population drops below $K_{safe} = K_{cap} \times \text{safeguard\_relief\_ratio}$, emergency relief kicks in:

  • Tier 1 ($\eta \le 0.5$): Famine relief, metabolic energy discount up to 40%, plant growth acceleration up to 60%.
  • Tier 2 ($\eta > 0.5$): Critical relief, reproduction cooldown halved, infant euthanasia suspended (safeguard_morph_mercy).
  • Tier 3 ($N \le K_{crit}$): The Sphere intervenes with a Genesis Miracle, creating safeguard_genesis_batch pristine regular beings to ensure species survival.

Performance & Scale — 1000+ head @ 60 FPS

  • Zero-Allocation Spatial Hash: Pre-allocated 1D bucket list in world.py eliminates tuple allocations and dictionary re-hashing per tick; query_radius uses squared-distance early-exit without math.hypot.
  • Fast Mate Discovery: Spatial index queries nearby partners in $O(1)$ instead of $O(N^2)$ nested roster scans.
  • Snapshot Caching: Static terrain and obstacles are pre-cached, eliminating redundant dictionary list copies on every broadcast frame.
  • Batched Canvas 2D Rendering: Batches drawing passes by caste, plant variant, and house primitives with inline trigonometric vertex transforms, completely eliminating per-creature ctx.save() / ctx.restore() overhead (draw calls reduced from 20,000+ to ~30-50).
  • Dynamic Level of Detail (LOD): Zoom-dependent rendering skips fine-grained glyph text and ripples when zoomed out, maintaining 60 FPS even with dense populations.
  • Decoupled React State: High-frequency simulation snapshots stream directly into mutable refs at 60 FPS for canvas rendering, while React virtual DOM reconciliation (HUD stats, charts) is throttled to ~6 Hz to keep the main browser thread light and responsive.

Codebase map

Tri-Repository Architecture & Single-System Deployment (§BP)

Flatland is decoupled into three dedicated GitHub repositories with unified same-system deployment:

  • flws (github.com/longphanmn/flws): Backend simulation engine (FastAPI, SimEngine thread, NumPy SoA, micro-Elman RNN, polar geometry SAT, TUI, SQLite WAL). Listens on host port :8000.
  • flws-web (github.com/longphanmn/flws-web): Standalone web frontend simulation client (React 18, Vite, TypeScript, Canvas2D/WebGL 60 FPS viewport, Macro Observatory). Deployed to GitHub Pages (https://longphanmn.github.io/flws-web/) and runs on :5173 / :80 (Nginx reverse-proxying to backend).
  • flws-page (github.com/longphanmn/flws-page): Official project landing page and showcase (interactive canvas, audio synthesizer badge, lore). Deployed to independent GitHub Pages (https://longphanmn.github.io/flws-page/).
  • Same-System Orchestration: docker-compose.yml and deploy.sh deploy and run both backend and frontend on the same host system.

Backend (backend/app/)

  • config.py:13Config dataclass: world geometry, densities, food, corpses, behaviour, life, reproduction, disease, environment, shelter, terrain, society, houses, chronicle. from_env() + tick_interval.
  • entities.py:1CasteTraits, CASTE_TRAITS, YIELD_RANK, caste_name(), Creature (shape/sides/caste/age/lifespan/health/infected/clan_id/sleeping...), Food (growth), Corpse, House (size/door/clan).
  • world.py:32World registry + uniform spatial hash (cell_size, rebuild_index), delta/distance wrap-aware, query_radius.
  • simulation/ — Modular simulation package (§BI, replacing legacy simulation.py:335):
  • - core.pySimulation class, deterministic step loop, SoA slot sync, and cache refreshes.

    - creature_update.py — Decomposed 7-phase agent loop (_creature_movement, _creature_feeding, etc.).

    - settlement.py — Housing economy, construction, claims, takeovers, and wall collision.

    - lifecycle.py — Spawning, reproduction, birth, death, skill titles, and disease propagation.

    - ecology.py — Flora lifecycle, farming, banquets, corpse decomposition, and nutrient cycling.

    - theology.py — Faith pools, Sacred Avatars, shrines, miracles, synods, and epiphanies.

    - society.py — Clans, diplomacy, war, coalitions, larders, trade caravans, and cannibalism.

    - serialization.py — Wire snapshot and delta payload generation.

    - environment.py — Weather FSM, wind, temperature grid, elevation, and wildfires.

    - constants.py — Lookups, multipliers, names, and avatar configurations.

  • agent_soa.py — SoA buffers (pos/vel/genomes + morph_radii/angles/k/traits) vectorized.
  • agent_pipeline.py — Vectorized batch sensory raycasting and movement physics.
  • neural_engine.py — Micro-Elman RNN forward inference (16→12→7, 295 weights).
  • morphology_engine.py — Polar geometry SAT collision & physical trait baking.
  • evolution_manager.py — Annealing λ(g), Abbott templates K3..64, polar crossover.
  • spatial_grid.py — Vectorized spatial grid for fast proximity queries.
  • analytics.py — TelemetryRing, macro metrics, demography, biodiversity, timeseries.
  • safeguard_engine.py — Extinction safeguards & Genesis miracles.
  • density_damping.py — Soft-cap density damping (ξ).
  • auth.py:1require_god FastAPI dependency for God passkey PBKDF2 verification (X-God-Key).
  • protocol.py:7 — Pydantic wire schemas: ControlAction, ControlMessage, EntityState, StateMessage, HistoryEvent, HelloMessage, GodLaws.
  • db.py:1 — SQLite WAL persistence for worlds, events, lineage, and snapshots with write buffer.
  • main.py:1 — FastAPI app, SimEngine dedicated tick thread, Hub broadcaster, REST & WebSocket routes.

Frontend (frontend/src/)

  • App.tsx — Main application layout, HUD, WebSocket synchronization, mobile drawer tabs.
  • analytics/ — Macro Analytics Engine & Observatory:
  • - Observatory.tsx — Full-screen macro dashboard container with tabbed views.

    - MacroOverview.tsx — Demographics, vital health, biomass & speed sparklines.

    - SociologyTab.tsx — Clan hegemony, trade caravans, wars & succession tracking.

    - EcologyTab.tsx — Botanical diversity, soil health & trophic pyramid.

    - CrisisTab.tsx — Epidemic spread, starvation alerts & disaster log.

    - MutationLab.tsx — Morphological phylogeny tree & 2D morphospace scatterplot.

    - MetricCard.tsx / Sparkline.tsx — Lightweight SVG time-series visualizers.

  • render/CanvasRenderer.tsx — High-performance 60 FPS batched HTML5 Canvas renderer.
  • render/ClanPanel.tsx — Live clan settlements, totems, and war records.
  • render/ChronicleFeed.tsx — Filterable, scrollable real-time event log.
  • render/PlotsPanel.tsx — Multi-metric population, caste, and trophic sparklines.
  • clan/ClanDetails.tsx — Clan profile, leader residence, founded day & casualty tracking.
  • history/WorldHistoryModal.tsx — Daily chronicle digest, major wars, and AI Story export.
  • god/GodPanel.tsx — Interactive Laws of Nature drawer across 6 macro domains.
  • god/auth.tsx — God passkey modal dialog and authenticated fetch wrapper (godFetch).
  • inspect/Inspector.tsx — Creature dossier, polar morphology radar, vitals & family tree.
  • wiki/Wiki.tsx — In-app interactive wiki & API playground.
  • types.ts — TypeScript definitions mirroring backend protocol schemas.
  • websocket.ts — Auto-reconnecting WebSocket client.

Data flow

SimEngine (dedicated thread) → sim.step()sim.snapshot() (lockless serialization) → HUB.broadcastwsCanvasRenderer + App state. Client → ControlMessageapply_controlRT.config/RT.sim → DB law_changes. Events → DB.add_events + genealogy.


Data model & protocol

Entities (in-memory)

  • Creature (entities.py:95): id, x, y, angle, shape polygon|line, sides, caste, radius, age, lifespan, stage infant|juvenile|adult|elder, irregularity, health 0–100, infected, sex male|female, mother_id/father_id, clan_id/clan_color, sleeping/indoors, generation, born_tick, energy, status hungry/starving, meals.
  • Food (entities.py:158): x, y, growth 0–1.
  • Corpse (entities.py:170): x, y, ttl, energy.
  • House (entities.py:184): x, y, size, door_width/door_side/door_offset, clan_id/clan_color (settlement), is_ruin/abandoned_ticks, takeover_tick (last hostile takeover, §AT-3 render flash); ruin after house_decay_ticks (config.py:113), settlement/ruin/takeover events.
  • Terrain: fertile: [{x,y,r}], rocks: [{x,y,r}] in snapshot.

Wire schemas (protocol.py)

  • EntityState (protocol.py:27): id, kind creature|food|house|corpse, x/y/angle, plus optional fields above.
  • StateMessage (protocol.py:62): tick, seed, width/height/boundary, population, entities, clans, creatures_alive/creatures_dead/dead_by_cause, infected_count, time_of_day/day/season/weather, terrain_fertile/terrain_rocks, relations, events, plus periodic 1 Hz analytics frame (coalesced macro metrics).
  • HistoryEvent (protocol.py:86): type death|birth|promotion|demotion|outbreak|recovery|bloom|alliance|rivalry|predation|war|ruin|settlement, tick, entity_id, caste, cause, x/y, payload (parents/sides/generation/clan_id etc).
  • HelloMessage (protocol.py:99): seed, tick_rate, width/height/boundary.
  • ControlMessage (protocol.py:22): action pause|resume|step|reset|set_speed + value.

WebSocket flow

Server → client: {"type":"hello", ...} then {"type":"state", ...} each tick (with coalesced 1 Hz analytics frames for the Observatory). Client → server: {"action":"pause"|"resume"|"step"|"reset"|"set_speed", "value":...} (main.py).


Laws of the Sphere

Every law in GodLaws (protocol.py:108) with type/range/default. Set via POST /api/laws or presets.

LawTypeRangeDefaultHint + docs
boundarytyping.typing.Literal'wrap', 'clamp'wrapWorld border topology: wrap (seamless toroidal loop) vs clamp (solid collision walls). md
food_counttyping.int≥0, ≤2000210Living food plants maintained across the world (summer ×1.2, winter ×0.5). md
energy_maxtyping.float>1, ≤10000100.0Maximum metabolic energy capacity an organism can store (10–500). md
energy_decay_per_ticktyping.float≥0, ≤20.025Baseline metabolic burn rate per tick without food (0.025). md
energy_from_foodtyping.float≥0, ≤100032.0Base energy yield from harvesting a mature plant (berry 48, grass 32, mushroom 24, poison 8). md
plant_variants_enabledtyping.boolTrueMaster switch enabling botanical biodiversity across 6 distinct functional plant species. md
plant_growth_ratetyping.float≥0, ≤10.05How fast sprouted plants mature into harvestable food (0.045). md
plant_spread_ratetyping.float≥0, ≤10.006Probability per tick that a mature plant drops seeds into adjacent fertile ground (0.006). md
nutrient_cycle_ratetyping.float≥0, ≤100.65Acceleration of plant growth near decomposing corpses (0.65) — death nourishes new life. md
poison_ratetyping.float≥0, ≤10.01Probability a new wild sprout is poisonous (-30 HP damage on ingestion). md
food_decay_enabledtyping.boolTrueEnables mature plants to naturally wither over time and fertilize the living soil. md
food_lifespan_tickstyping.int≥100, ≤10000009000Ticks a mature plant lives before naturally withering into the living soil grid (8000). md
agriculture_enabledtyping.boolTrueEnables seed gathering, cultivated farm plots (2× growth, 2.5× yield), irrigation furrows, and tending. md
granaries_enabledtyping.boolTrueEnables communal settlement granaries to stockpile grain and berries against winter. md
granary_capacitytyping.float≥0, ≤100000400.0Units of food a settlement granary can store (400) — feasts fire at ≥80% capacity. md
perceive_radiustyping.float>0.5, ≤6020.0Base perception sight radius (16) — scaled by caste (Woman 0.8×, Priest 1.35×), night (0.6×), and fog (0.6×). md
eat_radiustyping.float>0.1, ≤101.4Physical contact distance required to consume a plant, corpse, or prey item (1.4). md
hungry_ratiotyping.float>0, ≤10.35Energy threshold (≤35%) feeding normalized energy into neural network input slot 0 to trigger foraging. md
starving_ratiotyping.float>0, ≤10.15Severe energy threshold (≤15%) triggering desperation sprint and pulsing survival distress. md
steer_turntyping.float≥0, ≤3.20.45Maximum heading angular turn agility per tick, scaled by creature moment of inertia Izz. md
birth_enabledtyping.boolTrueMaster switch enabling reproduction, mating, and generational ascendance. md
lifespan_multtyping.float≥0.01, ≤1001.0Multiplier scaling all caste lifespans (Woman: 4,800 ticks → Priest: 9,000 ticks). md
adult_agetyping.float≥0, ≤100000600.0Ticks required for an infant/juvenile to mature into a sexually fertile adult (220). md
birth_ratetyping.float≥0, ≤10.05Base reproduction probability per eligible adult mating pair per tick (0.28). md
carrying_capacitytyping.int≥-1, ≤10000-1Population density threshold above which fertility gradually fades (-1 = auto). md
max_populationtyping.int≥-1, ≤15000-1Hard global population cap preventing any new births until density declines (-1 = auto). md
mutation_ratetyping.float≥0, ≤10.05Probability a newborn son deviates ±1 side from classical caste inheritance (0.05). md
mutation_heritabilitytyping.float≥0, ≤10.35
sex_ratiotyping.float≥0, ≤10.5Probability a newborn child is a son (ascending polygon) vs daughter (agile line) (0.50). md
max_sidestyping.int≥3, ≤6424Upper limit on regular polygon vertex ascendance (up to Priest / Circle status) (24). md
euthanasia_thresholdtyping.float≥0, ≤10.7Irregularity threshold; deformed infants exceeding this are consumed at adulthood (0.70). md
mutation_sigmatyping.float≥0, ≤10.08Gaussian mutation standard deviation (σ) applied to genome weights during crossover (0.08). md
crossover_ratetyping.float≥0, ≤10.5Probability of uniform 50/50 parental genome blending during sexual reproduction (0.50). md
morphology_annealing_enabledtyping.boolTrueMaster switch for geometric physics — polar (r,φ) annealing, SAT polygon collision, and trait baking. md
annealing_start_generationtyping.int≥0, ≤100015
annealing_decay_generationstyping.int≥1, ≤5000250Generations over which polar morphology annealing decays from Abbott templates to free evolution (150). md
morph_lambda_overridetyping.float≥-1.0, ≤1.0None
vertex_mutation_stdtyping.float≥0, ≤0.50.025
angle_mutation_stdtyping.float≥0, ≤0.50.012
topological_mutation_ratetyping.float≥0, ≤0.20.008
safeguard_enabledtyping.boolTrue
safeguard_critical_poptyping.int≥2, ≤5012
safeguard_relief_ratiotyping.float≥0.05, ≤0.50.3
safeguard_genesis_batchtyping.int≥1, ≤206
safeguard_morph_mercytyping.boolTrue
safeguard_max_miraclestyping.int≥11
soft_cap_enabledtyping.boolTrue
damping_steepnesstyping.float≥1.0, ≤20.012.0
crowding_stress_multtyping.float≥0.0, ≤1.01.0
resource_strain_multtyping.float≥0.0, ≤2.02.0
boom_ramp_daystyping.float≥0, ≤1001.2
boom_birth_floortyping.float≥0, ≤1.00.4
boom_cooldown_multtyping.float≥1.0, ≤10.01.0
boom_energy_multtyping.float≥1.0, ≤10.01.0
initial_season_offsettyping.int≥0, ≤30
disease_enabledtyping.boolTrueMaster switch for infectious pathogen outbreaks and contagion transmission. md
disease_outbreak_ratetyping.float≥0, ≤16e-05Spontaneous plague outbreak probability per tick during crowded conditions (0.00006). md
disease_ratetyping.float≥0, ≤10.035Contagion transmission probability per tick within contact range (0.035). md
disease_energy_draintyping.float≥0, ≤100.05Metabolic energy drained per tick from actively infected creatures (0.05). md
disease_lethalitytyping.float≥0, ≤10.18Direct health (HP) damage dealt per tick to actively diseased creatures (0.18). md
weather_enabledtyping.boolTrueMaster switch for dynamic meteorological cycles (sun, rain, fog, storms). md
sleep_enabledtyping.boolTrueEnables diurnal sleep cycles, house resting, and oral lore transfer after dark. md
day_lengthtyping.int≥2, ≤2000001200Total duration in ticks of a single diurnal day/night cycle (1200). md
season_lengthtyping.int≥2, ≤100000014400Duration in ticks of each season (Spring, Summer, Autumn, Winter) (12000). md
winter_food_multtyping.float≥0.1, ≤20.5Winter seasonal food abundance multiplier (0.70 gentle, 0.50 harsh, 0.30 extinction). md
night_sight_multtyping.float≥0.05, ≤20.6Perception radius multiplier during night ticks for non-nocturnal castes (0.60). md
weather_change_ratetyping.float≥0, ≤10.002Frequency of meteorological transitions between clear, rain, fog, and storm (0.002). md
weather_sickness_enabledtyping.boolFalseEnables exposure chill and hypothermia when caught unsheltered in wet or freezing weather. md
chill_draintyping.float≥0, ≤50.18Direct health drain per tick when chilled outdoors without shelter (0.18). md
shelter_enabledtyping.boolTrueMaster switch for house claiming, door navigation, and roof protection. md
exposure_draintyping.float≥0, ≤100.03Health and energy drain per tick when outdoors during harsh weather (0.025). md
house_capacitytyping.int≥1, ≤6412Bed capacity inside a settlement hall (12); excess members sleep outdoors. md
house_decay_tickstyping.int≥100, ≤1000002400Ticks before an abandoned, roofless house crumbles into ruins (10000). md
rest_recovery_multtyping.float≥0, ≤102.0Health regeneration multiplier when sleeping indoors under a roof (2.0). md
territory_enabledtyping.boolTrueEnables clan boundary markings, territory defence, and trespass penalties. md
territory_radiustyping.float≥1, ≤5014.0Radius of clan territorial influence around settlement houses (16). md
trespass_decaytyping.float≥0, ≤50.25Diplomatic relation points lost per tick when a rival clan enters marked territory (0.15). md
max_clanstyping.int≥-1, ≤64-1Maximum number of sovereign clans spawned during world initialization (-1 = auto). md
totems_enabledtyping.boolTrueEnables Sacred Avatar totem blessings for each clan settlement. md
succession_enabledtyping.boolTrueEnables dynamic governance leadership transfers on chieftain death. md
communication_enabledtyping.boolTrueEnables vocalizations, alarm chirps, peace hums, and emotional thought bubbles. md
knowledge_enabledtyping.boolTrueEnables spatial memory, waypoint mapping, and rumor broadcasting among kin. md
schism_enabledtyping.boolTrueEnables internal clan fractures when members starve or lack shelter. md
schism_thresholdtyping.float≥0, ≤10.5Dissatisfaction fraction (hunger, homelessness) triggering a factional clan schism (0.40). md
war_enabledtyping.boolTrueEnables inter-clan warfare, tactical raids, and territorial conquest. md
attack_damagetyping.float≥0, ≤100030.0Base damage dealt by soldiers and warriors in inter-clan battles (32.0). md
predation_enabledtyping.boolFalseEnables carnivorous predator-prey ecology and hunting dynamics. md
predator_ratiotyping.float≥0, ≤10.0Fraction of population spawned as predatory carnivores hunting prey (0.02). md
hunt_radiustyping.float≥1, ≤408.0Aggro detection radius within which carnivores and war parties acquire targets (16.0). md
bite_damagetyping.float≥0, ≤100028.0Combat damage dealt per carnivore attack or predatory strike (28.0). md
energy_from_preytyping.float≥0, ≤100040.0Caloric energy extracted from slaying and eating a prey creature (45.0). md
fear_radiustyping.float≥1, ≤4012.0Distance at which herbivores and vulnerable castes detect threats and execute evasion (12.0). md
coalitions_enabledtyping.boolTrueEnables mutual defensive alliances and diplomatic treaties between friendly clans. md
coalition_thresholdtyping.int≥-100, ≤10040Diplomatic trust score required for two friendly clans to form a defensive coalition (40). md
leader_decisions_enabledtyping.boolTrueEnables chieftain governance bylaws (rationing, martial law, war declarations). md
resource_sharing_enabledtyping.boolTrueEnables communal settlement larders and altruistic basket food sharing. md
larder_capacitytyping.float≥0, ≤5000300.0Energy capacity of settlement communal food stores where surplus is shared (300). md
cannibalism_enabledtyping.boolTrueEnables desperate consumption of the living during extreme starvation. md
eat_kin_enabledtyping.boolTrueAllows consumption of deceased or weak clanmates at the cost of tribal exile and feuds. md
cannibalism_energytyping.float≥0, ≤100035.0Energy gained by starving creatures resorting to eating fallen kin or rivals (45.0). md
theology_enabledtyping.boolTrueEnables the 8 Sacred Avatars, shrines, temples, miracles, and divine tithes. md
tithe_ratetyping.float≥0, ≤10.04Fraction of energy devout worshippers offer at shrines each dawn & dusk to build clan faith (0.04). md
temple_faith_costtyping.float≥0, ≤100000400.0Faith points required to consecrate a glowing Temple of the Sphere (400.0). md
age_enabledtyping.boolTrueEnables historical epoch progression (Golden Age, Ice Age, Age of Chaos, Age of Plague). md
age_lengthtyping.int≥100, ≤100000012000Duration in ticks per world historical epoch (50000). md
culture_enabledtyping.boolTrueEnables traditions, governance archetypes, and cultural diffusion. md
culture_spread_ratetyping.float≥0, ≤10.005Rate at which allied clans sharing borders adopt common cultural traits and beliefs (0.0005). md
rivers_enabledtyping.boolTrueEnables water channels, fords, water currents, bridges, and dams. md
river_counttyping.int≥0, ≤82Number of procedural river channels carved across the terrain at world generation (2). md
relief_enabledtyping.boolTrueEnables topographical elevation, slope inertia, cliffs, and road packing. md
structural_enabledtyping.boolTrueEnables weather wear on buildings, builder repairs, and roof collapse into rubble. md
earthquake_enabledtyping.boolFalseEnables seismic tremors that shake terrain and damage weakened structures. md
earthquake_ratetyping.float≥0, ≤0.018e-05Frequency of seismic quakes that crack buildings and shake terrain (0.00008). md
lightning_enabledtyping.boolTrueEnables real lightning strikes during storms that ignite fires and damage creatures. md
lightning_strike_ratetyping.float≥0, ≤0.050.0015Frequency of deadly electrical arc strikes during thunder storms (0.0015). md
wildfire_enabledtyping.boolTrueEnables combustive flame propagation across dense vegetation and forests. md
fire_ratetyping.float≥0, ≤0.058e-05Probability per tick that a mature plant ignites during dry spells or lightning strikes (0.00008). md
disaster_enabledtyping.boolTrueEnables cataclysmic meteors, floods, and natural world disturbances. md
disaster_ratetyping.float≥0, ≤0.054e-05Stochastic probability of catastrophic environmental disasters (0.0003). md
anomaly_counttyping.int≥0, ≤83Number of mysterious spatial anomaly zones altering local physics (3). md
door_clearancetyping.float≥1, ≤51.5Width multiplier for house doorways relative to the largest creature size (1.5). md
house_min_sizetyping.float≥3, ≤605.5
house_max_sizetyping.float≥3, ≤808.0
aid_ratetyping.float≥0, ≤10.05
alarm_call_ratetyping.float≥0, ≤10.12
alignment_weighttyping.float≥0, ≤100.0
alliance_thresholdtyping.int≥-100, ≤10050
attack_radiustyping.float≥0, ≤101.8
banquets_enabledtyping.boolTrue
beast_ratiotyping.float≥0, ≤10.0
betrayal_enabledtyping.boolTrue
birth_energy_costtyping.float≥0, ≤100020.0
bite_cooldowntyping.int≥0, ≤100015
cannibalism_hunger_ratiotyping.float≥0, ≤10.08
chill_ratetyping.float≥0, ≤100.04
chill_thresholdtyping.float≥0, ≤100012.0
coalition_min_sizetyping.int≥1, ≤1002
cohesion_weighttyping.float≥0, ≤100.0
corpse_energytyping.float≥0, ≤100025.0
corpse_ttltyping.int≥0, ≤100000600
corpses_enabledtyping.boolTrue
creature_densitytyping.float≥0, ≤100.0013
defection_enabledtyping.boolTrue
defense_weighttyping.float≥0, ≤100.5
desperate_perceive_multtyping.float≥1, ≤101.6
desperate_speed_multtyping.float≥1, ≤101.35
dialect_drift_enabledtyping.boolTrue
diet_strictnesstyping.float≥0, ≤10.0
disease_radiustyping.float≥0, ≤1003.0
eat_enemy_enabledtyping.boolTrue
energy_starttyping.float≥0, ≤100085.0
envoys_enabledtyping.boolTrue
exile_on_kin_eattyping.boolTrue
fertile_food_biastyping.float≥0, ≤100.7
fertile_patchestyping.int≥-1, ≤1000-1
fire_spread_ratetyping.float≥0, ≤100.035
flock_radiustyping.float≥0, ≤1006.0
fog_mushroom_multtyping.float≥0, ≤101.35
fog_sight_multtyping.float≥0, ≤100.6
food_call_ratetyping.float≥0, ≤10.08
food_giveup_tickstyping.int≥0, ≤100000240
hearths_enabledtyping.boolTrue
heighttyping.float≥10, ≤10000300.0
help_call_enabledtyping.boolTrue
help_radiustyping.float≥0, ≤10012.0
history_maxtyping.int≥0, ≤1000000200
house_claim_enabledtyping.boolTrue
house_densitytyping.float≥0, ≤10.00065
house_gaptyping.float≥0, ≤1006.0
hungry_perceive_multtyping.float≥1, ≤101.3
kin_stigmatyping.float≥0, ≤100040
knowledge_share_ratetyping.float≥0, ≤10.05
knowledge_ttltyping.int≥0, ≤1000000600
markets_enabledtyping.boolTrue
mate_energy_mintyping.float≥0, ≤100030.0
mate_radiustyping.float≥0, ≤10010.0
nn_inference_hztyping.int≥1, ≤100015
num_hexagonstyping.int≥-1, ≤100-1
num_housestyping.int≥-1, ≤100-1
num_pentagonstyping.int≥-1, ≤100-1
num_prieststyping.int≥-1, ≤100-1
num_squarestyping.int≥-1, ≤100-1
num_trianglestyping.int≥-1, ≤100-1
num_womentyping.int≥-1, ≤100-1
omens_enabledtyping.boolTrue
omp_enabledtyping.boolTrue
omp_thresholdtyping.int≥0, ≤10000100
rain_growth_multtyping.float≥0, ≤101.25
rain_speed_multtyping.float≥0, ≤100.85
recovery_ratetyping.float≥0, ≤10.03
relation_drift_ratetyping.float≥0, ≤102.2
reproduction_cooldowntyping.int≥0, ≤100000600
rivalry_thresholdtyping.int≥-100, ≤100-75
rock_counttyping.int≥-1, ≤1000-1
rubble_blocking_enabledtyping.boolTrue
scent_enabledtyping.boolTrue
schism_min_poptyping.int≥1, ≤10006
seedtyping.int≥042
separation_weighttyping.float≥0, ≤100.0
signal_radiustyping.float≥0, ≤10012.0
signal_speedtyping.float≥0, ≤1008.0
sleep_energy_multtyping.float≥0, ≤100.5
soil_depletion_enabledtyping.boolTrue
spawn_variancetyping.float≥0, ≤1000.25
storm_plant_damagetyping.float≥0, ≤100.02
storm_wander_bonustyping.float≥0, ≤100.35
tick_ratetyping.float≥0.1, ≤100010.0
trait_mutation_ratetyping.float≥0, ≤10.02
tribute_enabledtyping.boolTrue
vocalizations_enabledtyping.boolTrue
wander_turntyping.float≥0, ≤100.35
wet_disease_multtyping.float≥0, ≤101.5
widthtyping.float≥10, ≤10000400.0

Presets — one-click worlds

Sustainable is the 1000-day gentle world. Apply via The Sphere panel or POST /api/presets/{name}?reset.

PresetKey lawsApply
balance ACTIVEboundary=wrap, door_clearance=1.5, food_count=380, plant_growth_rate=0.065, plant_spread_rate=0.008, nutrient_cycle_rate=0.65 … +179 moreVia the app UI or TUI
sustainableboundary=wrap, door_clearance=1.5, food_count=550, plant_growth_rate=0.08, plant_spread_rate=0.01, nutrient_cycle_rate=0.85 … +179 moreVia the app UI or TUI
chaosboundary=wrap, door_clearance=1.5, food_count=320, plant_growth_rate=0.045, plant_spread_rate=0.006, nutrient_cycle_rate=0.65 … +179 moreVia the app UI or TUI
extinctionboundary=wrap, door_clearance=1.5, food_count=120, plant_growth_rate=0.025, plant_spread_rate=0.003, nutrient_cycle_rate=0.5 … +179 moreVia the app UI or TUI
boomboundary=wrap, door_clearance=1.5, food_count=440, plant_growth_rate=0.06, plant_spread_rate=0.012, nutrient_cycle_rate=0.85 … +179 moreVia the app UI or TUI
theocracyboundary=wrap, door_clearance=1.5, food_count=400, plant_growth_rate=0.055, plant_spread_rate=0.007, nutrient_cycle_rate=0.7 … +179 moreVia the app UI or TUI
warlordsboundary=wrap, door_clearance=1.5, food_count=340, plant_growth_rate=0.05, plant_spread_rate=0.006, nutrient_cycle_rate=0.65 … +179 moreVia the app UI or TUI

API reference

Live routes from app.routes + Swagger at /docs. Try curl examples below.

RouteName
/ws
GET /api/analytics/hegemonyget_analytics_hegemony
GET /api/analytics/summaryget_analytics_summary
GET /api/analytics/timeseriesget_analytics_timeseries
GET /api/analytics/trophicget_analytics_trophic
GET /api/analytics/warningsget_analytics_warnings
GET /api/annalsget_annals
GET /api/auth/statusauth_status
GET /api/clan/{clan_id}/biographyget_clan_biography
GET /api/clans/{clan_id}/historyget_clan_history
GET /api/clans/{clan_id}get_clan
GET /api/clansget_clans
GET /api/configget_config
GET /api/creature/{creature_id}get_creature
GET /api/history/summaryget_history_summary
GET /api/historyget_history
GET /api/lawsread_laws
GET /api/metrics/dampingget_damping_metrics
GET /api/metrics/morphologyget_morphology_metrics
GET /api/metrics/safeguardsget_safeguards_metrics
GET /api/perf/telemetryget_telemetry
GET /api/presetslist_presets
GET /api/stateget_state
GET /api/versionget_version
GET /api/wikiget_wiki_json
GET /api/worldsget_worlds
GET /guideget_guide
GET /health.htmlhealth_dashboard
GET /healthhealth_dashboard
GET /healthzhealthz
GET /robots.txtget_robots_txt
GET /sitemap.xmlget_sitemap_xml
GET /wikiget_wiki
POST /api/auth/setupauth_setup
POST /api/controlpost_control
POST /api/lawswrite_laws
POST /api/presets/{name}apply_preset

Curl playground


# laws
curl localhost:8000/api/laws
curl -X POST localhost:8000/api/laws -H 'content-type: application/json' -d '{"food_count": 90}'

# presets (1000-day one click)
curl -X POST localhost:8000/api/presets/sustainable?reset=true
curl -X POST localhost:8000/api/presets/chaos
curl -X POST localhost:8000/api/presets/extinction?reset=true

# state & history
curl localhost:8000/api/state | jq .tick
curl localhost:8000/api/history?limit=5 | jq
curl localhost:8000/api/worlds | jq
curl localhost:8000/api/clans | jq

# control
curl -X POST localhost:8000/api/control -H 'content-type: application/json' -d '{"action":"pause"}'
curl -X POST localhost:8000/api/control -d '{"action":"reset"}'

# websocket (live)
# ws://localhost:8000/ws  → {"type":"hello"} then {"type":"state"} throttled ~30Hz
# send {"action":"pause"} / {"action":"set_speed","value":20}

Configuration & ops

Env vars (FLATWORLD_*)

| Variable | Default | Description |

|---|---|---|

| FLATWORLD_WIDTH | 400 | World width (grid units) |

| FLATWORLD_HEIGHT | 300 | World height |

| FLATWORLD_BOUNDARY | wrap | wrap or clamp |

| FLATWORLD_SEED | 42 | RNG seed |

| FLATWORLD_TICK_RATE | 10 | Ticks per second |

| FLATWORLD_DB | backend/flatworld.db | SQLite path |

| FLATWORLD_GOD_KEY | — | Seed/override the god passkey at boot |

God passkey (auth)

POST /api/laws, POST /api/presets/{name}, POST /api/control and WebSocket control messages need the god passkey (X-God-Key header, key field on the socket). No credential yet → any god call answers 409 and the web UI asks to create one (POST /api/auth/setup). Lost it? Recover on the server only: cd backend && uv run python -m app.godkey reset <new> (or clear). The TUI takes no prompt: ./run.sh tui ws://host/ws <passkey> or export FLATWORLD_GOD_KEY. Only a PBKDF2 hash is stored.

Persistence (db.py:20)

SQLite flatworld.db (WAL, thread lock). Tables:

  • worlds(id, seed, width, height, boundary, started_at, ended_at)
  • events(id, world_id, tick, type, entity_id, caste, cause, x, y, payload, created_at)
  • law_changes(id, world_id, tick, name, value, created_at)
  • creatures(id, world_id, entity_id, caste, clan_id, generation, mother_id, father_id, born_tick, died_tick)
  • snapshots(id, world_id, tick, payload, created_at)

History survives restarts; reset closes old world row and opens new.

Concurrency stance & SimEngine

The simulation core is strictly deterministic (one seeded RNG stream, one fixed tick order). Run uvicorn with 1 worker (more workers = several disconnected worlds, not a faster one). Under SimEngine (main.py:446), simulation advancement runs on its own dedicated background OS thread. State stepping occurs under RT.lock while JSON snapshot serialization runs outside the lock (advance_world_lockless), so heavy state dumps and WebSocket broadcasts never block REST endpoints or hold the GIL. Key operational & diagnostic endpoints:

  • GET /healthz — Live server health, current TPS, memory usage, uptime, and active WebSocket client count.
  • GET /api/perf/telemetry — Rolling telemetry rings: tick duration, lock wait time, and broadcast latencies.
  • GET /api/analytics/summary — High-level macro demographics, biomass, and trophic distribution.

Run & deploy


./run.sh
# or
cd backend && uv run uvicorn app.main:app --reload --port 8000
cd frontend && npm run dev

Tests


cd backend && uv run pytest -q
cd backend && uv run pytest tests/test_synergies.py -q

Roadmap

See TODO.md (active) + docs/roadmap-archive.md (completed) — 13 sections + 213 laws + 42 routes + 7 presets. Wiki extends Guide with presets, sustainability & playground.


Generated from live code — Config defaults + GodLaws + app.routes. Official living documentation & encyclopedia for Flatland. · Developed by Long Phan[email protected] · Demo: Demo ↗ · Landing: Landing ↗ · GitHub: flws / flws-web · Built with OpenCode & Antigravity