BlueGit

timfa questward

Files

questward / tile_mmo_server_technical_design_v0.6.md

tile_mmo_server_technical_design_v0.6.md

tile_mmo_server_technical_design_v0.6.md 140.4 KiB Download Raw

--- title: Tile MMO Server Technical Design version: 0.20 status: proposed format: living-design-document ---

Tile MMO Server Technical Design

Version: 0.20 Status: Proposed architecture; intended to be iterated as implementation decisions are made. Scope: Authoritative Node.js/ECS backend, FrameworkV3-based game client (16×16 sprites, player-centered viewport), chunk/region streaming, SQLite persistence, admin world editor with per-chunk changelogs, player inventory and items, combat, player communication, banking/cheques, shopkeepers, marketplace/economy systems, skill progression, automatic restart/update orchestration, and future player scripting hooks.

1. Design goals

  • Support a large tile-based MMO world without simulating unused areas.
  • Keep the server fully authoritative: clients send actions and

intentions, never authoritative state changes.

  • Authenticate accounts via auth.timfalken.com (with an admin-<n> stub

until that service is live). An account may have unlimited characters, one in the world at a time, with delayed deletion and an inheritance bank tab.

  • Use ECS composition for entities and systems, while using chunks and

regions for spatial ownership and simulation lifecycle.

  • Allow simulation work to scale across Node.js workers and permit

entities to cross worker-managed region boundaries safely.

  • Keep client replication small: a player receives only the current

16×16 chunk and the eight neighbouring chunks.

  • Keep authored world data separate from ephemeral simulation state.
  • Persist only entities that explicitly need persistence; ordinary

spawned mobs disappear when their chunk is unloaded.

  • Avoid constant chunk writes. Normal chunk persistence occurs on

unload; graceful shutdown is implemented as a forced unload of all resident chunks.

  • Provide an admin-only graphical world editor for painting tiles,

opening or closing chunks, and placing/configuring spawners, with a per-chunk changelog of who changed what and when. Unedited chunks are grass-only and closed.

  • Automatically schedule a graceful midnight restart when live code or

authored world data changes, with an admin-triggered immediate restart path.

  • Reserve a clean control abstraction for a later sandboxed player

scripting language without requiring the scripting system in the initial release.

  • Build the player-facing client on the shared FrameworkV3 library, vendored

as a git submodule and built first so game-specific client code can layer on top of it, while keeping the server-side ECS an implementation detail of the backend. World sprites may be any size; each uses a centred pivot 8 pixels from the sprite bottom. The play viewport stays centered on the local player.

  • Authoritative movement is tile-to-tile at a global walk/run cadence

(default walk 2 tiles/s, run double), not a per-mob speed. Admins edit that cadence and other tick timers in a world-settings modal. Saving those settings applies immediately to the live world. World calendar time is server time minus 1200 years. At night the client darkens unlit tiles (how dark is a world setting); static light reach is baked by raycast when a chunk is saved.

  • Give every player a 32-slot inventory in which stackable items occupy a

single slot, and treat dropped items as temporary, non-blocking ground objects rather than tile occupancy.

  • Make ordinary communication spatial rather than global: nearby speech is

progressively degraded by distance, while long-distance exchange is a physical item or currency delivery by carrier pigeon. A letter is simply a paper item with player-written text.

  • Support persistent player groups without turning them into an instant

long-distance chat channel.

  • Provide a shared, unlimited player bank near the marketplace, with later

banks all reading the same vault, plus bearer cheques and free pigeon deposits.

  • Make the central marketplace an order-matching service rather than a public

auction list, with durable escrow and asynchronous pigeon delivery.

  • Keep the economy predominantly player-driven: most ingredients are gathered,

final goods are normally crafted by players, and finished-item drops come from enemies/bosses rather than ordinary NPC shops.

  • Let every combatant — players and other mobs — attack. Melee requires an

adjacent tile including diagonals; ranged attacks and spells use the range of the weapon or spell. A hit roll uses the weapon skill; damage uses Strength, Dexterity or Mind. Attack XP is split equally between those two skills.

  • Let shop NPCs sell items at a seed value that lerps toward the last

player-market sale price over a configurable duration (default one hour), with a hidden per-shop discount. Item inspection shows name, description, origin and the undiscounted current value, refreshed at most once per minute.

  • Use skill-based progression with no player classes. Every gameplay action is

governed by a skill and awards XP to that skill when successfully performed. Combat is the explicit dual-skill exception: hit skill and damage skill share the XP.

2. Core world model

2.1 Spatial hierarchy

World └── Region: 4 × 4 chunks └── Chunk: 16 × 16 tiles └── Tile

One chunk contains 256 tiles. One region is 64×64 tiles and contains 16 chunks (4,096 tiles). World tile coordinates are canonical; chunk and region coordinates are derived from them.

chunkX = floor(tileX / 16) chunkY = floor(tileY / 16) regionX = floor(chunkX / 4) regionY = floor(chunkY / 4)

If negative world coordinates are allowed, use true floor division rather than JavaScript integer truncation.

2.2 Three independent spatial states

The design deliberately separates region residency, chunk simulation, and client visibility.

ConcernUnitMeaning
ResidencyRegionWhether the region and its required chunk data exist in server memory and have a worker owner.
SimulationChunkWhether ECS systems actively simulate entities and gameplay in this chunk.
VisibilityChunkWhether a specific client is subscribed to the chunk and receives its snapshot/deltas.

2.3 Region states

UNLOADED ↓ load RESIDENT ↓ no residency references + grace period UNLOADED

A resident region is assigned to exactly one simulation worker. An unloaded region has no active ECS representation.

2.4 Chunk states

DORMANT ⇄ SIMULATING

A dormant chunk can remain resident in memory while normal gameplay systems ignore it. A simulating chunk participates in movement, combat, AI, spawners and other active systems.

3. Tile layers and occupancy

3.1 Ground layer

Every tile has a ground type. Ground is visual only. It does not by itself block movement, cause collision, or create gameplay behaviour.

TileGround { groundTypeId: GroundTypeId }

3.2 Block layer

A tile may also contain one block. The block is the actual world object standing on the tile and can determine collision and behaviour.

TileBlock { blockTypeId: BlockTypeId \| null config?: BlockConfig }

Examples include walls, doors, trees, torches and other lights, containers, spawners, marketplace counters and banks. Block definitions determine properties such as passability, interaction behaviour, whether a block participates in navigation, and whether it emits light (lightRangeTiles).

3.3 MOBile entities

A moving game entity — player, enemy, animal, NPC or any other mobile actor — is represented by an ECS entity rather than being painted into the static tile map. A mobile entity may inhabit a tile in addition to the tile’s ground and block layers, subject to collision rules.

Tile ├── Ground (visual layer) ├── Block (static/world-object layer; optional) ├── Ground item stacks (ephemeral, non-blocking) └── Mobile ECS entities (dynamic occupancy)

The spatial chunk index maintains which mobile entity IDs currently occupy each tile, allowing collision, nearby queries and replication without scanning the global ECS. Ground item stacks are indexed per tile as well, but they never contribute to movement collision and never prevent a mobile entity from standing on that tile.

4. ECS model

4.1 Entity composition

Entities are numeric identities plus components. Behaviour comes from systems querying component combinations rather than deep class inheritance.

Player Position Movement Health Combat Skills Inventory Currency Equipment Player NetworkIdentity ChunkLoader Persistent

Ordinary enemy Position Movement Health Combat Skills Creature AI

Named NPC Position Movement Health NPC AI Persistent

4.2 Global identity versus local ECS handle

Use a globally meaningful EntityId for storage, networking and cross-worker transfer, and a compact worker-local EntityHandle for hot ECS arrays. A transferred entity keeps its EntityId but may receive a different local handle on the destination worker.

4.3 Recommended initial components

CategoryComponents
SpatialPosition, Movement, Path, Collision
LivingHealth, Combat, Creature, Mob, Skills
PlayerPlayer, NetworkIdentity, Inventory, Currency, Equipment
AIAI, Target, BehaviourState
LifecycleChunkLoader, Persistent, SpawnOrigin
PresentationRenderable / Appearance
Future controlController / ScriptController / OfflineUntil

5. ChunkLoader and simulation activation

5.1 Generic ChunkLoader component

World activation is component-driven rather than player-specific. Any entity may carry a ChunkLoader component that says “keep the surrounding world resident and simulated”.

ChunkLoader { simulationRadiusChunks: 1, regionLoadRadius: 1 }

A normal player can therefore stimulate a 3×3 chunk area while keeping the surrounding 3×3 regions resident. Bosses, travelling NPCs, machines, scripted actors or administrative anchors can use the same mechanism.

5.2 Reference counting

Chunk simulation and region residency should use reference counts. Overlapping loaders increment the same references; leaving decrements them. A chunk sleeps only when its simulation reference count reaches zero. A region becomes eligible for unload only when its residency references reach zero.

5.3 Grace period

After the last residency reference disappears, retain the region briefly before unloading. This prevents repeated SQLite reads and writes when a loader oscillates around a boundary. The delay should be configurable.

6. Chunk lifecycle and persistence

6.1 No periodic chunk saves

Normal gameplay does not periodically rewrite loaded chunks. A chunk is saved as part of the unload path only.

Resident chunk ↓ last residency / forced shutdown unload Prepare unload ↓ Persist required chunk state once ↓ Persist required entities ↓ Remove ECS/runtime representation

A graceful server restart does not introduce a second save mechanism. It force-unloads every resident region/chunk, so the normal unload persistence path remains the single source of truth.

6.2 Persistent versus non-persistent entities

Persistence is an entity property, not a property of the chunk or spawner. An entity with Persistent is serialised when its owning chunk/region unloads. A non-persistent entity is simply discarded.

Non-persistent wolf spawn → simulate → chunk unload → disappear

Persistent named NPC load → simulate → chunk unload → save → recreate when area loads

6.3 Persistent is independent of ChunkLoader

These traits must remain independent. A persistent entity does not automatically keep its area active, and a ChunkLoader does not automatically become persistent.

7. Storage architecture

7.1 Separate authored world and runtime state

Use two SQLite databases with different responsibilities.

DatabaseResponsibility
world.sqliteAdmin-authored ground tiles, block tiles, light maps, live world settings and their edit log, spawner configuration, per-chunk editor changelogs, world revisions and world metadata.
state.sqliteAccounts, characters, inventories, carried currency, character vaults, inheritance tabs, cheque reservations, skills, groups, courier cargo/transit, unexpired ground items, market orders/escrow/trades, per-item last player-market sale, persistent ECS entities, offline-script state, optional persistent runtime chunk overrides, and other durable live-game state.

This prevents editor authoring changes from becoming entangled with live player/entity persistence.

7.2 Chunk writes in runtime state

If initial gameplay does not allow permanent tile/block modification, runtime chunks require no writes at all. If permanent runtime world changes are later added, dirty chunk overrides are held in memory and written to state.sqlite only when that chunk unloads. Shutdown uses forced unload and therefore follows the same rule.

7.3 Central persistence service

Simulation workers should not independently compete for SQLite writes. A persistence service owns the write connection, batches transactions, and receives logical save requests from workers.

Simulation workers │ save/unload messages ▼ Persistence service │ ▼ SQLite (WAL)

Live ECS state remains authoritative while loaded; SQLite is durable state, not a per-tick synchronisation mechanism.

8. World authoring and revision model

8.1 Admin-only world editor

The server includes a separate admin-only world editor UI. It is not part of the normal player client.

  • Display a 3×3 of 16×16 chunks, with the currently selected

chunk in the centre and a red border around that chunk. Painting, open/closed, and changelog apply only to the selected chunk; neighbours are visible for alignment and baked lighting context.

  • Provide Up, Down, Left and Right navigation buttons that move the

editor exactly one chunk in that direction.

  • Show the current chunk coordinates prominently, and whether the chunk

is open or closed.

  • Toggle the current chunk open or closed. Closed chunks remain visible

to nearby players but cannot be entered.

  • Allow painting a ground type on a tile.
  • Allow painting, replacing or erasing the block type on a tile.
  • Hovering a tile in the selected chunk previews the selected tool there:

existing content on that layer is hidden and the tool's sprite is shown where a click would place it.

  • Mouse wheel cycles the visual state of the selected ground or block

type (see section 21.3). If the hovered tile already has that type, the wheel also writes the new state onto it.

  • Render both layers together so the block appears on top of the ground.
  • Do not display ordinary mobile entities as editable map paint.
  • Allow selecting/configuring special block types such as Spawner, Bank,

Marketplace and light-emitting blocks (lightRangeTiles).

  • Open a world settings modal for global tick timers and constants

(movement cadence, night darkness, shop lerp duration, drop lifetime, and other values listed in section 8.5). The form is categorised and scrollable; a settings edit log sits beside it. Edited rows are marked until Save, and only those rows are written.

  • Provide a night-to-day slider that only previews lighting; it does

not change live world time. Preview uses the same baked light maps as play, including light that reaches this chunk from neighbouring chunks.

  • Later: allow configuring ground-item spawners analogously to mob

spawners. Exact item tables remain a later content decision.

  • Save changes through an authenticated admin API; the browser never

opens SQLite directly.

  • Show that chunk's changelog: a chronological list of saves, each with

which admin made the edit, when, and a bullet-point diff of the change.

The editor camera is not locked to a player character. It frames the currently selected chunk. This is the only intended exception to the player-centered play viewport in section 21.4.

8.2 World editor save behaviour

Saving a chunk writes the authored result to world.sqlite. It does not live-patch the currently running simulation map. Instead, the change creates or updates a pending world revision and schedules a server restart for the next server-local midnight (or Apply now).

Saving world settings is different: it updates the live settings row immediately, records a settings changelog entry, and the running process applies the new values without waiting for a world revision.

The running game remains pinned to the chunk world revision selected at its own startup. This avoids a dangerous mixed state where some loaded chunks use old authored data and newly loaded chunks use newer editor data. Settings are not revision-pinned.

8.3 Versioned authored chunks

A practical schema is to give every editor change a monotonically increasing world revision. The game process pins one active revision for its entire lifetime. Chunk lookup selects the latest authored version not newer than that pinned revision.

world_revisions revision_id created_at created_by status // pending / active / superseded

world_chunk_versions chunk_x chunk_y revision_id open // player-enterable; default false until set data_blob

world_meta active_revision pending_revision

world_settings revision_id settings_blob // historical snapshot copied onto a map revision

world_live_settings id // singleton row, always 1 settings_blob // the live, immediately applied settings updated_at updated_by

world_settings_edit_log log_id editor_admin_id edited_at diff_entries // which options changed, from/to

world_chunk_edit_log log_id chunk_x chunk_y revision_id editor_admin_id edited_at diff_entries // structured bullets for this save

On the next planned restart, startup promotes/selects the latest valid pending revision before world loading begins.

8.4 Per-chunk changelog

Every successful chunk save appends one changelog record for that chunk. The record is durable in world.sqlite and is not gameplay state.

The server diffs the newly saved chunk against the previous authored version of that same chunk (the latest world_chunk_versions row for those coordinates that this save replaces). Unchanged tiles produce no bullets. Each changed tile becomes one of:

- Ground at X, Y changed from Prev to New.
- Block <type> placed at X, Y.
- Block at X, Y changed from Prev to New.
- Chunk opened.
- Chunk closed.

X, Y are world tile coordinates. Prev / New / <type> are the ground or block definition display names. A block paint on an empty block layer is a placement. Replacing one block type (or its config, such as a spawner) with another is a change. Erasing a block is a removal. Ground is never absent; a ground paint is always a change from one type to another.

The editor UI lists records newest-last or newest-first consistently, each headed by admin identity and timestamp, with that save's bullets underneath. The changelog is an audit trail, not an undo stack. Undo/redo remains an open editor-UX decision. Derived light maps are not changelog bullets; they are regenerated on save (section 8.6).

8.5 World settings

Global gameplay constants live in authored world_live_settings. They are not per-mob, not client-authored, and not pinned to a map revision. Admins edit them from a large tabbed modal in the world-editor UI. The modal fills most of the screen: the left pane has category tabs (Simulation, Graphics, World, Characters, Communication, Inventory, Economy) with one panel visible at a time; the right pane is a settings edit log (which option changed, from/to, which admin, date/time).

Rows the admin has edited in this session are marked with a distinct background. Save writes only those dirty fields. The running process applies them immediately (walk cadence, tick rate, night darkness, bloom post-chain knobs, and other consumed timers). Chunk Apply now is not required.

nightDarkness only darkens during dusk/night/dawn (peak hours 22–5). Daytime hours 8–16 stay fully bright on the client. Editing night darkness in the editor snaps the Night preview slider to night so the change is visible immediately.

Minimum initial settings and defaults:

WorldSettings
- walkTilesPerSecond          // default 2
- simulationTickHz            // default 20; implementation default, still a setting
- shopPriceLerpDuration       // default 1 hour
- groundItemDespawnDuration   // default 10 minutes
- regionUnloadGracePeriod     // configurable grace after last residency
- defaultGroundTypeId         // grass used for never-edited chunks
- characterDeletionDelay      // default 24 hours
- nightDarkness               // default 0.72; 0 = no extra night darkening, 1 = fully black unlit tiles
- chatMaxCharacters           // default 100; trimmed proximity-chat line length
- bloomThreshold              // default 0.35; Framework bloom bright-pass
- bloomSoftKnee               // default 0.3
- bloomIntensity              // default 1.35
- bloomBlurSize               // default 3
- bloomSaturation             // default 1.15
- bloomColorPreserve          // default 0.35
- bloomDilate                 // default 2; 0 disables dilate
- bloomScales                 // default 2; H/V blur scale pairs
- bloomHalfRes                // default 1; 1 = half-res blur, 0 = full-res

Running is always double walking speed. It is not a separate per-entity field. From walkTilesPerSecond:

runTilesPerSecond   = walkTilesPerSecond * 2     // default 4
movementTickHz      = runTilesPerSecond          // default 4 Hz
walk: commit a tile every 2 movement ticks
run:  commit a tile every 1 movement tick

All ground mobiles — players, enemies, NPCs — use this same cadence. A mob definition does not set move speed. Gait (walk | run) is the only per-entity choice; it selects every-other vs every movement tick.

Other tick-duration constants that already exist in this document (shop lerp, ground-item despawn, residency grace, and later ones of the same kind) are edited here rather than hardcoded. Adding a new global timer means adding a field to WorldSettings and a row in this modal.

8.6 Baked lighting

Light from authored blocks is precomputed when a chunk is saved, not raytraced every simulation tick.

A block definition may set lightRangeTiles > 0. That tile is a static light source. Light travels only through passable tiles (the same passability as walking). Ground type does not block light. Mobiles and ground items do not block light.

For every tile within a source's range, the baker runs a simple grid raycast (for example Bresenham through tile centres). If the ray hits an impassable block before the destination, that source does not light that tile. A tile is lit if any source can reach it. Light does shine across chunk boundaries.

Saving a chunk rebakes:

1. that chunk's 16×16 light map, and 2. every neighbouring chunk that could be affected (chunks within the maximum lightRangeTiles of the saved chunk).

Neighbor rebakes use light sources and walls from the pending revision, including the chunk just saved. Those neighbor light maps are written into the same pending revision so play never mixes old and new lighting.

The light map is stored in the chunk data_blob as a 16×16 intensity (0 = unreachable, 1–255 = falloff by distance from the strongest reaching source). The client darkens tiles by that intensity at night, so a torch fades tile-by-tile rather than lighting a hard disc. Peak unlit darkness is nightDarkness (a live world setting). It is replicated to clients in CHUNK_SNAPSHOT / CHUNK_DELTA.

Runtime door open/close does not rebake static light unless a later iteration adds live lighting. Baked light is authored geometry.

The editor night-to-day slider interpolates preview ambient from full night (dark except baked-lit tiles) to full day (no ambient darkening). It does not persist and does not change server/world clock.

8.7 Default chunks and open / closed

A chunk the editor has never saved does not exist in world_chunk_versions. At runtime it is synthesised as:

  • every tile defaultGroundTypeId (grass),
  • no blocks,
  • closed,
  • no baked lights.

The world is therefore an infinite grass field until admins paint it, and players cannot walk onto it until an admin opens the chunk.

Closed chunks can still appear in a player's 3×3 view. They cannot be entered: MOVE_TO, pathfinding, spawning, and other player-entry actions treat every tile in a closed chunk as impassable. Visibility and lighting previews are unchanged. Where an open chunk shares an edge with a closed (or never-edited) chunk, the client draws a red border on that edge so players can see they cannot cross.

Open chunks are the playable map. Opening or closing is an authored chunk flag, saved with the pending revision like paint.

Spawners in a closed chunk do not spawn. Ground movement, including AI, does not step into a closed chunk. If a future bug or admin tool places an entity there, it can still be replicated to observers, but players cannot walk in after it.

9. Spawner blocks

9.1 Spawner data

A Spawner is a block in the authored block layer, with per-instance configuration stored as part of the chunk data.

SpawnerConfig { spawnerId: SpawnerId, mobTypeId: MobTypeId, maxAlive: number, spawnRangeTiles: number }

Additional parameters such as minimum/maximum spawn delay can be added later without changing the core model.

9.2 Spawner editor

Selecting a Spawner tile in the world editor opens a configuration panel containing at minimum: mob type, maximum alive count and spawn range. Validation happens server-side before the pending world revision is written.

9.3 Spawned entity persistence

The spawner never decides whether its mob is persistent. The mob definition/archetype does. When the spawner creates an entity, the entity receives Persistent only if that mob type is defined as persistent.

MobDefinition: deer persistent = false

MobDefinition: named_guard_captain persistent = true

9.4 SpawnOrigin

Spawned mobs receive a SpawnOrigin component referencing the spawner. This lets maxAlive count only entities belonging to that spawner and avoids expensive geometric searches.

SpawnOrigin { spawnerId: SpawnerId }

For non-persistent mobs, disappearance on chunk unload naturally decreases the count. For persistent mobs, SpawnOrigin is persisted so the spawner can recognise an existing persistent instance even after it has moved or been unloaded elsewhere. A lightweight persistence index by spawnerId prevents duplicate persistent spawns.

9.5 Spawner simulation

SpawnerSystem runs only while the spawner’s chunk is simulating and open, and at a much lower frequency than movement. A spawn candidate must satisfy block collision, bounds, an open chunk, and mobile-occupancy rules. Ground type does not affect passability unless a later gameplay system explicitly introduces a separate rule for it.

9.6 Future ground-item spawners

Some items will later spawn naturally on the ground, using a world-editor block analogous to a mob spawner. Those spawned stacks should use the same non-blocking ground-item representation as player drops, but their lifetime, respawn and maxOnGround rules belong to the spawner configuration rather than the 10-minute player-drop timer.

Exact item lists, harvest interactions and spawner parameters are later content decisions and do not block the inventory/bank model.

10. Startup and loading order

Loading order is explicit so authored world state exists before persistent entities are instantiated into it.

> 1. Start process and load configuration, including server time > zone and storage paths. > > 2. Open world.sqlite and validate/migrate its schema. > > 3. Select/promote the world revision to use for this process and > pin it for the lifetime of the process. > > 4. Load static registries: ground definitions, block definitions, > item definitions, material definitions, spell definitions, mob archetypes and component serializers. > > 5. Open state.sqlite and run runtime-state migrations. > > 6. Start the persistence service, durable domain services (such as courier, bank, market and shop-price services when enabled), region coordinator and simulation workers. > > 7. Load the index of persistent entities that themselves require > world activation (for example persistent ChunkLoaders or future > offline scripted players). > > 8. For each required region, load authored chunk data from the > pinned world revision first. > > 9. Apply any durable runtime chunk override state, if the game > supports such modifications. > > 10. Instantiate persistent entities into the already-created > world/chunks. > > 11. Recalculate ChunkLoader references and begin chunk simulation. > > 12. Only after the world reports READY does the gateway accept > normal player logins.

This ordering solves the bootstrap problem for persistent entities that keep their own chunks active: a compact persistence index can locate them without first loading the entire world.

11. Simulation workers and region ownership

11.1 Ownership invariant

Exactly one worker authoritatively owns a region at any instant. Every authoritative entity belongs to the worker that owns the entity’s current region.

11.2 Coordinator

A central region coordinator maintains RegionId → WorkerId and assigns/migrates regions based on actual measured simulation effort, while preferring neighbouring regions on the same worker when load permits.

11.3 Work measurement

  • Average and high-percentile tick execution time.
  • Number of simulating chunks.
  • Number of active entities and AI entities.
  • Pathfinding work and queued searches.
  • Cross-worker boundary message volume.
  • Backlog / tick lateness.

Actual time spent simulating is more important than raw player count or raw region count.

11.4 Node.js implementation

Simulation workers keep mutable ECS worlds isolated and talk only through structured-cloneable messages. The default runtime is in-process workers with clone-on-boundary (so the protocol is real even without OS threads). SIMULATION_WORKER_MODE=thread runs the same WorkerWorld inside worker_threads. Do not share a mutable ECS in SharedArrayBuffer.

A coordinator on the gateway thread owns region assignment (neighbour-sticky, least-loaded tie-break), global EntityIds, transfer handoff, ghost exchange, and SQLite. SIMULATION_WORKERS defaults to 2. Dynamic load rebalance is later.

12. Cross-worker communication

12.1 No remote mutation

A worker may inspect a limited read-only representation of neighbouring entities but never directly mutates authoritative state owned by another worker.

12.2 Border ghosts

Neighbouring workers can exchange compact border/ghost entity data for nearby interaction and AI: EntityId, position, collision footprint, type and minimal combat metadata. Ghosts are not full ECS entities and are never authoritative.

12.3 Remote actions

Worker A goblin targets Player 42 (owned by Worker B) Worker A → REMOTE_ACTION(attack intent) → Worker B Worker B validates range/state and applies authoritative result

12.4 Entity transfer

When an entity crosses from a region owned by Worker A into one owned by Worker B, ownership is handed off at a simulation tick boundary using a sequence-numbered transfer protocol. There is never more than one authoritative copy.

A: prepare transfer B: validate / accept A: freeze at handoff boundary B: instantiate authoritative entity at effective tick Coordinator: update ownership mapping A: remove authoritative copy

13. Server tick and stimulation

13.1 Fixed simulation tick

Use a fixed server simulation tick. The default is 20 Hz (50 ms), stored as WorldSettings.simulationTickHz. This is not a protocol promise.

Movement does not commit a new tile on every simulation tick. See section 13.4.

1\. Drain validated incoming commands 2. Apply completed worker/entity transfers 3. Recalculate activation changes 4. Movement / collision 5. Combat 6. Scheduled AI 7. Scheduled spawners/environment, including ground-item expiry in simulating chunks 8. Produce cross-worker messages 9. Produce client replication deltas 10. Queue unload/persistence work

13.2 Different system frequencies

Not every ECS system should run every tick. Ground movement commits only on the global movement cadence (section 13.4). AI decisions, target searches and spawner checks can run at lower frequencies. Sleeping chunks are not “slow ticked”; they are omitted from normal simulation.

13.3 Timestamp-based inactive progression

Long-lived timers such as growth, cooldowns, ground-item expiry and shop price lerps should store future timestamps where possible. When an area wakes, the system catches up from the timestamp instead of executing missed ticks. An expired ground item is discarded on catch-up without ever reappearing. Shop and tooltip prices are evaluated from last-sale timestamps when observed; they are not ticked. Durations such as shop lerp and ground-item despawn come from WorldSettings, not from hardcoded literals in systems.

13.4 Global movement cadence

All ground-moving entities share one walk speed and one run speed.

  • Default walk: 2 tiles per second (walkTilesPerSecond).
  • Run: always double walk (default 4 tiles per second).
  • Movement ticks fire at runTilesPerSecond (default 4 Hz).
  • Walk: the entity may advance one path tile on every other movement

tick.

  • Run: the entity may advance one path tile on every movement tick.

Mobs do not define their own move speed. Movement.gait is walk or run. Players send SetGait. AI may set gait; it still uses the global cadence. Flying pigeon transit is not this cadence; it keeps its own route clock.

If the path is blocked on a movement tick, the entity stays on its tile and retries on a later legal tick. Occupancy, combat range and pickup always use the last committed tile.

13.5 World calendar time

World time is server time 1:1, in the same configured IANA zone used for midnight restarts, with 1200 years subtracted from the calendar date. A server clock of 24 Aug 2026 21:00 is world 24 Aug 826 21:00. Clock-of-day, including night, therefore matches the host's zone.

The gateway includes current world time (or server unix time plus the year offset) in the status sent to clients so shading does not depend on the player's device clock. Lighting is presentation; combat and movement do not wait on the day/night overlay.

14. Client gateway and authority

14.1 Stable connection ownership

Client WebSocket/TCP connections belong to a gateway rather than simulation workers. When the player crosses into a region owned by another worker, the socket stays connected to the same gateway; only internal routing changes.

14.2 Client commands are intentions

A client sends commands such as MoveTo, Interact, Attack, UseItem, EquipItem, UnequipItem, SelectSpell, SetGait, DropItem, PickupItem, BankDeposit, BankWithdraw, BuyFromShop or SendPigeon. The authenticated account determines the actor; after character select, commands apply to that account's active character. The client never supplies an authoritative resulting position, health value or inventory result.

14.3 Input queue

Socket handlers validate message shape and enqueue commands. Simulation workers consume commands at tick boundaries. WebSocket callbacks do not mutate ECS state directly.

14.4 Authentication

Live login uses auth.timfalken.com. The game server never stores a password. It receives an authenticated account identity (and email) from that service and maps it to a durable accountId in state.sqlite.

Until auth.timfalken.com is available, the gateway uses a stub identity: each new connection is admin-<n>, where n is the number of currently connected clients including this one (the first connection is admin-1). Stub accounts are treated as admins so the world editor can be used during development. Stub accounts have no email; deletion “emails” are logged instead of sent.

When real auth ships, the stub is removed. Admin rights come from that service, not from the admin- name prefix.

An account may have only one active play session at a time (one character in the world).

14.5 Characters

An account has unlimited characters and plays one at a time. First login with no characters must create one before entering the world. Later logins show a character-selection menu: create, choose, mark for deletion, or cancel deletion.

Initial character setup (may change later):

CreateCharacter
- firstName     // not globally unique
- lastName      // unique surname, owned by this account
- sex           // male | female

Rules:

  • Last names are globally unique. The first character to take a surname

claims it for that account. The same player may reuse that last name on their other characters. Another account cannot use it.

  • First names need not be unique globally.
  • For a given account, firstName + lastName must be unique among

characters that still exist (including those pending deletion).

  • Uniqueness is case-insensitive; display uses the casing the player typed.
Account
- accountId
- authSubject               // from auth.timfalken.com, or stub admin-<n>
- email?                    // from auth; absent on stub
- surnameClaims[]

Character
- characterId
- accountId
- firstName
- lastName
- sex
- deletionScheduledAt?      // null if not deleting
- inventory, equipment, currency, vault, skills, ...

The in-world ECS player entity is a character, not the account.

14.6 Character deletion and inheritance

From character select, the player may mark a character for deletion.

  • The character cannot be played while deletion is pending.
  • Permanent delete happens after characterDeletionDelay (default **24

hours**). Until then the player may cancel.

  • The server always notifies the account email when deletion is

marked (and should notify again on cancel and on actual delete). Stub auth logs the message instead.

  • On permanent delete, the name pair is freed. If this account has no

remaining characters with that last name, the surname claim is released.

  • Before the vault is moved, BankService voids outstanding filled

cheques issued by this character (reservations return to the vault).

  • All items in inventory, equipment, carried currency, and the character

vault are moved to that account's inheritance bank tab.

Any living character of the same account may, at a bank, claim inheritance stacks (and currency) into that character's own vault. Claiming is a move from the account tab to the character vault, not a second copy.

15. Client chunk subscription and replication

15.1 3×3 visibility

A player receives the current chunk and the eight surrounding chunks, a maximum viewport of 48×48 tiles. Neighbouring closed chunks are still sent so scenery remains visible; the player simply cannot walk onto them.

┌───┬───┬───┐ │ V │ V │ V │ ├───┼───┼───┤ │ V │ P │ V │ ├───┼───┼───┤ │ V │ V │ V │ └───┴───┴───┘

15.2 Incremental subscription changes

Crossing one chunk east subscribes only the three newly visible eastern chunks and unsubscribes only the three old western chunks. The rest of the 3×3 view remains subscribed.

15.3 Snapshots and deltas

Initial subscription sends a CHUNK_SNAPSHOT containing authored/runtime tile state, currently visible entities and unexpired ground item stacks. Afterwards, revisioned CHUNK_DELTA messages report tile changes, entity spawn/move/change/despawn events and ground-item appear/change/despawn events. Full chunks are not retransmitted every tick.

Entity move events carry the new integer tile and the current gait so the client can lerp over the walk or run interval. They do not carry a fractional in-between position. Smooth walking is a client visual lerp (section 21.5), not part of the replication payload.

Chunk snapshots include the baked light map (section 8.6).

Visible equipment is replicated as a compact appearance payload (body sprite plus worn overlay layers and recolour parameters), not as the entity's full inventory. Nearby clients can draw another player's armour without receiving their bags.

15.4 Visibility can span workers

The gateway can source visible chunks from multiple workers. A player may be authoritative on Worker A while one or more of the eight neighbouring visible chunks are owned by Worker B. Client visibility must never force simulation-region reassignment.

16. Click-to-move and A\* pathfinding

16.1 Command flow

Client: MOVE_TO(tileX, tileY) ↓ Gateway validates/authenticates ↓ Owning worker validates target ↓ A\ calculates authoritative route ↓ Path component attached/updated ↓ MovementSystem advances the entity one tile at a time* on the global walk/run cadence (section 13.4)

Authoritative Position is always an integer tileX, tileY. The server does not store a sub-tile location for walking mobiles. When a movement tick allows this gait to step, MovementSystem commits the next path tile in a single jump. Combat, occupancy, pickup and interaction all use that committed tile.

Flying pigeons still ignore the ground navigation grid, but their replicated ECS position is likewise a tile. The transit clock determines which tile they occupy at a given time; the client may lerp the sprite between those tiles like any other mobile.

16.2 Initial A\* implementation

For normal player clicks within the visible 3×3 chunks, the search space is at most 48×48 = 2,304 tiles, so conventional A\* is a strong starting point.

  • Binary heap priority queue for the open set.
  • Manhattan heuristic for four-direction movement; octile heuristic if

diagonal movement is later allowed.

  • Reusable typed-array or pooled search buffers for hot paths to reduce

allocation and garbage collection.

  • Rate-limit path requests per player and avoid recalculation every

tick.

  • Use block passability, open-chunk bounds, and dynamic occupancy;

ground is visual only. Tiles in closed or never-edited chunks are not legal path targets for players.

16.3 Navigation revisions

Each chunk maintains a navigation revision that increments when a movement-affecting block changes. A path records the relevant revisions. Static geometry changes can invalidate paths; temporary mobile occupancy normally causes a short wait or small local re-path rather than rebuilding every path.

16.4 Long-distance extension

If long-distance autonomous travel is added later, introduce hierarchical pathfinding: region graph → chunk portals/edges → local tile A\*. The client movement command interface does not need to change. Server movement remains discrete tile steps; only the path length changes.

17. Automatic update and restart scheduler

17.1 Restart triggers

A graceful restart is scheduled for the next midnight in configured server-local time when either of these conditions occurs:

  • A new commit is detected on origin/master. The master branch is the

live branch.

  • An administrator saves a world-editor change, creating/updating a

pending authored world revision.

Multiple triggers coalesce into one scheduled restart. The scheduler stores all reasons so players and admins can see why a restart is pending.

17.2 Detecting live-code changes

The running server periodically performs a non-destructive remote check, for example git fetch origin master followed by comparison of the running commit with origin/master. It does not update the checked-out code while the game is live.

17.3 Server-local midnight

Midnight is calculated in a configured IANA time zone rather than by adding 24 hours to the current time. This keeps behaviour correct across daylight-saving transitions.

17.4 Player-visible restart state

Restart status is part of the server status sent to clients. Connected players see that a restart is scheduled and the scheduled local time. The server can also issue configurable countdown notices as the restart approaches and includes the state immediately when a player logs in.

RestartStatus { scheduled: true, scheduledAt: timestamp, reasons: \["code-update", "world-update"\] }

17.5 Manual admin restart

An authorised admin action can invoke the same graceful restart pipeline immediately. This is not a separate “hard restart” path; it differs only in scheduled time.

17.6 Graceful restart sequence

> 1. Enter DRAINING / RESTARTING state and reject new logins. > > 2. Broadcast the final restart notice. > > 3. Disconnect player sessions cleanly and persist session state. > Shutdown handling overrides normal offline-script retention so chunk > unload cannot be blocked by a retiring process. > > 4. Stop accepting new gameplay commands and finish the current > safe tick boundary. > > 5. Force-unload every resident region/chunk, ignoring normal > ChunkLoader references. This invokes the ordinary chunk/entity unload > persistence path exactly once. > > 6. Flush the persistence service and close SQLite connections > cleanly. > > 7. Atomically write a restart request manifest. It records the > restart reasons, whether a code deployment is requested, the target Git > commit if known, and the pending world revision if one exists. > > 8. Exit the Node.js game process cleanly. At this point the game > process has no responsibility for updating or relaunching itself.

17.7 systemd process supervisor

The production Node.js process is owned by a systemd service. systemd therefore already knows when the process has fully exited; no separate polling process is needed. Only after the previous ExecStart process is gone does systemd begin the next service start.

The preferred lifecycle is:

Running Node.js server
        |
        | graceful planned restart or crash
        v
Node.js process fully exits
        |
        v
systemd starts the service again
        |
        +--> conditional update hook
        |       |
        |       +--> planned code deployment: git fetch/pull --ff-only
        |       +--> world-only restart: no Git mutation
        |       +--> crash/no restart manifest: no Git mutation
        |
        +--> optional dependency/build step if deployment changed code
        |
        v
Start Node.js server
        |
        v
Startup selects the new active world revision
        |
        v
Gateway opens when the world reports READY

17.7.1 Why Git pull must be conditional

A naive ExecStartPre=git pull on every restart is unsafe. Suppose a new commit is detected at 14:00 and correctly scheduled for midnight, but the game process crashes at 16:00. An unconditional pull would deploy the new commit immediately during crash recovery, bypassing the scheduled maintenance window.

Therefore the restart manifest distinguishes an intentional deployment restart from an ordinary process failure:

{
  "reason": ["code-update", "world-update"],
  "deployCode": true,
  "targetCommit": "<optional commit hash>",
  "pendingWorldRevision": 184
}

The manifest should be written using a temporary file plus atomic rename so the supervisor never consumes a half-written request. The supervisor consumes/removes the request only after it has successfully interpreted it.

If the Node.js process dies without a valid deployment request, systemd restarts the currently checked-out version. This gives fast crash recovery without prematurely deploying pending code.

17.7.2 Suggested systemd shape

A production unit can conceptually look like this:

[Unit]
Description=Tile MMO Server
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=tilemmo
Group=tilemmo
WorkingDirectory=/srv/tile-mmo/current

# This hook checks the restart manifest. It pulls/builds only when an
# intentional deployment was requested. Prefixing with '+' optionally
# allows the hook to run with privileges different from the game user.
ExecStartPre=+/usr/local/sbin/tile-mmo-update-if-requested
ExecStart=/usr/bin/node /srv/tile-mmo/current/dist/server.js

Restart=always
RestartSec=5s
TimeoutStopSec=120s
KillSignal=SIGTERM

[Install]
WantedBy=multi-user.target

Restart=always is appropriate here because an explicit systemctl stop tile-mmo does not cause systemd to restart the unit, while a clean in-game restart exit and an unexpected crash both do.

The exact paths, build command and privilege split are deployment details, but the important invariant is that the Node.js process does not pull Git itself.

17.7.3 Code-update, world-update and crash behaviour

SituationRestart manifestGit pull before restartWorld revision
Scheduled code updatedeployCode=trueYes, fast-forward onlyActivate pending revision if present
World-editor-only updatedeployCode=falseNoActivate pending revision
Manual deployment restartExplicit admin intentAs requestedActivate pending revision if present
Unexpected Node.js crashMissing/invalidNoContinue current active revision
systemctl stopIrrelevantNo automatic restartN/A

This preserves the midnight deployment promise even when the game crashes before the scheduled maintenance window.

17.8 Failure behaviour

Deployment should fail closed. If Git cannot fast-forward, a build or migration fails, or startup validation fails, the game must not open to players on a partially updated state. The update hook should log the failure clearly and return non-zero; systemd may retry according to its restart/start-limit policy. Databases remain intact, and backups or snapshots before schema migrations are recommended.

A failed crash recovery that did not request deployment must not silently switch to a newer Git commit as a recovery strategy.

18. Future player scripting architecture

18.1 Scope

The custom scripting language is explicitly a later feature. Version 1 only needs architectural hooks so adding scripts does not require replacing the player-control or simulation model.

18.2 Controller abstraction

All player actions should already pass through an internal command interface. Manual client input is therefore one possible controller. A future script is another controller that emits the same validated action intentions.

ClientController ─┐
                  ├─> ActionCommand queue ─> authoritative game systems
ScriptController ─┘

Scripts never mutate ECS components directly. They request actions such as MoveTo, Interact or Attack and receive the same validation as a human client.

18.3 Online scripted mode

A logged-in player may enable the script while remaining connected and observing the game. Control mode explicitly determines whether manual input or the script is currently producing gameplay commands. The server remains authoritative either way.

18.4 Logout with active script

If a player has configured offline script execution, logout removes the network/controller connection but keeps the player entity alive. The entity changes to an offline script-controlled state and continues acting until it dies or its configured offline duration expires.

Player online Player + NetworkIdentity + ChunkLoader + Controller ↓ logout with offline scripting Player + ScriptController + ChunkLoader + OfflineUntil ↓ death OR expiry persist player state → remove runtime entity

18.5 Offline scripted players and loading

An offline scripted player must continue to stimulate the world it traverses, so it retains a ChunkLoader. This is powerful but potentially expensive: thousands of offline scripts could keep large parts of the world active. Offline duration, script CPU budget and concurrent offline-script limits therefore become explicit resource policy, not implementation accidents.

18.6 Restart continuity

A planned restart persists the offline-script state and expiry time, force-unloads the old process, and rehydrates still-valid offline scripted players during startup. This is why the startup index for persistent ChunkLoaders is part of the base architecture.

18.7 Scripting language safety requirements

When the language is implemented, it should be interpreted/compiled into a purpose-built sandbox rather than evaluated as JavaScript. At minimum it should enforce:

  • No file-system, operating-system, database or arbitrary network

access.

  • No eval or escape into Node.js objects.
  • Per-tick/per-event instruction budgets and bounded memory.
  • Rate-limited expensive operations such as path requests and world

queries.

  • Capability-based read APIs for nearby visible/known world state.
  • Action output only through the normal server command pipeline.
  • Persistable script variables/state if offline execution must survive

restarts.

  • Deterministic or tightly controlled timing semantics where practical.

An event-driven language is preferable to running every player script continuously at full simulation frequency. Events such as arrival, attack, nearby entity changes or timer expiration can wake scripts only when useful.

19. Security and administration

  • World-editor endpoints require an explicit admin role and separate

server-side authorisation checks.

  • Client-supplied entity/player IDs are never trusted as authority;

authenticated connection/session context identifies the actor.

  • World-editor data is validated against known ground, block, item and mob

definitions before database write.

  • Admin restart and deployment controls use the same authenticated

administration layer.

  • The Node.js game process should run as a dedicated unprivileged user.

Where practical, source-update permission belongs only to the systemd update hook (for example a privileged ExecStartPre helper), leaving the running Node.js process unable to modify its own checkout.

  • SQLite writes are parameterised and centralised through

persistence/editor services.

  • Inventory, vault, cheque and courier mutations are server-authoritative.

Clients cannot invent cheque IDs, forge cargo, or credit a vault.

  • Attack hit/miss and damage are server-authoritative. Clients cannot supply

a roll or a damage result. Shop purchase prices are computed at buy time on the server.

20. Recommended process topology

Clients
  |
  v
WebSocket/API Gateway
  |
  +-- Region Coordinator ----> Simulation Worker A
  |                              <--> Simulation Worker B
  |
  +-- Communication Service --> proximity speech
  |
  +-- CourierService ---------> pigeon cargo / transit
  |
  +-- BankService ------------> shared vaults / cheques / reservations
  |
  +-- MarketService ----------> order book / escrow / trades / last-sale index
  |
  +-- Persistence Service ----> state.sqlite
  |
  +-- Admin / World Editor ---> world.sqlite

External process supervision:
systemd ---> conditional deployment hook ---> Node.js relaunch

21. Player client architecture

21.1 FrameworkV3 as a git submodule

The player-facing client is built on the shared FrameworkV3 library:

<https://gitlab.com/Timfa/frameworkv3>

FrameworkV3 contains generic reusable client-side code. Game-specific rendering, UI, input, assets and protocol handling live in this repository, on top of that library. They are not patched into FrameworkV3 unless they are genuinely reusable across games.

This repository vendors FrameworkV3 as a git submodule rather than copying its source or depending on an unpublished global install.

mmo/
  client/
    frameworkv3/     # git submodule → gitlab.com/Timfa/frameworkv3
    src/             # this game's client: protocol, UI, world view, assets
  server/            # Node.js ECS backend; does not import FrameworkV3

The submodule path is client/frameworkv3. A clone of this repo is not client-buildable until submodules are present:

git clone --recurse-submodules <this-repo>
# or, in an existing checkout:
git submodule update --init --recursive

The submodule records a pinned commit. Bumping FrameworkV3 is an explicit commit in this repository (new submodule SHA). Game code must not rely on an uncommitted dirty checkout of the submodule.

Build order:

1. Build FrameworkV3 from client/frameworkv3
2. Build this game's client against that output
3. The Node.js server is a separate build and does not link FrameworkV3

The exact FrameworkV3 build command follows that project's own instructions. This game's client build must consume the framework's public/build artefacts, not fork its internals.

CI and developer machines check out submodules before the client job. A missing or uninitialized submodule is a failed client build, not a fallback to a system copy of FrameworkV3.

If this repo's master also ships the built web/desktop client from the same process that deploys the game server, a submodule bump is just another commit and follows the normal midnight restart/deploy path. The running Node.js game process still does not compile or import FrameworkV3.

The backend remains the authoritative Node.js ECS simulation described in this document. The client does not need to use ECS. It receives only a small 3×3-chunk view plus player/UI state, so a conventional object/view-model model is simpler and entirely appropriate.

21.2 Server/client model separation

Backend ECS components are not treated as a shared client object model. Network messages form the contract between the two sides.

Authoritative Node.js ECS
        |
        | snapshots / deltas / UI state
        v
Network protocol DTOs
        |
        v
Built FrameworkV3 (from client/frameworkv3 submodule)
        |
        v
This game's client code (client/src)

The two projects may share protocol schemas, enums or generated message types, but the client must not depend on the internal layout of ECS component storage. That allows server internals to be optimised without forcing corresponding client rewrites.

21.3 Sprite size, pivot and Y-sort

World sprites may be any pixel size. The gameplay tile remains 16×16. Each sprite is placed with an automatic pivot: horizontally centred, and 8 pixels up from the bottom of the sprite. That pivot sits on the tile centre, so a 16×16 sprite still fills the tile and a taller sprite stands on the same feet line and extends upward.

Each sprite kind — grounds, blocks, items, mobs, and characters — uses its own per-type asset folder (client/assets/<kind>/<key>/). Every base PNG in that folder is a visual state. Filenames ending in -bloom, -equip, or combinations such as -equip-bloom are companions, not states: torch-bloom.png is the bloom overlay for state torch, {state}-equip.png is the worn equipment overlay for that state, and {state}-equip-bloom.png is the bloom overlay for that equip sprite. Companions always live in the same folder as their base state and are never listed as placeable editor states. Image names follow layer:key:state (plus :equip / :bloom suffixes). States are not listed in the type definition: the first base filename in alphabetical (numeric) order is the default. A later gameplay system may set a named state on a placed tile (for example a door closed / open); unknown names fall back to the default. The editor mouse wheel cycles these states.

Bloom companions are drawn on a separate Framework bloom render layer that uses Shader.getBloomPostChain(...). Bloom post-chain parameters are live world settings under the Graphics tab.

Each type definition may set sprite-sheet playback for every state PNG:

frames            // sub-images in the sheet; default 1
framesPerRow      // columns in the sheet; default 1
animationSpeed    // seconds per frame; 0 means still

Blocks and mobiles with oversized sprites are Y-sorted: sprites higher on the screen draw behind sprites lower on the screen, using the pivot's world Y (the occupied tile, or the interpolated foot position while walking). Ground tiles and the night overlay stay behind and in front of that pass respectively.

Nearest-neighbour sampling still applies so pixels stay sharp under viewport zoom. Zoom scales the whole view uniformly; it is not a per-sprite size override.

21.4 Viewport, camera and zoom

In normal play the viewport is always centered on the local player's character. The camera does not free-pan. Scrolling the world happens only because the player moved.

The player may zoom in and out within configured minimum and maximum bounds (for example 1× to 4×; the exact numbers are a game setting). Zoom does not move the camera off the player and does not change server visibility: the client still receives only the 3×3 chunk window.

The admin world editor is the exception: it frames the selected 16×16 chunk and navigates by chunk, as in section 8.1.

21.5 Client movement interpolation

The server jumps mobiles from tile to tile. The client draws a visual lerp between the previous replicated tile and the new one over the interval implied by gait and WorldSettings (walk: 1 / walkTilesPerSecond, run: half of that). If a delta arrives late, clamp the remaining lerp. That lerp is presentation only:

  • Hit tests, range, pickup and occupancy use the authoritative tile.
  • A corrected server position snaps the interpolation target; the client

does not accumulate drift.

  • Interpolation does not entitle the client to send fractional positions.

21.6 Equipment layers and recolouring

A mob (including a player character) is drawn as a stack of sprites on the same tile: the body sprite (male or female from character sex, or the mob archetype body), then each piece of visible equipment. Overlays are not baked into the body art.

draw order (back → front, default)
  1. body / mob base
  2. boots
  3. legs
  4. chest
  5. head
  6. off-hand
  7. weapon

Slot draw order is data so a cloak or a two-handed sprite can be inserted without a renderer rewrite. Overlay sprites use the same automatic pivot as other world art (horizontal centre, 8 pixels from the bottom).

Equipment items stay in dedicated equipment slots, not in the 32 inventory slots, while worn. EquipItem(slotIndex) moves a legal item from inventory into the matching equipment slot, returning any previously worn item to inventory if there is space. UnequipItem(equipSlot) does the reverse. The weapon equipment slot is what combat uses; it replaces the older “wielded flag on an inventory slot” idea.

Non-player mobs may carry an Equipment component or a simpler appearance list on the mob definition so a guard can show armour without a player inventory.

Equipment
- slots: { head?, chest?, legs?, boots?, weapon?, offhand?, ... }

ItemDefinition.equipment?
- slot
- overlaySpriteId
- recolourableChannels?: ["metal"]   // omitted if the art is not recoloured
- materialId?                        // e.g. iron, steel; used with "metal"

Inventory icons and worn overlays may be different 16×16 files. Both are world sprites and both go through the size check.

Recolourable equipment

Some gear shares one overlay and is tinted per material. Metal armour is the initial case: iron, steel and later metals are not separate full-size art sets.

MaterialDefinition
- materialId            // iron, steel, ...
- displayName
- channel               // metal for armour; later channels may include cloth
- colour                // destination RGB for that channel

A recolourable overlay is authored as:

  • the 16×16 overlay sprite, with shading in the channel regions, and
  • an optional 16×16 channel mask of the same dimensions, whose pixels

name which recolour channel they belong to (for example a reserved mask colour meaning metal). Unmasked pixels are drawn unchanged.

At draw time, masked pixels keep the overlay’s relative brightness (highlights and shadows) and replace the hue/saturation with the item’s MaterialDefinition.colour. The client must not invent a colour; the server sends the material id (or the already-resolved colour) on the appearance layer.

Iron plate and steel plate therefore share overlaySpriteId = platebody and differ only by materialId. Non-metal unique art omits recolourableChannels and is blitted as authored.

Recolour happens on the client as a presentation step. It does not change item identity, combat stats or inventory. Nearby observers receive enough appearance data to apply the same layers and tints.

21.7 World time and night shading

The client treats world time as server time minus 1200 years (section 13.5). It uses that clock-of-day to shade the 3×3 view.

At night, tiles that the baked light map says are unreachable from any static light are drawn darker. Tiles a light can reach stay brighter. Light does not bleed through walls: the mask was raycast through passable tiles at editor save, including across chunk borders, so a torch on the edge of one chunk can light tiles in the next.

By day, ambient light is full and the baked mask does not darken the ground. The day/night curve (how dark “night” is, dusk length) can stay a world setting or a later tuning value; the invariant is that night uses baked reachability, not a per-frame raycast.

The world-editor night-to-day slider is the same shading function, driven by the slider instead of the clock, so an admin can preview a chunk at any light level without changing live world time.

22. Items, inventory and ground drops

22.1 Item definitions

Every obtainable object is an ItemDefinition. Stacking, uniqueness and later economy rules are data on that definition, not special cases in UI code.

ItemDefinition
- itemId
- displayName
- description
- seedValue               // base price before player-market adaptation
- stackable
- maxStackSize            // default 99 for stackable items
- uniqueInstance          // true for letters, filled cheques, and similar
- category: ingredient | intermediate | finished | document | other
- npcShopAllowed
- gatherSources
- craftingRecipe(s)
- dropTableSources
- attack?: AttackProfile  // weapons; omitted for non-weapons
- equipment?:             // worn/wielded visuals; see 21.6
    slot
    overlaySpriteId
    recolourableChannels?
    materialId?

A stackable item with no instance data merges with an identical itemId in the same container up to maxStackSize. Unique-instance items never merge; each occupies its own slot at quantity 1.

Currency is not an inventory item. Carried money is a numeric Currency balance on the player. Banked money is a numeric balance on that player's vault. Coins do not occupy inventory slots and cannot be dropped on the ground in this model.

How most items are obtained is specified later. Two source families already fit this model without changing it:

  • Ground-item spawners in the world editor, analogous to mob spawners.
  • Later harvesting from the environment by players.

Paper, blank cheques and letters are specified now because communication, banking and pigeons depend on them.

22.2 Player inventory

A player inventory has exactly 32 slots.

Inventory
- slots[32]: empty | ItemStack

ItemStack
- itemId
- quantity                 // 1 for unique-instance items
- instance?: ItemInstance  // present only when uniqueInstance is true
- origin?: ItemOrigin      // crafter or shop NPC; see 22.6

Rules:

  • A stack occupies exactly one slot, regardless of quantity.
  • Inserting a stackable item first tries to merge into an existing compatible

stack whose combined quantity would not exceed maxStackSize. Stacks are compatible only when itemId matches and origin matches (including both being empty). Any remainder needs an empty slot, or the whole action fails.

  • Moving, swapping and splitting stacks are ordinary server-validated

commands. The client never asserts the resulting inventory.

  • Inventory, wallet and vault contents are player-private UI state. They

are not part of 3×3 chunk replication. Other clients see ground items and pigeon entities, not another player's bags or a pigeon's cargo.

  • Logout and restart persist the full inventory and carried currency in

state.sqlite.

22.3 Paper and letters

Blank paper is a stackable item.

Writing consumes one paper and produces a letter: a unique-instance item whose instance data is text written by a player. A letter is not a mail record and has no inherent recipient. It is just paper with writing on it.

LetterInstance
- letterId
- authorPlayerId
- body
- writtenAt

If the paper stack's quantity is 1, the slot may be converted in place into the letter. If quantity is greater than 1, writing requires a free inventory slot for the new letter and decrements the paper stack.

Reading a letter inspects its instance data. Sending a letter is the same pigeon-cargo action used for any other item stack.

Maximum letter length is a defined game rule and can be chosen during implementation.

22.4 Dropping items

A player may drop an item stack, or part of a stack, onto their current tile.

GroundItem
- groundItemId
- tileX / tileY
- ItemStack
- droppedAt
- expiresAt               // droppedAt + WorldSettings.groundItemDespawnDuration
- source                  // player-drop | later: item-spawner
- droppedByPlayerId?

Rules:

  • Player-dropped items remain for WorldSettings.groundItemDespawnDuration

(default 10 minutes), then vanish forever.

  • Anyone may pick up a ground item. There is no owner lock and no loot-rights

delay.

  • Ground items do not block movement and do not prevent a player from

standing on that tile.

  • Pickup requires the player to stand on that tile. The command names the

groundItemId when several stacks share the tile.

  • Pickup fails if the player's inventory cannot accept the stack (no legal

merge and no empty slot). The ground item is unchanged.

  • Several distinct stacks may occupy one tile at once.
  • Later naturally spawned ground items use the same non-blocking

representation, but their lifetime and respawn belong to the item spawner rather than this 10-minute player-drop timer.

Dropped items are not ChunkLoaders and do not keep a chunk simulated.

They do survive chunk unload until expiresAt, using timestamp expiry rather than a per-tick countdown. On unload, unexpired ground items are written to state.sqlite. On load or wake, items whose expiresAt is in the past are discarded and never replicated. Simulating chunks also remove them when the timestamp elapses.

If a unique-instance item that encodes a bank reservation (a filled cheque) expires on the ground or is otherwise destroyed without being redeemed, that reservation is released and the reserved goods become available in the issuer's vault again.

22.5 Pickup and drop commands

DROP_ITEM(slotIndex, quantity?)
PICKUP_ITEM(groundItemId)

Both are intentions. The owning worker validates the actor's tile, inventory space and stack rules, then applies the result. Standing on a tile that has ground items does not pick them up automatically.

22.6 Item inspection, origin and displayed value

Hovering an item — in inventory, a shop stock list, or on the ground — shows at least:

ItemTooltip
- displayName
- description
- originLabel              // who crafted it, or the shop NPC if bought there
- currentValue             // undiscounted adapted value; see section 27

Origin is stored on the stack:

ItemOrigin
- kind: crafted | shop | unknown
- playerId?                // when crafted by a player
- npcId?                   // when bought from a shop NPC

The origin label is the crafting player's name, or the shop NPC's name when the stack was bought from that NPC. Harvested, looted or otherwise unstamped stacks use unknown and omit the origin line until later content says otherwise. Buying from a shop stamps that NPC as origin. Crafting stamps the crafter. Shop-bought goods are not treated as crafted by the NPC; the NPC name simply occupies that inspection field.

currentValue uses the same last-sale lerp as shopkeepers (section 27.6) but without the per-shop discount. It is informational. The client must not recompute it every simulation tick. The player UI may refresh displayed values at most once per minute, from the last-sale record plus seedValue. The actual shop purchase price is always computed server-side at the moment of purchase.

23. Player communication and carrier pigeons

23.1 Proximity chat is the default

Ordinary chat is spatial. A player speaks from a world position and only nearby players receive a useful version of the message. Legibility decreases as the recipient gets farther from the speaker.

Readability uses Euclidean tile distance against the 16-tile chunk size:

distance <= 8 tiles   // half a chunk: full plaintext
8 < distance < 16     // linear falloff, e.g. 12 tiles → 50% readability
distance >= 16 tiles  // a full chunk: 0% readability, no bubble

The speaker always receives their own trimmed plaintext. Other recipients receive a server-obscured copy: letters and digits may become . with probability 1 - readability; spaces and punctuation stay. At 0% readability the server sends nothing, so the client never draws a bubble.

Enter opens a bottom-of-screen line (max chatMaxCharacters, default 100). Enter again trims and sends CHAT_SAY. Escape cancels. The client shows CHAT_BUBBLE above the speaker.

For example:

Near:       I'm really far away
Farther:    I'm re...y far aw.y
Very far:   I'...re..ly..ar.aw.y
Beyond range: no message

Crucially, degradation is performed server-side. The server must not send the full plaintext to a distant client and merely ask that client to obscure it, because a modified client could then recover speech it was not supposed to understand.

A chat message therefore conceptually contains:

ChatSpeech
- messageId
- speakerEntityId
- originX / originY
- createdAt
- text

The communication service performs a spatial recipient query and derives the recipient-specific legible representation before routing it through the gateway. Chat routing is separate from normal 3×3 chunk replication, so the eventual hearing/text range does not have to equal the visual chunk-subscription radius.

23.2 Persistent player groups

Players can create permanent groups and invite other players into them. Groups are durable social entities stored in state.sqlite, with membership surviving logout and server restart.

A minimal model contains:

PlayerGroup
- groupId
- name
- owner / roles
- createdAt

PlayerGroupMember
- groupId
- playerId
- role
- joinedAt

Invite, accept, leave, kick and role-management operations are authoritative server actions.

Group membership does not create magical long-distance communication. If members are close enough, they can communicate through the normal proximity rules. Communication to distant group members means sending items — including letters — by carrier pigeon, the same mechanism available to any player.

If group-wide letter sending is later supported, it is an addressing convenience that still consumes one paper/letter item and one pigeon dispatch per recipient. The group is not a global instant chat channel.

23.3 Pigeons carry cargo, not messages

A carrier pigeon is a free physical courier. It does not send a chat packet. It carries either:

  • an amount of the sender's carried currency, or
  • exactly one item stack (a letter, a filled cheque, blank paper, or any

other stack)

One pigeon cannot carry both money and an item, and cannot carry two item stacks. Dispatching a pigeon is free, so a player who wants to move several stacks sends several pigeons one after another.

Cargo is removed from the sender immediately and placed into durable transit. A crash or restart cannot duplicate that cargo or silently erase it.

Pigeons are not inventory items. Any player may dispatch one from anywhere, provided they have valid cargo.

SendPigeon
- destination: Player(playerId) | Bank
- cargo: Money(amount) | Item(slotIndex, quantity?)

23.4 Destinations

Player destination. The pigeon flies toward a character addressed by first name and last name. The sender may type that pair, or pick a friend from their friends list to fill the same fields. On arrival:

  • Money is added to the recipient's carried Currency if they are online;

otherwise it is deposited into the recipient's bank.

  • An item stack is placed in the recipient's inventory if they are online and

have space (a legal merge or an empty slot). If they are offline or cannot accept the stack, the pigeon continues to the nearest bank and deposits the stack into the recipient's vault.

This keeps offline and full-inventory delivery durable without a separate mailbox object.

Bank destination. The pigeon flies to the nearest bank to the dispatch tile. Travel time is that aerial journey, even though every bank shares the same vault. On arrival the cargo is deposited into the sender's vault, except for the filled-cheque special case in section 24.7.

"Nearest bank" is computed from authored Bank block positions in the pinned world revision. If additional banks are added later, a pigeon sent to Bank still lands at whichever bank is closest to where it was dispatched; the goods then appear in the shared vault.

23.5 Carrier pigeon transit

A carrier pigeon must take time to cross the world; long-distance item and currency delivery is intentionally not instantaneous.

At MMO scale, however, every delivery should not keep an entire trail of regions fully stimulated merely so a pigeon can advance. The recommended model is a persistent courier transit record with world position/route/progress that can advance through dormant space using coarse path segments and timestamps.

CourierTransit
- courierId
- cargo                   // Money(amount) | ItemStack
- senderPlayerId
- destination             // Player(playerId) | Bank
- currentPosition
- route
- speed / timing state
- status

A carrier pigeon is part of the shared physical world, not a private visual belonging only to its sender or recipient. Whenever its calculated route passes through a simulating chunk, the courier should materialise there as a normal ECS Mob entity, regardless of whether the sender or recipient is nearby. Any client whose normal 3x3 chunk subscription includes that pigeon receives it like any other visible mobile entity and can therefore see unrelated pigeons flying past in the distance.

The visible pigeon does not receive ChunkLoader. It exists because the chunk is already simulating for some other reason. If it leaves the last relevant simulating chunk, its exact position/progress is folded back into the durable CourierTransit record and the ECS instance can disappear while the journey continues abstractly. If a dormant/unloaded part of its route later becomes simulated while the pigeon should currently be inside it, the owning worker materialises the pigeon at the position implied by the transit clock and route.

Dormant route                 Simulating chunk                 Dormant route

abstract transit  -------->  ECS pigeon visible to clients  -------->  abstract transit
                                  |       |       |
                               Player A Player B unrelated observer

This means a player standing halfway between sender and recipient can see the pigeon fly through their area even though the cargo has nothing to do with them. Unrelated clients receive the pigeon entity, not the cargo contents. It preserves the sense that deliveries physically cross the world without requiring thousands of deliveries to become thousands of permanent ChunkLoaders.

Because pigeons fly rather than use the ground navigation grid, their coarse route can initially be represented by direct or waypoint-based aerial segments. This makes deterministic materialisation from route + elapsed time considerably simpler than it would be for a ground-based courier.

If future gameplay allows pigeons to be intercepted, killed or rerouted anywhere along their journey, the transit model can be made progressively more detailed; that interaction is not required by the initial courier design.

23.6 Courier service

A dedicated CourierService should own durable cargo and delivery state. Simulation workers may own visible pigeon entities while the service owns the durable fact that a delivery exists.

Player action -> CourierService -> durable cargo/transit
                                  |
                                  +-> visible pigeon when needed
                                  |
                                  +-> inventory, wallet or BankService deposit

This separation is also useful for marketplace settlement, which uses the same carrier-pigeon delivery infrastructure for remote counterparties.

23.7 Character friends

Friendships are character-to-character, stored in state.sqlite. They are not account-wide. A hovering client shows only the nearby character's first name. Clicking that character opens an inspect modal with first and last name and a friend-request action.

A friend request must be accepted (or a reverse request counts as accept). Either character may remove the friendship; it then disappears for both. Incoming and outgoing requests and the friends list are shown in a Friends panel. Deleting a character clears its requests and friendships.

The friends list is an addressing book for later pigeon dispatch: pick a friend to fill first and last name, or type a name pair that the server resolves.

FriendRequest
- fromCharacterId
- toCharacterId
- createdAt

Friendship
- characterIdA   // min(id1, id2)
- characterIdB   // max(id1, id2)
- createdAt

24. Bank, cheques and shared vaults

24.1 Bank location and access

A bank exists at or near the central marketplace as an authored Bank block. Deposit, withdraw, cheque issue and in-person cheque redemption require server-validated access to a bank interaction; the bank is not a global menu usable from anywhere.

Pigeon dispatch to Bank is the exception: that command may be issued from anywhere, and the goods become available only after the pigeon arrives.

24.2 One shared vault

Each character has a single vault in state.sqlite:

CharacterVault
- characterId
- bankedCurrency
- stacks[]
- reservations[]

Capacity is unlimited: there is no slot cap. Per-stack stacking rules still apply (maxStackSize; unique instances never merge), so 200 blank paper is stored as 99 + 99 + 2 rather than one unbounded pile.

If more banks are authored later, all banks are linked. Withdrawing at bank B can retrieve goods deposited at bank A. The vault is not per-branch.

Pigeon deposits affect when goods become available, not which vault they enter. After the pigeon arrives at the nearest bank, the goods appear in the same shared vault accessible from every bank.

24.3 Deposit and withdraw

While interacting with a bank, a player may:

  • Deposit any carried currency and any inventory stacks, in whole or in part.
  • Withdraw currency into the carried wallet.
  • Withdraw an item stack, or part of a stack, into inventory, subject to the

32-slot and merge rules.

  • Claim items or currency from the account inheritance tab into this

character's vault (section 24.9).

Goods reserved by an outstanding filled cheque cannot be withdrawn by the issuer until that cheque is redeemed or voided.

24.4 Blank cheques

A player at a bank may request blank cheques.

  • Blank cheques are a stackable item with maxStackSize 99.
  • The bank counts blank cheques already in the player's inventory (not

the vault) and issues only enough to bring that total to 99.

  • If the player already holds 99, the bank issues none.
  • Issued cheques go into inventory, merging into an existing blank-cheque

stack when possible. If the player holds none and has no empty slot, the request fails.

The bank will not issue more than 99 blank cheques into inventory, even on repeated requests.

24.5 Filling a cheque

Using a blank cheque at a bank lets the issuer pick vault goods and a quantity. For stackable items they choose an itemId and quantity; the quantity may be larger than one maxStackSize, and the reservation covers that many available (unreserved) items of that type in the vault. For unique-instance items they choose that exact instance and the quantity is 1.

FilledChequeInstance
- chequeId
- issuerPlayerId
- itemId
- quantity
- instance?: ItemInstance   // set when the reserved goods are unique
- createdAt

Filling:

1. Validates that the vault has at least quantity of that item available (not already reserved). Unique instances must still be present and unreserved. 2. Reserves those goods in the issuer's vault. Reserved goods cannot be withdrawn, sold or reserved again. 3. Consumes one blank cheque. If that was the last cheque in the slot, the slot becomes the filled cheque in place; otherwise a free slot is required for the filled cheque.

A filled cheque is a unique-instance bearer item. It does not stack. Whoever holds it may redeem it. Cheques specify vault items and a quantity, not carried currency. Money is moved with a pigeon, or by depositing and withdrawing at a bank.

24.6 Redeeming a cheque in person

The bearer interacts with any bank and redeems the filled cheque.

  • The server moves the reserved goods from the issuer's vault into the

bearer's inventory, subject to inventory space. A quantity larger than maxStackSize becomes as many stacks as needed.

  • The cheque item is consumed.
  • If inventory cannot accept the resulting stacks, redemption fails and both

cheque and reservation remain unchanged.

The bearer may then deposit those goods into their own vault if they wish.

24.7 Redeeming a cheque by pigeon

If the bearer dispatches a pigeon whose cargo is a filled cheque and whose destination is Bank:

  • The pigeon flies to the nearest bank from the dispatch tile.
  • On arrival, BankService transfers the reserved goods from the issuer's

vault into the pigeon's sender's vault.

  • The cheque is consumed in transit; it is not deposited as an item.

The receiver of the transfer is whoever sent that pigeon, not the original cheque issuer. This is how a cheque moves goods from one vault to another without the receiver standing at a bank.

Sending a filled cheque to a player delivers the cheque item itself (or into that player's bank if they cannot hold it). It does not redeem it.

24.8 Bank service

Vault mutation, cheque issue, reservation, in-person redemption and pigeon-arrival deposits are owned by a single authoritative BankService (or an equivalently serialised service) so two concurrent withdrawals, cheque fills or pigeon arrivals cannot double-spend the same goods.

Bank interaction or pigeon arrival
        |
        v
BankService
  - shared vault
  - reservations
  - cheque issue / redeem
        |
        +-> inventory / currency on the acting player when in person
        |
        +-> vault credit on pigeon arrival

Cheque identifiers are server-issued. A client cannot forge a claim against another player's vault.

24.9 Inheritance bank tab

Each account has one inheritance tab, separate from every character vault:

AccountInheritance
- accountId
- currency
- stacks[]

It is written only when a character of that account is permanently deleted (section 14.6). Any of that player's living characters can move stacks and currency from this tab into their own vault at a bank. They cannot deposit into inheritance except through character deletion.

25. Central marketplace and order matching

25.1 Marketplace location

A central marketplace exists at or near the centre of the game world. Creating, modifying or cancelling market orders requires server-validated access to the marketplace interaction; the marketplace is not intended to be a global menu that can be used from anywhere.

Orders themselves remain durable after the player leaves the marketplace or logs out.

25.2 No public list of sell orders

The market is an order book, but players do not browse a list of individual items currently offered for sale.

A seller submits:

SellOrder
- item / item definition
- quantity
- minimum unit/total price

A buyer submits:

BuyOrder
- requested item / matching criteria
- quantity
- maximum unit/total price

The UI may know which item types exist and may eventually show historical data, but it does not expose the live asks in a way that lets a buyer simply pick a listed seller.

25.3 Escrow

Market orders escrow the asset required to honour them. Escrow is taken from carried inventory and carried currency. The marketplace sits next to the bank, so a player can withdraw from the vault immediately before placing an order.

  • Creating a sell order removes/reserves the offered item stack from the

seller's inventory.

  • Creating a buy order removes/reserves the buyer's maximum offered currency.
  • Cancelling an unmatched order returns the escrowed asset through the defined

settlement/delivery rules.

This prevents double spending, selling the same item twice, or a buyer spending currency after placing a bid.

25.4 Matching rules

A buy and sell order match when:

buyerMaximum >= sellerMinimum

Sell orders are considered cheapest first. Within the same minimum price, a stable creation sequence/FIFO rule should be used unless later game rules choose otherwise.

For a symmetric order book, buy orders are naturally prioritised by highest maximum bid and then oldest sequence. This means a newly submitted sell order matches the best compatible existing bid, while a newly submitted buy order matches the cheapest compatible existing ask.

The trade price is exactly the midpoint between the two limits:

tradePrice = midpoint(buyerMaximum, sellerMinimum)

Example:

Seller minimum:  80
Buyer maximum:  100
Trade price:      90

The exact rounding rule when integer currency produces a half-unit midpoint is a defined-but-still-open game rule and must be deterministic.

25.5 Immediate side versus pigeon side

The order that is submitted last is the order that triggers the match.

The player who submitted that matching order receives the acquired asset immediately because they are currently present at the marketplace interaction (item stack into inventory, or currency into the carried wallet). The pre-existing counterparty receives their acquired item or currency through a carrier pigeon whose destination is Bank, landing at the nearest bank to the marketplace. On arrival the settlement is deposited into that counterparty's shared vault. This remains valid if they are offline.

Existing sell + new matching buy
-> new buyer receives item immediately
-> existing seller receives payment by pigeon to bank

Existing buy + new matching sell
-> new seller receives payment immediately
-> existing buyer receives item by pigeon to bank

If a trade requires more than one item stack (for example a quantity that does not fit in a single maxStackSize), the older counterparty receives as many free sequential pigeons as needed. Each pigeon still carries only one stack or only currency.

Any unused part of buy-order currency escrow caused by the midpoint price is returned immediately to the triggering player when they are the buyer, and returned by the settlement pigeon into the older counterparty's vault when they were the buyer.

25.6 Market service and atomicity

Marketplace matching should not live inside an arbitrary region worker. Use a single authoritative MarketService (or an equivalently serialised partitioned service later) so two simultaneous orders cannot both consume the same escrow.

Order insertion, matching, escrow movement and creation of the resulting settlement deliveries are committed atomically in state.sqlite.

Conceptually:

Marketplace interaction
        |
        v
MarketService
  - durable order book
  - escrow
  - deterministic matching
  - trade record
        |
        +-> immediate settlement to triggering player's inventory or wallet
        |
        +-> CourierService pigeon to Bank for the older counterparty
        |
        +-> last-sale index update for that itemId

The system should also retain an immutable trade record for auditing and recovery.

25.7 Last player-market sale per item

Each successful player-market match updates a single durable record for that itemId. There is no price history series — only the latest sale:

ItemLastMarketSale
- itemId
- lastTradePrice           // unit price of that match (the midpoint)
- lastTradeAt
- priceFrom                // evaluated undiscounted value at lastTradeAt

priceFrom is not a history log. It is the lerp origin captured at the moment of this sale so the displayed price does not jump back to seed when a new trade occurs:

1. Evaluate the current undiscounted value at now using the previous last-sale record (or seedValue if none exists). 2. Store that value as priceFrom, store the new trade's unit price as lastTradePrice, and store now as lastTradeAt.

Shopkeepers and item tooltips both read this record. They do not tick it; they evaluate it from timestamps when a shop is opened, a purchase is attempted, or a tooltip refresh is requested.

26. Combat

26.1 Every combatant can attack

Players, enemies, animals and any other mobile with a Combat component can attack. Shopkeepers and other non-fighting NPCs simply omit Combat, or never issue attack commands.

Attacking is an intention. The client (or AI, or a future script) sends ATTACK(targetEntityId). The owning worker validates range, line-of-use, the current attack profile and cooldown, then resolves hit and damage authoritatively. The client never supplies a hit result or a damage number.

Cross-worker attacks already use REMOTE_ACTION(attack intent): the worker that owns the target applies the authoritative result.

26.2 Attack profiles

The current attack comes from the wielder's selected profile: a wielded weapon's AttackProfile, a selected spell, or a default unarmed melee profile when nothing is wielded.

AttackProfile
- attackId
- mode: melee | ranged | magic
- rangeTiles               // melee is always 1; ranged/magic from the item or spell
- hitSkillId
- damageSkillId
SpellDefinition
- spellId
- displayName
- AttackProfile            // mode = magic, hitSkillId = Magic, damageSkillId = Mind
- other costs/effects      // later content

Typical weapon mappings:

Sword     -> melee,  range 1,           hit Swordfighting, damage Strength
Axe       -> melee,  range 1,           hit Axefighting,   damage Strength
Bow       -> ranged, range from item,   hit Archery,       damage Dexterity
Spell     -> magic,  range from spell,  hit Magic,         damage Mind
Unarmed   -> melee,  range 1,           hit Unarmed,       damage Strength

The exact weapon and spell catalogue is content. The pairing rule is not: melee weapons use a weapon skill plus Strength, ranged weapons use a weapon skill plus Dexterity, and spells use Magic plus Mind.

EquipItem(slotIndex) moves a legal item from inventory into the matching equipment slot (section 21.6). The weapon slot supplies the current AttackProfile. SelectSpell(spellId) selects a spell the actor is allowed to use. The selected profile determines range and both skills.

26.3 Melee range

A melee attack is legal only when the attacker stands on one of the eight tiles surrounding the target's tile: orthogonal or diagonal, Chebyshev distance exactly 1. The attacker cannot melee from the target's own tile.

. . .
. T .     attacker must occupy one of the eight `.` tiles
. . .

This adjacency rule is independent of whether ordinary walking is four- or eight-directional.

26.4 Ranged attacks and spells

Ranged weapons and spells may fire from further away. Maximum Chebyshev distance is rangeTiles on that item or spell. Distance 0 (same tile) is not a legal ranged/spell attack unless a later exception is defined.

The attacker must still occupy a simulating chunk and satisfy any later line-of-sight rule. Exact obstruction rules are an open content decision; range itself is not.

26.5 Hit roll

Whether the attack lands is a server-side roll driven by the hit skill of the current profile (Swordfighting, Axefighting, Archery, Magic, Unarmed, and so on). The client does not roll.

The exact hit curve, any defender contribution from Defence, and the RNG are later tuning. The invariant is that the hit chance is a function of the attacker's hit-skill level, not of Strength, Dexterity or Mind.

A miss deals no damage.

26.6 Damage

On a hit, damage is determined by the damage skill:

  • Melee → Strength
  • Ranged → Dexterity
  • Magic → Mind

Weapon or spell base damage and the defender's mitigation (including whether Defence reduces damage) are later tuning. The governing damage skill is not.

26.7 Experience split

When a player successfully hits, the attack's XP award is split equally between the hit skill and the damage skill:

totalXp = attack xp formula for this successful hit
hitSkill     += totalXp / 2
damageSkill  += totalXp / 2

Example: a sword hit awards half its XP to Swordfighting and half to Strength. A bow hit splits Archery and Dexterity. A spell hit splits Magic and Mind.

If an unusual profile ever named the same skill twice, XP is awarded once, not doubled. Misses award no combat XP. Ordinary mobs do not earn XP; their Skills component is filled from the mob archetype and stays at those levels.

Non-combat actions remain single-skill as in section 27.4.

26.8 Mob combat stats

MobDefinition
- ...
- skillLevels: { skillId → level }
- defaultAttack: attackId | unarmed

A wolf might have Unarmed and Strength. An archer guard might have Archery and Dexterity. Those levels feed the same hit and damage resolution as players.

27. Player-driven economy and skill progression

27.1 Item-source philosophy

The economy is intentionally player-driven.

Normal NPC shops should sell only basic ingredients. The vast majority of materials are gathered directly from the world by players. Finished goods are normally produced by player crafting/professions.

The only normal non-player source of finished items is enemy or boss loot.

This gives four broad source paths, with ground-item spawners as an additional early world source once content defines them:

World gathering / harvesting -> ingredients
Ground-item spawners --------> some world items, later specified
Basic NPC shops -------------> limited basic ingredients
Player production -----------> intermediate/final products
Enemies and bosses ----------> loot, including possible finished items

Stacking, unique instances, letters and cheques are defined in section 22. Economy-facing fields remain on the same ItemDefinition:

ItemDefinition
- itemId
- displayName / description / seedValue
- stackable / maxStackSize / uniqueInstance
- category: ingredient | intermediate | finished | document | other
- npcShopAllowed
- gatherSources
- craftingRecipe(s)
- dropTableSources
- attack?: AttackProfile
- equipment?: slot / overlaySpriteId / recolourableChannels / materialId

Content validation can then reject an ordinary shop inventory that accidentally contains a finished product unless explicitly permitted by a future exception.

27.2 No player classes

Players do not choose a class. Capabilities and progression come from independent skills.

Examples include:

  • Swordfighting, Axefighting, Archery, Magic, Unarmed
  • Strength, Dexterity, Mind
  • Defence
  • Lumbering
  • Fishing
  • Smithing

The final skill list is game content and is not limited to skills found in any particular inspiration game.

27.3 Skill state

Skill progression is persistent player state.

SkillProgress
- skillId
- xp

Level should preferably be derived from XP and the skill's level curve rather than stored as an independent source of truth, although it may be cached.

SkillDefinition
- skillId
- displayName
- levelCurve
- maxLevel (if any)

27.4 Actions are governed by skills

Every gameplay action that participates in progression is associated with a governing skill. Combat attacks are the explicit exception: they have a hit skill and a damage skill, and split XP equally between them (section 26.7).

ActionDefinition
- actionId
- governingSkillId
- requiredLevel
- xpAward / xpFormula
- other requirements

Examples:

Cut tree        -> Lumbering
Catch fish      -> Fishing
Forge sword     -> Smithing
Sword hit       -> Swordfighting + Strength (equal split)
Bow hit         -> Archery + Dexterity (equal split)
Spell hit       -> Magic + Mind (equal split)
Defensive act   -> Defence

The server validates the action, performs the authoritative outcome, and then awards XP according to the action result. A client cannot claim XP independently.

27.5 Skills replace class restrictions

Equipment, recipes, actions, gathering nodes and other content may require skill levels, but there is no permanent class gate. A player can train any combination of skills over time.

This also fits the future scripting model: scripts issue normal actions, and successful scripted actions use exactly the same skill checks and XP rules as manual player actions.

27.6 NPC shops and market-adapted prices

Named shop NPCs can sell items to players. They are not the player marketplace and they do not expose live sell orders. A shop interaction requires being at that NPC.

Stock remains constrained by npcShopAllowed and the ingredient-only rule in 27.1. Each shop NPC has a hidden discount that players never see:

ShopNpc
- npcId
- hiddenDiscount           // multiplier, e.g. 0.9; not shown to clients
- stock[]                  // itemIds this NPC sells

Until an itemId has a player-market last-sale record, the undiscounted value is seedValue from the item definition.

When a last-sale record exists, both tooltips and shops evaluate a timestamp lerp that does not require a per-tick update:

t = min(1, (now - lastTradeAt) / WorldSettings.shopPriceLerpDuration)
undiscounted = lerp(priceFrom, lastTradePrice, t)
shopPrice    = undiscounted * thatNpc.hiddenDiscount

lerp(a, b, t) = a + (b - a) * t. After the configured lerp duration (default one hour), t is capped at 100% and the value rests on the last player-market unit price (times discount, for shops) until another player-market sale occurs.

A new player-market sale captures the then-current undiscounted value as priceFrom (section 25.7), so the lerp restarts toward the new last price without jumping back to seed.

Integer currency must be rounded deterministically at evaluation time. Shop purchase price is computed on the server at the instant of BuyFromShop. Displayed tooltip value is the undiscounted figure and may be refreshed at most once per minute (section 22.6).

Buying from a shop removes the listed price from the player's carried currency, puts the stack in inventory subject to the 32-slot rules, and stamps ItemOrigin.kind = shop with that NPC. Shops in this model sell to players; they do not buy player goods unless a later iteration adds that.

28. Suggested implementation phases

Phase 1 — Single-worker playable core

  • World coordinate helpers, 16×16 chunks and 4×4-chunk regions.
  • Ground/block tile model and chunk spatial occupancy.
  • Basic ECS and fixed simulation tick.
  • ChunkLoader reference counting and sleeping/unloading.
  • Isolated simulation workers behind a clone-on-boundary protocol

(in-process default; worker_threads optional).

  • world.sqlite read path and state.sqlite persistence service.
  • Admin world editor: chunk navigation, open/closed flag, default grass for

unsaved chunks, ground/block paint, light-emitting blocks, baked cross-chunk light maps, night-to-day preview slider, world settings modal with live apply and a settings edit log, per-chunk changelog, chunk save to pending revision.

  • SpawnerSystem for at least one non-persistent mob archetype.
  • WebSocket gateway, stub admin-<n> auth until auth.timfalken.com,

character create/select/delete, authoritative command queue and 3×3 chunk replication.

  • Click-to-move with server-side A\*, global walk/run cadence (default 2

tiles/s walk, run every movement tick, walk every other), and SetGait.

  • FrameworkV3 git submodule at client/frameworkv3, built first, then a

game-specific client on top of it with 16×16 sprites, load-time and CI rejection of wrong-sized art (including equipment overlays and recolour masks), layered worn equipment with material recolouring, a player-centered viewport with bounded zoom, client-only lerp of tile-to-tile movement, and night shading from baked light maps.

  • 32-slot player inventory, stack merging, drop/pickup, and 10-minute

non-blocking ground items.

  • Paper items that can be written into unique letter items.
  • Basic proximity chat with server-side distance degradation.
  • Persistent player skill state, including Strength, Dexterity and Mind, and

at least a small initial set of skill-governed actions.

  • Melee and ranged/spell attack validation (8-tile melee adjacency, item/spell

range), server-side hit rolls, damage from the matching damage skill, and equal XP split on a successful player hit.

  • Graceful forced-unload shutdown.

Phase 2 — Operations and live deployment

  • RestartScheduler and player-visible scheduled restart state.
  • origin/master change detection.
  • systemd service supervision and conditional deployment hook.
  • World-revision activation on restart.
  • Admin immediate restart.
  • Migration, backup and startup readiness checks.

Phase 3 — Multi-worker world

  • Multiple isolated simulation workers and neighbour-sticky region ownership

(shipped); dynamic load rebalance remains.

  • Cross-worker entity transfers (shipped).
  • Border ghosts for occupancy/pathfinding (shipped); remote combat actions remain.
  • Gateway subscriptions spanning multiple workers (shipped).
  • Load metrics and neighbour-aware region balancing remain.

Phase 4 — World depth, social systems and economy

  • Persistent named NPCs and other persistent mob archetypes.
  • Spawner persistent-instance index and duplicate prevention.
  • Optional durable gameplay chunk overrides, written only on unload.
  • Hierarchical pathfinding if long-distance autonomous travel needs it.
  • Persistent player groups and invitations.
  • Carrier-pigeon cargo transit: free dispatch, money or one item stack,

player or nearest-bank destinations, including offline/full-inventory fallback to the recipient vault.

  • Shared unlimited character bank near the marketplace, account

inheritance tab on character delete, blank cheques filled to 99, reserved filled cheques, in-person redemption and pigeon-to-bank cheque transfers.

  • Central marketplace, escrow, deterministic order matching, pigeon-to-bank

settlement for the older counterparty, and a per-item last-sale record for shop/tooltip adaptation.

  • NPC shops that sell npcShopAllowed stock at seed value lerped toward the

last player-market price over shopPriceLerpDuration, with a hidden per-shop discount.

  • Item inspection: name, description, origin (crafter or shop NPC) and

undiscounted current value, refreshed at most once per minute.

  • Player crafting/gathering economy rules and shop-content validation.
  • Broader skill catalogue, progression curves and skill-gated content.

Phase 5 — Player scripting

  • Custom language grammar/compiler/interpreter.
  • ScriptController and event API.
  • CPU/memory/query quotas and sandboxing.
  • Online scripted control mode.
  • Offline retained player entities with expiry and ChunkLoader

behaviour.

  • Persisted/restart-safe script state.

29. Core invariants

InvariantRule
Server authorityClients send intent; the server computes and owns outcomes.
Region ownershipExactly one simulation worker authoritatively owns a region.
Entity ownershipExactly one worker authoritatively owns an entity.
Remote mutationWorkers never directly mutate remote authoritative state.
Spatial separationRegion residency, chunk simulation and client visibility remain distinct.
Persistence separationPersistent and ChunkLoader are independent entity traits.
Chunk persistenceNormal dirty chunk state is written on unload, not periodically.
World authoringEditor changes create pending authored state; the running server stays pinned to its startup revision. Each chunk save appends an admin-attributed diff changelog.
Restart pathPlanned restart force-unloads the world and reuses the ordinary unload save path.
ControlHuman and future scripted control both emit validated action commands.
DeploymentThe game exits gracefully; systemd relaunches it and only pulls/builds when an intentional deployment manifest requests it.
Client architectureFrameworkV3 is a git submodule under client/frameworkv3, built before game client code; backend ECS internals do not become the client object model.
SpritesWorld sprites may be any size. Pivot is horizontal centre and 8px from the sprite bottom, on the tile centre. Ground/block types load visual states from a per-type folder (first alphabetical PNG is default). Sheets use frames, framesPerRow, animationSpeed. Blocks and mobiles Y-sort north-behind-south.
AppearanceVisible gear is layered 16×16 overlays on the mob; recolourable channels (such as metal) use material colour without duplicate art sets. Nearby clients receive appearance layers, not another player's inventory.
Play cameraThe play viewport is centered on the local player. Only the admin world editor uses a free chunk camera.
MovementAll ground mobiles share a global walk/run cadence from world settings; the server commits integer tiles; clients lerp for presentation only.
World timeWorld calendar time is server time minus 1200 years. Night darkens tiles the baked light map cannot reach.
World settingsTick timers and global constants (including night darkness) are authored in the editor modal, applied immediately on save, and recorded in a settings edit log. Chunk map data remains revision-pinned.
Baked lightStatic light reach is raycast through passable tiles on chunk save, may cross chunks, and is not recomputed every tick.
Ground itemsPlayer drops last groundItemDespawnDuration (default 10 minutes), block nobody, and are picked up only by a player standing on that tile.
Shop pricesNPC shop prices lerp from the captured pre-sale value toward the last player-market unit price over shopPriceLerpDuration (default one hour), times a hidden per-shop discount.
Proximity speechDistant clients never receive unobscured plaintext that game rules say they cannot understand.
Courier cargoPigeons carry money or one item stack, never a chat packet; cargo is durable in transit and remains delayed.
InventoryA player has 32 slots; a stack occupies one slot; the client never asserts inventory, wallet or vault results.
Shared bankEvery bank reads the same character vault; pigeon deposits become available only after arrival at the nearest bank.
Closed chunksClosed or never-edited chunks are visible but not enterable; never-edited terrain is default grass with no blocks.
AccountsLogin is auth.timfalken.com (or admin-<n> stub). Characters belong to an account; one may be in the world at a time.
NamesSurnames are globally unique per account; first+last is unique per account; names free only after permanent delete.
InheritanceDeleted characters dump inventory, equipment, wallet and vault into an account inheritance tab other characters can claim.
ChequesFilling a cheque reserves vault goods; the bearer item is the claim; destruction without redemption releases the reservation.
Marketplace escrowEvery open order is fully backed by escrow and matching/settlement is atomic and deterministic.
CombatMelee requires an 8-neighbour tile; ranged/spell range comes from the item or spell; hit uses the weapon skill; damage uses Strength, Dexterity or Mind.
ProgressionPlayers have no classes; non-combat actions award XP to one governing skill; a successful attack splits XP equally between hit and damage skills.

30. Important edge cases to preserve during implementation

  • A ChunkLoader crossing a region boundary can change

residency/simulation references and worker ownership in the same tick; ordering must avoid temporary double ownership.

  • A player at a worker boundary may receive visible chunks from multiple

workers without moving ownership solely for rendering.

  • A planned restart must ignore normal ChunkLoader retention when

forcing the world to unload.

  • A world-editor save must never cause newly loaded chunks in the

current process to use the pending revision. It must append a changelog record naming the admin, timestamp and tile diffs.

  • Pathfinding and player movement must reject tiles in closed or

never-edited chunks even when those chunks are in the 3×3 view.

  • Two accounts must not claim the same surname. One account may reuse its

surname; first+last must stay unique on that account until permanent delete.

  • Marking a character for deletion must not free the name or move items

until the delay elapses. Cancelling must restore playability.

  • Character deletion must notify the account email (or log, on stub auth).

Permanent delete must void that character's issued cheques, then move inventory, equipment, wallet and vault into the account inheritance tab.

  • Saving a chunk must rebake that chunk's light map and any neighbour

chunks within max light range, using passable-tile raycasts. Light from a source in chunk A may appear in chunk B.

  • A mob definition must not carry its own walk/run speed; gait only

selects every-other vs every movement tick on the global cadence.

  • World-settings saves must not apply to the live process; they wait for

the same pending-revision restart as chunk edits.

  • Night shading must not light a tile the baked mask marks unreachable,

even if a torch is nearby through a wall.

  • Oversized block and mob sprites must Y-sort so objects higher on the

screen draw behind objects lower on the screen. Closed-chunk edges facing an open chunk must show a red border in the client.

  • Equipping must not leave two items in the same equipment slot. Unequip

into a full inventory must fail and leave the item worn.

  • Nearby clients must not receive another player's inventory in order to

draw their armour; appearance layers and material ids are sufficient.

  • A client build without client/frameworkv3 initialized must fail rather

than silently using some other FrameworkV3 install.

  • Client interpolation of movement must not be treated as authority. Combat

range and pickup use the server tile, not the lerped draw position.

  • The play camera must remain centered on the local player. Zoom must not

expand the subscribed chunk set.

  • A persistent mob spawned by a spawner must not be duplicated merely

because it moved out of the spawner’s loaded area.

  • A non-persistent mob disappears when its chunk is actually unloaded,

not merely when it becomes dormant.

  • If a persistent ChunkLoader or offline scripted player exists after

restart, startup must discover it from an index without loading the entire world.

  • A pending code update followed by an unrelated Node.js crash must

restart the currently deployed commit rather than deploying early.

  • Negative coordinates, daylight-saving midnight calculation, duplicate

transfer messages and failed deployment migrations should all have explicit tests.

  • Proximity chat degradation must happen before plaintext reaches an unauthorised

distant client; rendering-only obfuscation is not sufficient.

  • Carrier-pigeon deliveries must survive restarts and recipient logout without

requiring every traversed chunk to remain stimulated.

  • A pigeon carrying an item to a player whose inventory cannot accept it must

not destroy the cargo; it deposits into that player's vault via the nearest bank.

  • Two concurrent bank withdrawals, cheque fills or pigeon-arrival deposits must

not spend the same vault goods twice.

  • Filling two cheques against the same vault stack must reserve disjoint

quantities or reject the second fill.

  • A filled cheque that expires on the ground must release its reservation and

must not remain redeemable.

  • A player-dropped ground item must not block movement, must not keep its chunk

loaded, and must still be present after a chunk unload/reload if expiresAt has not passed.

  • Pickup of a ground item from a tile the player is not standing on must fail.
  • Requesting blank cheques must never raise the player's carried blank-cheque

count above 99.

  • A marketplace match must atomically consume both escrows exactly once, even if

two compatible orders arrive concurrently.

  • A matching market order from an online player may settle immediately for that

player while the older/offline counterparty's delivery remains durable.

  • Skill XP is awarded only after authoritative action resolution, never directly

from a client-reported result. A successful player attack splits that XP; a miss awards none.

  • A melee attack from the target's own tile, or from Chebyshev distance greater

than 1, must fail. A ranged or spell attack beyond that item or spell's rangeTiles must fail.

  • A new player-market sale must capture the then-current undiscounted lerp

value as priceFrom so shop and tooltip prices do not jump back to seed.

  • Two shop NPCs may charge different prices for the same item at the same

instant because each applies its own hidden discount to the same lerp.

  • Item tooltip value must not be recomputed every tick; a one-minute refresh

is sufficient. Purchase price is still evaluated at the moment of buy.

31. Decisions through version 0.12

  • Chunk persistence is unload-driven rather than periodic.
  • The authored tile model has separate visual ground and functional

block layers.

  • Mobile actors remain ECS entities and are not authored as painted tile

contents.

  • Spawner blocks are editor-placeable and configurable per instance;

persistence belongs to the spawned mob type.

  • world.sqlite is an authored, revisioned world source; state.sqlite

holds runtime durable state.

  • Editor changes are staged for activation on restart instead of

hot-patching the running world.

  • Code/world changes schedule a player-visible midnight restart; admins

can trigger the same graceful pipeline immediately.

  • Git pull/build/relaunch belongs to systemd supervision after the

game process has safely exited.

  • Deployment is manifest-driven: crash recovery restarts the currently

checked-out commit, while only an intentional deployment restart may fast-forward master.

  • Future player scripting is modelled as an alternative controller

producing normal server action commands.

  • Offline scripted players may remain in-world as ChunkLoaders until

death or expiry and must survive planned restarts through persistence.

  • The player client is built on FrameworkV3, included as the git submodule

client/frameworkv3 and built first so this game's client code can layer on top. The client does not need an ECS and consumes protocol state independently of backend ECS storage. The Node.js server does not import FrameworkV3.

  • World sprites may be any pixel size. Each is placed with a pivot at

horizontal centre and 8 pixels from the sprite bottom, on the tile centre. Blocks and mobiles are Y-sorted. The player may zoom the whole viewport within configured bounds; sprites are not scaled individually.

  • Visible equipment is drawn as extra 16×16 layers on the mob, including

players. Worn items occupy equipment slots, not the 32 inventory slots. Nearby clients replicate appearance layers only, never another player's inventory.

  • Recolourable gear (metal armour) shares one overlay sprite and a 16×16

channel mask. Material definitions supply the metal colour; luminance of the overlay is preserved. Iron and steel plate are different items with the same art and different materialId.

  • The play camera is always centered on the local player. The admin world

editor is the only exception, and it frames one chunk at a time.

  • Authoritative movement is a tile-to-tile jump on a global cadence:

default walk 2 tiles/s, run double. Walk steps every other movement tick; run steps every movement tick. Mobs do not set their own speed. Clients lerp for visuals only and never send interpolated positions.

  • Admins edit global tick timers and constants in a world-settings modal.

Saving applies those values immediately to the live process and appends a settings changelog. Chunk map saves still wait on the pending world revision.

  • World calendar time is server time minus 1200 years, same IANA zone as

midnight restarts. At night the client darkens tiles the baked light map cannot reach.

  • Static light is baked on chunk save by raycast through passable tiles,

including across chunk borders. The editor has a night-to-day slider for preview only.

  • Each world-editor chunk save stores who edited it, when, and a bullet

diff of ground changes, block placements, block replacements and block removals at world tile coordinates.

  • Default speech is proximity-based and becomes less legible with distance.

Long-distance exchange is physical: a pigeon carries money or one item stack. A letter is paper with player-written text, not a separate mail record.

  • Permanent player groups are social/addressing structures and do not create an

instant global chat channel.

  • Carrier-pigeon transit is persistent but does not automatically keep every

traversed chunk simulated. Whenever a pigeon passes through a chunk that is already simulating, it materialises as an ECS Mob and is visible to any nearby client whose normal chunk subscription includes it, even if that client is unrelated to the delivery. Unrelated clients do not receive cargo contents.

  • A player has a 32-slot inventory. Stackable items occupy one slot. Currency is

a numeric wallet/vault balance, not an inventory item.

  • Player-dropped items lie on the tile for groundItemDespawnDuration

(default 10 minutes), block nobody, and may be picked up by anyone standing on that tile. They survive unload until expiry via timestamps.

  • The bank near the marketplace holds an unlimited character vault.

Later banks are linked to the same vault. Pigeons may deposit money or one stack into the sender's vault after arriving at the nearest bank. An account-level inheritance tab receives a deleted character's goods.

  • Blank cheques are issued at a bank up to a carried total of 99. Filling a

cheque reserves a vault item quantity. The filled cheque is a bearer item. In-person redemption withdraws into the bearer's inventory. Sending the cheque to the bank by pigeon transfers the reserved goods into the pigeon's sender's vault.

  • The central marketplace hides individual live sell listings and matches durable

escrowed buy/sell orders at the midpoint of compatible bid/ask limits. Quantities are item stacks.

  • The newest matching market participant receives the trade result locally; the

older counterparty receives theirs by pigeon into their bank.

  • NPC shops remain restricted to npcShopAllowed basic ingredients. They sell

to players at lerp(priceFrom, lastTradePrice, min(1, (now - lastTradeAt) / shopPriceLerpDuration)) times a hidden per-shop discount. With no player-market sale yet, the undiscounted value is seedValue. Tooltips use the same lerp without the discount and refresh at most once per minute.

  • Hovering an item shows name, description, origin (crafter, or shop NPC name

if bought there) and current undiscounted value.

  • All combatants can attack. Melee requires standing on one of the eight

neighbouring tiles. Ranged attacks and spells use the item's or spell's range. The hit roll uses the weapon skill; damage uses Strength (melee), Dexterity (ranged) or Mind (magic). Successful player-attack XP is split equally between those two skills.

  • Player progression is skill-based rather than class-based. Non-combat

actions award XP to one governing skill; combat hits split XP as above.

  • Never-edited chunks are default grass, no blocks, and closed. The

editor opens or closes each chunk. Closed chunks are visible but not enterable.

  • Accounts authenticate at auth.timfalken.com. Until that service is up,

each connection is stub admin-<n> (n = connected client count including this one) and is treated as admin.

  • An account has unlimited characters and plays one at a time. Creation

takes first name (not globally unique), last name (globally unique to the account, reusable on that account's other characters), and male/female. first+last must be unique for that account. This setup may change later.

  • Character deletion is a 24-hour (configurable) delay with email notify

and cancel. Permanent delete frees names and moves inventory, equipment, wallet and vault to the account inheritance tab, which any of that player's characters can claim into their own vault.

32. Open design decisions for later iterations

These do not block the initial implementation, but should eventually be specified explicitly:

  • Whether multiple mobile entities may occupy one tile and, if so, which

categories can overlap.

  • Whether player movement is four-direction only or also supports

diagonals. Combat melee adjacency already includes diagonals.

  • Exact hit-chance and damage curves, attack intervals/cooldowns, whether

Defence modifies incoming hit chance or damage, and ranged/spell line-of-sight or obstruction rules.

  • Deterministic rounding when shop discount or lerp produces a fractional

currency amount.

  • Exact equipment slot list, per-slot draw order exceptions (cloaks,

two-handed weapons), and whether worn overlays have facing frames to match the mob.

  • Additional recolour channels beyond metal (for example cloth dyes) and

the exact luminance-preserving remap function.

  • Exact camera zoom minimum, maximum and whether zoom is restricted to

integer steps.

  • Exact night ambient curve (how dark, dusk length) and whether baked light

stores a boolean reach mask or a distance/falloff value per tile.

  • Whether opening a door at runtime should rebake or ignore static light.
  • Exact simulation tick rate stays a world setting; lower-frequency AI and

spawner cadences can still be tuned independently.

  • Exact world/chunk binary serialisation format and schema/version

migration strategy.

  • Whether gameplay can permanently modify ground/block tiles in the

initial release.

  • Spawner timing rules, spawn-point restrictions and behaviour when

persistent spawned mobs travel very far away.

  • World-editor undo/redo and rollback UI. The per-chunk changelog is an audit

log, not by itself an undo stack.

  • Exact restart warning intervals and whether admins can

cancel/reschedule a planned restart.

  • Worker rebalance thresholds and whether regions may migrate while

players are actively crossing their boundaries.

  • Future scripting language syntax, event model and resource quotas.
  • Group naming/roles, membership limits and whether group-wide letter sending

is offered as an addressing convenience that still dispatches one pigeon and consumes one paper/letter per recipient.

  • Whether pigeons can eventually be intercepted, killed or redirected in transit.
  • Marketplace partial fills, cancellation rules, fees/taxes (if any),

tie-breaking details and midpoint rounding for indivisible currency.

  • Whether market price history or aggregate statistics are visible despite live

order listings remaining hidden.

  • Initial skill catalogue, XP curves, level caps, action XP formulas and the

remaining interpretation of skills such as Defence.

  • Maximum letter body length and whether writing paper requires a desk or can be

done from inventory anywhere.

  • Exact item catalogue, which items stack, per-item maxStackSize exceptions,

harvest interactions and ground-item spawner parameters.

  • Whether death drops inventory, and whether dropped unique items other than

cheques have destruction side-effects.

  • Whether the issuer can void a filled cheque without the bearer item being

destroyed, and whether cheques can ever represent currency rather than items.

  • Whether a short dispatch interval is needed so many pigeons cannot leave in a

single tick, even though sending remains free.

  • New-character spawn location (must be an open chunk) and name length /

allowed-character rules.

  • Later changes to character creation beyond first name, last name and sex.

33. Architectural summary

ECS → what an entity is and what systems can act on it Chunk → tile data, spatial lookup, simulation and client subscription Region → residency and simulation-worker ownership Coordinator→ where regions execute Gateway → stable client connections, auth, character select, and command/update routing world.sqlite→ authored versioned ground/block/spawner/light/settings world; unedited chunks are closed grass state.sqlite→ accounts, characters, friends, vaults, inheritance, and other durable live-game state systemd → process supervision and relaunch Deployment hook → conditional Git update/build only for intentional deployment restarts Controller → manual client input today; sandboxed player scripts later FrameworkV3 → git submodule at client/frameworkv3; built first; game client code layers on top Sprites → any size; pivot at horizontal centre, 8px from bottom; Y-sort blocks/mobs Equipment → layered 16×16 overlays on mobs; metal armour shares art and recolours by material Camera → play view centered on the local player; bounded zoom; editor is chunk-framed Movement → global walk/run cadence (default 2 tiles/s walk, run double); server tile steps; client visual lerp World time → server clock minus 1200 years; night darkens unlit tiles Light → baked passable-tile raycast on editor save; shines across chunks World settings → admin modal for tick timers and global constants; live apply Inventory → 32 slots; stacks occupy one slot; letters are written paper items Bank → per-character vault; account inheritance tab on character delete Auth → auth.timfalken.com, stub admin-<n> until live; unlimited characters, one in world Chunks → editor open/closed; default grass and closed until painted Ground items → non-blocking, 10-minute player drops, pickup only while standing on the tile Communication service → proximity speech CourierService → pigeons carrying money or one item stack through durable transit BankService → shared unlimited vaults, cheque reservations and redemption MarketService → durable escrowed order book, matching, last-sale index and pigeon-to-bank settlement Shop NPCs → sell allowed stock; price lerps toward last player-market sale over shopPriceLerpDuration, times a hidden discount Combat → 8-tile melee, item/spell ranged range; hit skill roll; Strength / Dexterity / Mind damage; equal XP split Skills → classless progression; non-combat XP to one skill; attack XP split hit/damage

34. Version history

0.19

  • Playable item basis: 32-slot inventory, equipment overlays, carried coins,

ground drops (10-minute player drops, pickup on the tile), bank vaults, and account inheritance on character delete. Spawner and bank blocks can be painted in the editor; spawners produce placeholder deer up to maxAlive. Missing art is temporary 16×16 PNGs under client/assets/ so real sprites can drop in later by replacing those files.

0.18

  • Server ECS uses compact worker-local EntityHandles (recycled free list)

alongside global EntityIds for storage, networking and transfer. Path is a separate component from Movement; players carry NetworkIdentity instead of putting sessionId on character. Nearby clients get ENTITY_SPAWN / compact ENTITY_MOVE (tile + gait) / ENTITY_DESPAWN rather than appearance-heavy moves or extra snapshots.

0.17

  • Region workers own ECS worlds behind a clone-on-boundary protocol

(optional worker_threads). ChunkLoader reference counts keep 3×3 chunks simulating and 3×3 regions resident; other resident chunks stay dormant. Regions unload after the grace period and persist flagged entities. Crossing a foreign region transfers the only authoritative copy; ghosts cover border occupancy; client snapshots may span workers.

0.16

  • Proximity chat: Enter opens a bottom input (max chatMaxCharacters,

default 100). Enter sends a trimmed line; the speaker always sees their own text. Other players get a server-obscured bubble (full until 8 tiles, linear to silent at 16 tiles). At 0% readability no bubble is sent. Walk/run R is ignored while the chat line is open.

0.15

  • Hovering another player shows their first name. Clicking them opens an

inspect modal (first + last name) to send a friend request. Requests must be accepted; removing a friend removes them on both sides. The friends list is the later pigeon address book.

0.14

  • Ground and block types load visual states from per-type sprite folders

(first alphabetical PNG is the default). Sprite definitions include frames, framesPerRow and animationSpeed. The editor previews the selected tool on hover and cycles states with the mouse wheel. Gameplay may set a named visual state (for example a door).

0.13

  • World settings are live: an admin modal with categories, dirty-field

highlighting, and a settings edit log. Save applies immediately (including nightDarkness) rather than waiting on a map revision.

0.12

  • Chunks are open or closed in the world editor. Closed chunks stay visible

but cannot be entered. Never-edited chunks are default grass with no blocks and are closed.

  • Login uses auth.timfalken.com; until that is live, connections are stub

admin-<n> (connected-client count including this one) and are admins.

  • Accounts have unlimited characters, one in the world at a time. Creation

is first name, unique account-owned last name, and male/female.

  • Character deletion waits 24 hours with email and cancel. Permanent delete

frees names and moves goods to an account inheritance bank tab.

0.11

  • Made walk/run a global cadence from world settings (default 2 tiles/s

walk, run double): walk steps every other movement tick, run every tick. Mob definitions do not set move speed.

  • Added an admin world-settings modal for tick timers and global constants

(shop lerp duration, drop lifetime, simulation tick, and the same class of values). Settings ride the pending world revision.

  • World calendar time is server time minus 1200 years.
  • Baked static lighting by passable-tile raycast on chunk save, including

across chunk borders. Clients darken unreachable tiles at night. The editor has a night-to-day preview slider.

0.10

  • Drew visible equipment as 16×16 overlay layers on mobs (including players),

with worn items in equipment slots rather than the 32-slot inventory.

  • Replicated compact appearance layers to nearby clients instead of another

player's inventory.

  • Recolourable metal armour shares one overlay plus a 16×16 channel mask;

material definitions supply the metal colour while preserving shading.

0.9

  • Vendored FrameworkV3 as the git submodule client/frameworkv3. The game

client builds that library first and implements game-specific code on top of it. The Node.js server does not import the submodule.

0.8

  • Required all world sprites (tiles, blocks, mobs, items) to be 16×16 pixels,

rejected at load, with a CI unit test that reports and fails on any other size. Sprites are not individually scaled; the player may zoom the viewport within configured bounds.

  • Locked the play camera to the local player. The admin world editor remains

the only non-player-centered view.

  • Made authoritative movement integer tile-to-tile steps. Clients lerp

mobiles for presentation only.

  • Added a per-chunk world-editor changelog: admin, timestamp, and bullet

diffs for ground changes, block place/change/remove.

0.7

  • Added combat for all mobs including players: melee from any of the eight

neighbouring tiles, ranged and spells from the item or spell range.

  • Hit rolls use the weapon skill (Swordfighting, Axefighting, Archery, Magic,

and so on). Damage uses Strength, Dexterity or Mind according to melee, ranged or magic.

  • Successful player-attack XP is split equally between the hit skill and the

damage skill. Ordinary mobs use archetype skill levels and do not earn XP.

  • Shop NPCs sell items at seed value adapted to the last player-market unit

price, lerping over one hour, multiplied by a hidden per-shop discount.

  • Only the latest player-market sale per item is stored (price, timestamp, and

lerp origin). No historical series.

  • Item hover shows name, description, origin (crafter or shop NPC) and the

undiscounted current value, refreshed at most once per minute.

0.6

  • Added a 32-slot player inventory, stackable items, carried currency as a

numeric wallet, and unique-instance items for letters and filled cheques.

  • Redefined letters as paper items with player-written text rather than a

separate mail record.

  • Redefined carrier pigeons as free couriers that carry money or one item

stack to a player or to the nearest bank.

  • Added a shared unlimited bank near the marketplace, blank cheques filled to

99, vault reservations on fill, in-person redemption and pigeon-to-bank cheque transfers between vaults.

  • Added player-dropped ground items: 10-minute lifetime, non-blocking, pickup

only while standing on the tile, timestamp persistence across unload.

  • Specified later ground-item spawners and harvesting as content that reuses

this item model.

  • Routed offline/full-inventory pigeon delivery and older-side market

settlement into the recipient's shared bank vault.

0.5

  • Made carrier pigeons shared world-visible entities whenever their route crosses an already-simulating chunk.
  • Unrelated nearby players can see pigeons in their normal 3x3 chunk view; pigeons do not keep chunks loaded themselves.
  • Added deterministic materialisation/dematerialisation between durable abstract transit and worker-owned ECS pigeon entities.

0.4

  • Added FrameworkV3 as the shared player-client foundation while keeping backend ECS internal to the server.
  • Added server-side proximity chat degradation, persistent player groups and durable carrier-pigeon letters.
  • Added scalable courier transit that can cross dormant world space without forcing normal chunk simulation.
  • Added the central marketplace, escrowed hidden order book, midpoint pricing and pigeon-based remote settlement.
  • Added the player-driven item-source philosophy and restrictions on NPC shop inventories.
  • Added classless, skill-based player progression and authoritative skill XP.

0.3

  • Converted the living design document to Markdown as the canonical format.
  • Defined systemd as the production process supervisor.
  • Added a conditional, manifest-driven deployment path so crashes do not deploy pending code early.
  • Added a concrete example systemd service shape and clarified privilege separation.

0.2

  • Added unload-driven chunk persistence, authored world revisions, the admin world editor, spawner blocks, graceful scheduled restarts and future player scripting hooks.
Source
1---
2title: Tile MMO Server Technical Design
3version: 0.20
4status: proposed
5format: living-design-document
6---
7
8# Tile MMO Server Technical Design
9
10**Version:** 0.20
11**Status:** Proposed architecture; intended to be iterated as implementation decisions are made.
12**Scope:** Authoritative Node.js/ECS backend, FrameworkV3-based game client (16×16 sprites, player-centered viewport), chunk/region streaming, SQLite persistence, admin world editor with per-chunk changelogs, player inventory and items, combat, player communication, banking/cheques, shopkeepers, marketplace/economy systems, skill progression, automatic restart/update orchestration, and future player scripting hooks.
13
14# 1. Design goals
15
16- Support a large tile-based MMO world without simulating unused areas.
17
18- Keep the server fully authoritative: clients send actions and
19 intentions, never authoritative state changes.
20
21- Authenticate accounts via auth.timfalken.com (with an `admin-<n>` stub
22 until that service is live). An account may have unlimited characters,
23 one in the world at a time, with delayed deletion and an inheritance
24 bank tab.
25
26- Use ECS composition for entities and systems, while using chunks and
27 regions for spatial ownership and simulation lifecycle.
28
29- Allow simulation work to scale across Node.js workers and permit
30 entities to cross worker-managed region boundaries safely.
31
32- Keep client replication small: a player receives only the current
33 16×16 chunk and the eight neighbouring chunks.
34
35- Keep authored world data separate from ephemeral simulation state.
36
37- Persist only entities that explicitly need persistence; ordinary
38 spawned mobs disappear when their chunk is unloaded.
39
40- Avoid constant chunk writes. Normal chunk persistence occurs on
41 unload; graceful shutdown is implemented as a forced unload of all
42 resident chunks.
43
44- Provide an admin-only graphical world editor for painting tiles,
45 opening or closing chunks, and placing/configuring spawners, with a
46 per-chunk changelog of who changed what and when. Unedited chunks are
47 grass-only and closed.
48
49- Automatically schedule a graceful midnight restart when live code or
50 authored world data changes, with an admin-triggered immediate restart
51 path.
52
53- Reserve a clean control abstraction for a later sandboxed player
54 scripting language without requiring the scripting system in the
55 initial release.
56
57- Build the player-facing client on the shared FrameworkV3 library, vendored
58 as a git submodule and built first so game-specific client code can layer
59 on top of it, while keeping the server-side ECS an implementation detail of
60 the backend. World sprites may be any size; each uses a centred pivot
61 8 pixels from the sprite bottom. The play viewport stays
62 centered on the local player.
63
64- Authoritative movement is tile-to-tile at a **global** walk/run cadence
65 (default walk 2 tiles/s, run double), not a per-mob speed. Admins edit
66 that cadence and other tick timers in a world-settings modal. Saving
67 those settings applies immediately to the live world. World
68 calendar time is server time minus 1200 years. At night the client
69 darkens unlit tiles (how dark is a world setting); static light reach
70 is baked by raycast when a chunk is saved.
71
72- Give every player a 32-slot inventory in which stackable items occupy a
73 single slot, and treat dropped items as temporary, non-blocking ground
74 objects rather than tile occupancy.
75
76- Make ordinary communication spatial rather than global: nearby speech is
77 progressively degraded by distance, while long-distance exchange is a
78 physical item or currency delivery by carrier pigeon. A letter is simply a
79 paper item with player-written text.
80
81- Support persistent player groups without turning them into an instant
82 long-distance chat channel.
83
84- Provide a shared, unlimited player bank near the marketplace, with later
85 banks all reading the same vault, plus bearer cheques and free pigeon
86 deposits.
87
88- Make the central marketplace an order-matching service rather than a public
89 auction list, with durable escrow and asynchronous pigeon delivery.
90
91- Keep the economy predominantly player-driven: most ingredients are gathered,
92 final goods are normally crafted by players, and finished-item drops come from
93 enemies/bosses rather than ordinary NPC shops.
94
95- Let every combatant — players and other mobs — attack. Melee requires an
96 adjacent tile including diagonals; ranged attacks and spells use the range
97 of the weapon or spell. A hit roll uses the weapon skill; damage uses
98 Strength, Dexterity or Mind. Attack XP is split equally between those two
99 skills.
100
101- Let shop NPCs sell items at a seed value that lerps toward the last
102 player-market sale price over a configurable duration (default one hour),
103 with a hidden per-shop discount.
104 Item inspection shows name, description, origin and the undiscounted
105 current value, refreshed at most once per minute.
106
107- Use skill-based progression with no player classes. Every gameplay action is
108 governed by a skill and awards XP to that skill when successfully performed.
109 Combat is the explicit dual-skill exception: hit skill and damage skill
110 share the XP.
111
112# 2. Core world model
113
114## 2.1 Spatial hierarchy
115
116World
117└── Region: 4 × 4 chunks
118└── Chunk: 16 × 16 tiles
119└── Tile
120
121One chunk contains 256 tiles. One region is 64×64 tiles and contains 16
122chunks (4,096 tiles). World tile coordinates are canonical; chunk and
123region coordinates are derived from them.
124
125chunkX = floor(tileX / 16)
126chunkY = floor(tileY / 16)
127regionX = floor(chunkX / 4)
128regionY = floor(chunkY / 4)
129
130If negative world coordinates are allowed, use true floor division
131rather than JavaScript integer truncation.
132
133## 2.2 Three independent spatial states
134
135The design deliberately separates region residency, chunk simulation,
136and client visibility.
137
138| **Concern** | **Unit** | **Meaning** |
139|-------------|----------|------------------------------------------------------------------------------------------------|
140| Residency | Region | Whether the region and its required chunk data exist in server memory and have a worker owner. |
141| Simulation | Chunk | Whether ECS systems actively simulate entities and gameplay in this chunk. |
142| Visibility | Chunk | Whether a specific client is subscribed to the chunk and receives its snapshot/deltas. |
143
144## 2.3 Region states
145
146UNLOADED
147↓ load
148RESIDENT
149↓ no residency references + grace period
150UNLOADED
151
152A resident region is assigned to exactly one simulation worker. An
153unloaded region has no active ECS representation.
154
155## 2.4 Chunk states
156
157DORMANT ⇄ SIMULATING
158
159A dormant chunk can remain resident in memory while normal gameplay
160systems ignore it. A simulating chunk participates in movement, combat,
161AI, spawners and other active systems.
162
163# 3. Tile layers and occupancy
164
165## 3.1 Ground layer
166
167Every tile has a ground type. Ground is visual only. It does not by
168itself block movement, cause collision, or create gameplay behaviour.
169
170TileGround {
171groundTypeId: GroundTypeId
172}
173
174## 3.2 Block layer
175
176A tile may also contain one block. The block is the actual world object
177standing on the tile and can determine collision and behaviour.
178
179TileBlock {
180blockTypeId: BlockTypeId \| null
181config?: BlockConfig
182}
183
184Examples include walls, doors, trees, torches and other lights, containers,
185spawners, marketplace counters and banks. Block definitions determine
186properties such as passability, interaction behaviour, whether a block
187participates in navigation, and whether it emits light (`lightRangeTiles`).
188
189## 3.3 MOBile entities
190
191A moving game entity — player, enemy, animal, NPC or any other mobile
192actor — is represented by an ECS entity rather than being painted into
193the static tile map. A mobile entity may inhabit a tile in addition to
194the tile’s ground and block layers, subject to collision rules.
195
196Tile
197├── Ground (visual layer)
198├── Block (static/world-object layer; optional)
199├── Ground item stacks (ephemeral, non-blocking)
200└── Mobile ECS entities (dynamic occupancy)
201
202The spatial chunk index maintains which mobile entity IDs currently
203occupy each tile, allowing collision, nearby queries and replication
204without scanning the global ECS. Ground item stacks are indexed per
205tile as well, but they never contribute to movement collision and never
206prevent a mobile entity from standing on that tile.
207
208# 4. ECS model
209
210## 4.1 Entity composition
211
212Entities are numeric identities plus components. Behaviour comes from
213systems querying component combinations rather than deep class
214inheritance.
215
216Player
217Position
218Movement
219Health
220Combat
221Skills
222Inventory
223Currency
224Equipment
225Player
226NetworkIdentity
227ChunkLoader
228Persistent
229
230Ordinary enemy
231Position
232Movement
233Health
234Combat
235Skills
236Creature
237AI
238
239Named NPC
240Position
241Movement
242Health
243NPC
244AI
245Persistent
246
247## 4.2 Global identity versus local ECS handle
248
249Use a globally meaningful EntityId for storage, networking and
250cross-worker transfer, and a compact worker-local EntityHandle for hot
251ECS arrays. A transferred entity keeps its EntityId but may receive a
252different local handle on the destination worker.
253
254## 4.3 Recommended initial components
255
256| **Category** | **Components** |
257|----------------|----------------------------------------------|
258| Spatial | Position, Movement, Path, Collision |
259| Living | Health, Combat, Creature, Mob, Skills |
260| Player | Player, NetworkIdentity, Inventory, Currency, Equipment |
261| AI | AI, Target, BehaviourState |
262| Lifecycle | ChunkLoader, Persistent, SpawnOrigin |
263| Presentation | Renderable / Appearance |
264| Future control | Controller / ScriptController / OfflineUntil |
265
266# 5. ChunkLoader and simulation activation
267
268## 5.1 Generic ChunkLoader component
269
270World activation is component-driven rather than player-specific. Any
271entity may carry a ChunkLoader component that says “keep the surrounding
272world resident and simulated”.
273
274ChunkLoader {
275simulationRadiusChunks: 1,
276regionLoadRadius: 1
277}
278
279A normal player can therefore stimulate a 3×3 chunk area while keeping
280the surrounding 3×3 regions resident. Bosses, travelling NPCs, machines,
281scripted actors or administrative anchors can use the same mechanism.
282
283## 5.2 Reference counting
284
285Chunk simulation and region residency should use reference counts.
286Overlapping loaders increment the same references; leaving decrements
287them. A chunk sleeps only when its simulation reference count reaches
288zero. A region becomes eligible for unload only when its residency
289references reach zero.
290
291## 5.3 Grace period
292
293After the last residency reference disappears, retain the region briefly
294before unloading. This prevents repeated SQLite reads and writes when a
295loader oscillates around a boundary. The delay should be configurable.
296
297# 6. Chunk lifecycle and persistence
298
299## 6.1 No periodic chunk saves
300
301Normal gameplay does not periodically rewrite loaded chunks. A chunk is
302saved as part of the unload path only.
303
304Resident chunk
305↓ last residency / forced shutdown unload
306Prepare unload
307↓
308Persist required chunk state once
309↓
310Persist required entities
311↓
312Remove ECS/runtime representation
313
314A graceful server restart does not introduce a second save mechanism. It
315force-unloads every resident region/chunk, so the normal unload
316persistence path remains the single source of truth.
317
318## 6.2 Persistent versus non-persistent entities
319
320Persistence is an entity property, not a property of the chunk or
321spawner. An entity with Persistent is serialised when its owning
322chunk/region unloads. A non-persistent entity is simply discarded.
323
324Non-persistent wolf
325spawn → simulate → chunk unload → disappear
326
327Persistent named NPC
328load → simulate → chunk unload → save → recreate when area loads
329
330## 6.3 Persistent is independent of ChunkLoader
331
332These traits must remain independent. A persistent entity does not
333automatically keep its area active, and a ChunkLoader does not
334automatically become persistent.
335
336# 7. Storage architecture
337
338## 7.1 Separate authored world and runtime state
339
340Use two SQLite databases with different responsibilities.
341
342| **Database** | **Responsibility** |
343|--------------|-----------------------------------------------------------------------------------------------------------------------------------------|
344| world.sqlite | Admin-authored ground tiles, block tiles, light maps, live world settings and their edit log, spawner configuration, per-chunk editor changelogs, world revisions and world metadata. |
345| state.sqlite | Accounts, characters, inventories, carried currency, character vaults, inheritance tabs, cheque reservations, skills, groups, courier cargo/transit, unexpired ground items, market orders/escrow/trades, per-item last player-market sale, persistent ECS entities, offline-script state, optional persistent runtime chunk overrides, and other durable live-game state. |
346
347This prevents editor authoring changes from becoming entangled with live
348player/entity persistence.
349
350## 7.2 Chunk writes in runtime state
351
352If initial gameplay does not allow permanent tile/block modification,
353runtime chunks require no writes at all. If permanent runtime world
354changes are later added, dirty chunk overrides are held in memory and
355written to state.sqlite only when that chunk unloads. Shutdown uses
356forced unload and therefore follows the same rule.
357
358## 7.3 Central persistence service
359
360Simulation workers should not independently compete for SQLite writes. A
361persistence service owns the write connection, batches transactions, and
362receives logical save requests from workers.
363
364Simulation workers
365│ save/unload messages
366▼
367Persistence service
368│
369▼
370SQLite (WAL)
371
372Live ECS state remains authoritative while loaded; SQLite is durable
373state, not a per-tick synchronisation mechanism.
374
375# 8. World authoring and revision model
376
377## 8.1 Admin-only world editor
378
379The server includes a separate admin-only world editor UI. It is not
380part of the normal player client.
381
382- Display a 3×3 of 16×16 chunks, with the currently selected
383 chunk in the centre and a red border around that chunk.
384 Painting, open/closed, and changelog apply only to the
385 selected chunk; neighbours are visible for alignment and
386 baked lighting context.
387
388- Provide Up, Down, Left and Right navigation buttons that move the
389 editor exactly one chunk in that direction.
390
391- Show the current chunk coordinates prominently, and whether the chunk
392 is **open** or **closed**.
393
394- Toggle the current chunk open or closed. Closed chunks remain visible
395 to nearby players but cannot be entered.
396
397- Allow painting a ground type on a tile.
398
399- Allow painting, replacing or erasing the block type on a tile.
400
401- Hovering a tile in the selected chunk previews the selected tool there:
402 existing content on that layer is hidden and the tool's sprite is shown
403 where a click would place it.
404
405- Mouse wheel cycles the **visual state** of the selected ground or block
406 type (see section 21.3). If the hovered tile already has that type, the
407 wheel also writes the new state onto it.
408
409- Render both layers together so the block appears on top of the ground.
410
411- Do not display ordinary mobile entities as editable map paint.
412
413- Allow selecting/configuring special block types such as Spawner, Bank,
414 Marketplace and light-emitting blocks (`lightRangeTiles`).
415
416- Open a **world settings** modal for global tick timers and constants
417 (movement cadence, night darkness, shop lerp duration, drop lifetime,
418 and other values listed in section 8.5). The form is categorised and
419 scrollable; a settings edit log sits beside it. Edited rows are marked
420 until Save, and only those rows are written.
421
422- Provide a **night-to-day slider** that only previews lighting; it does
423 not change live world time. Preview uses the same baked light maps as
424 play, including light that reaches this chunk from neighbouring chunks.
425
426- Later: allow configuring ground-item spawners analogously to mob
427 spawners. Exact item tables remain a later content decision.
428
429- Save changes through an authenticated admin API; the browser never
430 opens SQLite directly.
431
432- Show that chunk's changelog: a chronological list of saves, each with
433 which admin made the edit, when, and a bullet-point diff of the change.
434
435The editor camera is **not** locked to a player character. It frames the
436currently selected chunk. This is the only intended exception to the
437player-centered play viewport in section 21.4.
438
439## 8.2 World editor save behaviour
440
441Saving a **chunk** writes the authored result to world.sqlite. It does
442not live-patch the currently running simulation map. Instead, the change
443creates or updates a pending world revision and schedules a server
444restart for the next server-local midnight (or Apply now).
445
446Saving **world settings** is different: it updates the live settings
447row immediately, records a settings changelog entry, and the running
448process applies the new values without waiting for a world revision.
449
450The running game remains pinned to the **chunk** world revision selected
451at its own startup. This avoids a dangerous mixed state where some
452loaded chunks use old authored data and newly loaded chunks use newer
453editor data. Settings are not revision-pinned.
454
455## 8.3 Versioned authored chunks
456
457A practical schema is to give every editor change a monotonically
458increasing world revision. The game process pins one active revision for
459its entire lifetime. Chunk lookup selects the latest authored version
460not newer than that pinned revision.
461
462world_revisions
463revision_id
464created_at
465created_by
466status // pending / active / superseded
467
468world_chunk_versions
469chunk_x
470chunk_y
471revision_id
472open // player-enterable; default false until set
473data_blob
474
475world_meta
476active_revision
477pending_revision
478
479world_settings
480revision_id
481settings_blob // historical snapshot copied onto a map revision
482
483world_live_settings
484id // singleton row, always 1
485settings_blob // the live, immediately applied settings
486updated_at
487updated_by
488
489world_settings_edit_log
490log_id
491editor_admin_id
492edited_at
493diff_entries // which options changed, from/to
494
495world_chunk_edit_log
496log_id
497chunk_x
498chunk_y
499revision_id
500editor_admin_id
501edited_at
502diff_entries // structured bullets for this save
503
504On the next planned restart, startup promotes/selects the latest valid
505pending revision before world loading begins.
506
507## 8.4 Per-chunk changelog
508
509Every successful chunk save appends one changelog record for that chunk.
510The record is durable in `world.sqlite` and is not gameplay state.
511
512The server diffs the newly saved chunk against the previous authored
513version of that same chunk (the latest `world_chunk_versions` row for
514those coordinates that this save replaces). Unchanged tiles produce no
515bullets. Each changed tile becomes one of:
516
517```text
518- Ground at X, Y changed from Prev to New.
519- Block <type> placed at X, Y.
520- Block at X, Y changed from Prev to New.
521- Chunk opened.
522- Chunk closed.
523```
524
525`X, Y` are world tile coordinates. `Prev` / `New` / `<type>` are the
526ground or block definition display names. A block paint on an empty block
527layer is a placement. Replacing one block type (or its config, such as a
528spawner) with another is a change. Erasing a block is a removal. Ground is
529never absent; a ground paint is always a change from one type to another.
530
531The editor UI lists records newest-last or newest-first consistently, each
532headed by admin identity and timestamp, with that save's bullets underneath.
533The changelog is an audit trail, not an undo stack. Undo/redo remains an
534open editor-UX decision. Derived light maps are not changelog bullets;
535they are regenerated on save (section 8.6).
536
537## 8.5 World settings
538
539Global gameplay constants live in authored `world_live_settings`. They
540are **not** per-mob, **not** client-authored, and **not** pinned to a
541map revision. Admins edit them from a large tabbed modal in the
542world-editor UI. The modal fills most of the screen: the left pane has
543category tabs (Simulation, Graphics, World, Characters, Communication,
544Inventory, Economy) with one panel visible at a time; the right pane is
545a settings edit log (which option changed, from/to, which admin,
546date/time).
547
548Rows the admin has edited in this session are marked with a distinct
549background. Save writes **only** those dirty fields. The running
550process applies them immediately (walk cadence, tick rate, night
551darkness, bloom post-chain knobs, and other consumed timers). Chunk
552**Apply now** is not required.
553
554`nightDarkness` only darkens during dusk/night/dawn (peak hours 22–5).
555Daytime hours 8–16 stay fully bright on the client. Editing night
556darkness in the editor snaps the Night preview slider to night so the
557change is visible immediately.
558
559Minimum initial settings and defaults:
560
561```text
562WorldSettings
563- walkTilesPerSecond // default 2
564- simulationTickHz // default 20; implementation default, still a setting
565- shopPriceLerpDuration // default 1 hour
566- groundItemDespawnDuration // default 10 minutes
567- regionUnloadGracePeriod // configurable grace after last residency
568- defaultGroundTypeId // grass used for never-edited chunks
569- characterDeletionDelay // default 24 hours
570- nightDarkness // default 0.72; 0 = no extra night darkening, 1 = fully black unlit tiles
571- chatMaxCharacters // default 100; trimmed proximity-chat line length
572- bloomThreshold // default 0.35; Framework bloom bright-pass
573- bloomSoftKnee // default 0.3
574- bloomIntensity // default 1.35
575- bloomBlurSize // default 3
576- bloomSaturation // default 1.15
577- bloomColorPreserve // default 0.35
578- bloomDilate // default 2; 0 disables dilate
579- bloomScales // default 2; H/V blur scale pairs
580- bloomHalfRes // default 1; 1 = half-res blur, 0 = full-res
581```
582
583Running is always **double** walking speed. It is not a separate per-entity
584field. From `walkTilesPerSecond`:
585
586```text
587runTilesPerSecond = walkTilesPerSecond * 2 // default 4
588movementTickHz = runTilesPerSecond // default 4 Hz
589walk: commit a tile every 2 movement ticks
590run: commit a tile every 1 movement tick
591```
592
593All ground mobiles — players, enemies, NPCs — use this same cadence. A
594mob definition does not set move speed. Gait (`walk` | `run`) is the only
595per-entity choice; it selects every-other vs every movement tick.
596
597Other tick-duration constants that already exist in this document (shop
598lerp, ground-item despawn, residency grace, and later ones of the same
599kind) are edited here rather than hardcoded. Adding a new global timer
600means adding a field to `WorldSettings` and a row in this modal.
601
602## 8.6 Baked lighting
603
604Light from authored blocks is precomputed when a chunk is saved, not
605raytraced every simulation tick.
606
607A block definition may set `lightRangeTiles > 0`. That tile is a static
608light source. Light travels only through **passable** tiles (the same
609passability as walking). Ground type does not block light. Mobiles and
610ground items do not block light.
611
612For every tile within a source's range, the baker runs a simple grid
613raycast (for example Bresenham through tile centres). If the ray hits an
614impassable block before the destination, that source does not light that
615tile. A tile is lit if **any** source can reach it. Light **does** shine
616across chunk boundaries.
617
618Saving a chunk rebakes:
619
6201. that chunk's 16×16 light map, and
6212. every neighbouring chunk that could be affected (chunks within the
622 maximum `lightRangeTiles` of the saved chunk).
623
624Neighbor rebakes use light sources and walls from the pending revision,
625including the chunk just saved. Those neighbor light maps are written
626into the same pending revision so play never mixes old and new lighting.
627
628The light map is stored in the chunk `data_blob` as a 16×16 intensity
629(0 = unreachable, 1–255 = falloff by distance from the strongest
630reaching source). The client darkens tiles by that intensity at night,
631so a torch fades tile-by-tile rather than lighting a hard disc. Peak
632unlit darkness is `nightDarkness` (a live world setting). It is
633replicated to clients in `CHUNK_SNAPSHOT` / `CHUNK_DELTA`.
634
635Runtime door open/close does not rebake static light unless a later
636iteration adds live lighting. Baked light is authored geometry.
637
638The editor night-to-day slider interpolates preview ambient from full
639night (dark except baked-lit tiles) to full day (no ambient darkening).
640It does not persist and does not change server/world clock.
641
642## 8.7 Default chunks and open / closed
643
644A chunk the editor has never saved does not exist in `world_chunk_versions`.
645At runtime it is synthesised as:
646
647- every tile `defaultGroundTypeId` (grass),
648- no blocks,
649- **closed**,
650- no baked lights.
651
652The world is therefore an infinite grass field until admins paint it, and
653players cannot walk onto it until an admin **opens** the chunk.
654
655**Closed** chunks can still appear in a player's 3×3 view. They cannot be
656entered: `MOVE_TO`, pathfinding, spawning, and other player-entry actions
657treat every tile in a closed chunk as impassable. Visibility and lighting
658previews are unchanged. Where an **open** chunk shares an edge with a
659closed (or never-edited) chunk, the client draws a red border on that
660edge so players can see they cannot cross.
661
662**Open** chunks are the playable map. Opening or closing is an authored
663chunk flag, saved with the pending revision like paint.
664
665Spawners in a closed chunk do not spawn. Ground movement, including AI,
666does not step into a closed chunk. If a future bug or admin tool places an
667entity there, it can still be replicated to observers, but players cannot
668walk in after it.
669
670# 9. Spawner blocks
671
672## 9.1 Spawner data
673
674A Spawner is a block in the authored block layer, with per-instance
675configuration stored as part of the chunk data.
676
677SpawnerConfig {
678spawnerId: SpawnerId,
679mobTypeId: MobTypeId,
680maxAlive: number,
681spawnRangeTiles: number
682}
683
684Additional parameters such as minimum/maximum spawn delay can be added
685later without changing the core model.
686
687## 9.2 Spawner editor
688
689Selecting a Spawner tile in the world editor opens a configuration panel
690containing at minimum: mob type, maximum alive count and spawn range.
691Validation happens server-side before the pending world revision is
692written.
693
694## 9.3 Spawned entity persistence
695
696The spawner never decides whether its mob is persistent. The mob
697definition/archetype does. When the spawner creates an entity, the
698entity receives Persistent only if that mob type is defined as
699persistent.
700
701MobDefinition: deer
702persistent = false
703
704MobDefinition: named_guard_captain
705persistent = true
706
707## 9.4 SpawnOrigin
708
709Spawned mobs receive a SpawnOrigin component referencing the spawner.
710This lets maxAlive count only entities belonging to that spawner and
711avoids expensive geometric searches.
712
713SpawnOrigin {
714spawnerId: SpawnerId
715}
716
717For non-persistent mobs, disappearance on chunk unload naturally
718decreases the count. For persistent mobs, SpawnOrigin is persisted so
719the spawner can recognise an existing persistent instance even after it
720has moved or been unloaded elsewhere. A lightweight persistence index by
721spawnerId prevents duplicate persistent spawns.
722
723## 9.5 Spawner simulation
724
725SpawnerSystem runs only while the spawner’s chunk is simulating **and
726open**, and at a much lower frequency than movement. A spawn candidate
727must satisfy block collision, bounds, an open chunk, and mobile-occupancy
728rules. Ground type does not affect passability unless a later gameplay
729system explicitly introduces a separate rule for it.
730
731## 9.6 Future ground-item spawners
732
733Some items will later spawn naturally on the ground, using a world-editor
734block analogous to a mob spawner. Those spawned stacks should use the same
735non-blocking ground-item representation as player drops, but their lifetime,
736respawn and `maxOnGround` rules belong to the spawner configuration rather
737than the 10-minute player-drop timer.
738
739Exact item lists, harvest interactions and spawner parameters are later
740content decisions and do not block the inventory/bank model.
741
742# 10. Startup and loading order
743
744Loading order is explicit so authored world state exists before
745persistent entities are instantiated into it.
746
747> **1.** Start process and load configuration, including server time
748> zone and storage paths.
749>
750> **2.** Open world.sqlite and validate/migrate its schema.
751>
752> **3.** Select/promote the world revision to use for this process and
753> pin it for the lifetime of the process.
754>
755> **4.** Load static registries: ground definitions, block definitions,
756> item definitions, material definitions, spell definitions, mob archetypes and component serializers.
757>
758> **5.** Open state.sqlite and run runtime-state migrations.
759>
760> **6.** Start the persistence service, durable domain services (such as courier, bank, market and shop-price services when enabled), region coordinator and simulation workers.
761>
762> **7.** Load the index of persistent entities that themselves require
763> world activation (for example persistent ChunkLoaders or future
764> offline scripted players).
765>
766> **8.** For each required region, load authored chunk data from the
767> pinned world revision first.
768>
769> **9.** Apply any durable runtime chunk override state, if the game
770> supports such modifications.
771>
772> **10.** Instantiate persistent entities into the already-created
773> world/chunks.
774>
775> **11.** Recalculate ChunkLoader references and begin chunk simulation.
776>
777> **12.** Only after the world reports READY does the gateway accept
778> normal player logins.
779
780This ordering solves the bootstrap problem for persistent entities that
781keep their own chunks active: a compact persistence index can locate
782them without first loading the entire world.
783
784# 11. Simulation workers and region ownership
785
786## 11.1 Ownership invariant
787
788Exactly one worker authoritatively owns a region at any instant. Every
789authoritative entity belongs to the worker that owns the entity’s
790current region.
791
792## 11.2 Coordinator
793
794A central region coordinator maintains RegionId → WorkerId and
795assigns/migrates regions based on actual measured simulation effort,
796while preferring neighbouring regions on the same worker when load
797permits.
798
799## 11.3 Work measurement
800
801- Average and high-percentile tick execution time.
802
803- Number of simulating chunks.
804
805- Number of active entities and AI entities.
806
807- Pathfinding work and queued searches.
808
809- Cross-worker boundary message volume.
810
811- Backlog / tick lateness.
812
813Actual time spent simulating is more important than raw player count or
814raw region count.
815
816## 11.4 Node.js implementation
817
818Simulation workers keep mutable ECS worlds isolated and talk only through
819structured-cloneable messages. The default runtime is in-process workers
820with clone-on-boundary (so the protocol is real even without OS threads).
821`SIMULATION_WORKER_MODE=thread` runs the same `WorkerWorld` inside
822`worker_threads`. Do not share a mutable ECS in SharedArrayBuffer.
823
824A coordinator on the gateway thread owns region assignment (neighbour-sticky,
825least-loaded tie-break), global EntityIds, transfer handoff, ghost exchange,
826and SQLite. `SIMULATION_WORKERS` defaults to 2. Dynamic load rebalance is
827later.
828
829# 12. Cross-worker communication
830
831## 12.1 No remote mutation
832
833A worker may inspect a limited read-only representation of neighbouring
834entities but never directly mutates authoritative state owned by another
835worker.
836
837## 12.2 Border ghosts
838
839Neighbouring workers can exchange compact border/ghost entity data for
840nearby interaction and AI: EntityId, position, collision footprint, type
841and minimal combat metadata. Ghosts are not full ECS entities and are
842never authoritative.
843
844## 12.3 Remote actions
845
846Worker A goblin targets Player 42 (owned by Worker B)
847Worker A → REMOTE_ACTION(attack intent) → Worker B
848Worker B validates range/state and applies authoritative result
849
850## 12.4 Entity transfer
851
852When an entity crosses from a region owned by Worker A into one owned by
853Worker B, ownership is handed off at a simulation tick boundary using a
854sequence-numbered transfer protocol. There is never more than one
855authoritative copy.
856
857A: prepare transfer
858B: validate / accept
859A: freeze at handoff boundary
860B: instantiate authoritative entity at effective tick
861Coordinator: update ownership mapping
862A: remove authoritative copy
863
864# 13. Server tick and stimulation
865
866## 13.1 Fixed simulation tick
867
868Use a fixed server simulation tick. The default is 20 Hz (50 ms), stored
869as `WorldSettings.simulationTickHz`. This is not a protocol promise.
870
871Movement does **not** commit a new tile on every simulation tick. See
872section 13.4.
873
8741\. Drain validated incoming commands
8752. Apply completed worker/entity transfers
8763. Recalculate activation changes
8774. Movement / collision
8785. Combat
8796. Scheduled AI
8807. Scheduled spawners/environment, including ground-item expiry in simulating chunks
8818. Produce cross-worker messages
8829. Produce client replication deltas
88310. Queue unload/persistence work
884
885## 13.2 Different system frequencies
886
887Not every ECS system should run every tick. Ground movement commits only
888on the global movement cadence (section 13.4). AI decisions, target
889searches and spawner checks can run at lower frequencies. Sleeping chunks
890are not “slow ticked”; they are omitted from normal simulation.
891
892## 13.3 Timestamp-based inactive progression
893
894Long-lived timers such as growth, cooldowns, ground-item expiry and shop
895price lerps should store future timestamps where possible. When an area
896wakes, the system catches up from the timestamp instead of executing missed
897ticks. An expired ground item is discarded on catch-up without ever
898reappearing. Shop and tooltip prices are evaluated from last-sale timestamps
899when observed; they are not ticked. Durations such as shop lerp and
900ground-item despawn come from `WorldSettings`, not from hardcoded
901literals in systems.
902
903## 13.4 Global movement cadence
904
905All ground-moving entities share one walk speed and one run speed.
906
907- Default walk: **2 tiles per second** (`walkTilesPerSecond`).
908- Run: always **double** walk (default 4 tiles per second).
909- Movement ticks fire at `runTilesPerSecond` (default 4 Hz).
910- **Walk:** the entity may advance one path tile on every other movement
911 tick.
912- **Run:** the entity may advance one path tile on every movement tick.
913
914Mobs do not define their own move speed. `Movement.gait` is `walk` or
915`run`. Players send `SetGait`. AI may set gait; it still uses the global
916cadence. Flying pigeon transit is not this cadence; it keeps its own
917route clock.
918
919If the path is blocked on a movement tick, the entity stays on its tile
920and retries on a later legal tick. Occupancy, combat range and pickup
921always use the last committed tile.
922
923## 13.5 World calendar time
924
925World time is server time **1:1**, in the same configured IANA zone used
926for midnight restarts, with **1200 years subtracted** from the calendar
927date. A server clock of 24 Aug 2026 21:00 is world 24 Aug 826 21:00.
928Clock-of-day, including night, therefore matches the host's zone.
929
930The gateway includes current world time (or server unix time plus the
931year offset) in the status sent to clients so shading does not depend on
932the player's device clock. Lighting is presentation; combat and movement
933do not wait on the day/night overlay.
934
935# 14. Client gateway and authority
936
937## 14.1 Stable connection ownership
938
939Client WebSocket/TCP connections belong to a gateway rather than
940simulation workers. When the player crosses into a region owned by
941another worker, the socket stays connected to the same gateway; only
942internal routing changes.
943
944## 14.2 Client commands are intentions
945
946A client sends commands such as MoveTo, Interact, Attack, UseItem,
947EquipItem, UnequipItem, SelectSpell, SetGait, DropItem, PickupItem, BankDeposit,
948BankWithdraw, BuyFromShop or SendPigeon. The authenticated **account**
949determines the actor; after character select, commands apply to that
950account's **active character**. The
951client never supplies an authoritative resulting position, health
952value or inventory result.
953
954## 14.3 Input queue
955
956Socket handlers validate message shape and enqueue commands. Simulation
957workers consume commands at tick boundaries. WebSocket callbacks do not
958mutate ECS state directly.
959
960## 14.4 Authentication
961
962Live login uses **auth.timfalken.com**. The game server never stores a
963password. It receives an authenticated account identity (and email) from
964that service and maps it to a durable `accountId` in `state.sqlite`.
965
966Until auth.timfalken.com is available, the gateway uses a **stub identity**:
967each new connection is `admin-<n>`, where `n` is the number of currently
968connected clients **including this one** (the first connection is
969`admin-1`). Stub accounts are treated as admins so the world editor can be
970used during development. Stub accounts have no email; deletion “emails”
971are logged instead of sent.
972
973When real auth ships, the stub is removed. Admin rights come from that
974service, not from the `admin-` name prefix.
975
976An account may have only **one active play session** at a time (one
977character in the world).
978
979## 14.5 Characters
980
981An account has unlimited characters and plays **one** at a time. First
982login with no characters must create one before entering the world. Later
983logins show a character-selection menu: create, choose, mark for deletion,
984or cancel deletion.
985
986Initial character setup (may change later):
987
988```text
989CreateCharacter
990- firstName // not globally unique
991- lastName // unique surname, owned by this account
992- sex // male | female
993```
994
995Rules:
996
997- **Last names** are globally unique. The first character to take a surname
998 claims it for that **account**. The same player may reuse that last name
999 on their other characters. Another account cannot use it.
1000- **First names** need not be unique globally.
1001- For a given account, `firstName` + `lastName` must be unique among
1002 characters that still exist (including those pending deletion).
1003- Uniqueness is case-insensitive; display uses the casing the player typed.
1004
1005```text
1006Account
1007- accountId
1008- authSubject // from auth.timfalken.com, or stub admin-<n>
1009- email? // from auth; absent on stub
1010- surnameClaims[]
1011
1012Character
1013- characterId
1014- accountId
1015- firstName
1016- lastName
1017- sex
1018- deletionScheduledAt? // null if not deleting
1019- inventory, equipment, currency, vault, skills, ...
1020```
1021
1022The in-world ECS player entity is a **character**, not the account.
1023
1024## 14.6 Character deletion and inheritance
1025
1026From character select, the player may mark a character for deletion.
1027
1028- The character cannot be played while deletion is pending.
1029- Permanent delete happens after `characterDeletionDelay` (default **24
1030 hours**). Until then the player may cancel.
1031- The server **always** notifies the account email when deletion is
1032 marked (and should notify again on cancel and on actual delete). Stub
1033 auth logs the message instead.
1034- On permanent delete, the name pair is freed. If this account has no
1035 remaining characters with that last name, the surname claim is released.
1036- Before the vault is moved, `BankService` voids outstanding filled
1037 cheques **issued by** this character (reservations return to the vault).
1038- All items in inventory, equipment, carried currency, and the character
1039 vault are moved to that **account's inheritance bank tab**.
1040
1041Any living character of the same account may, at a bank, **claim**
1042inheritance stacks (and currency) into that character's own vault. Claiming
1043is a move from the account tab to the character vault, not a second copy.
1044
1045# 15. Client chunk subscription and replication
1046
1047## 15.1 3×3 visibility
1048
1049A player receives the current chunk and the eight surrounding chunks, a
1050maximum viewport of 48×48 tiles. Neighbouring **closed** chunks are still
1051sent so scenery remains visible; the player simply cannot walk onto them.
1052
1053┌───┬───┬───┐
1054│ V │ V │ V │
1055├───┼───┼───┤
1056│ V │ P │ V │
1057├───┼───┼───┤
1058│ V │ V │ V │
1059└───┴───┴───┘
1060
1061## 15.2 Incremental subscription changes
1062
1063Crossing one chunk east subscribes only the three newly visible eastern
1064chunks and unsubscribes only the three old western chunks. The rest of
1065the 3×3 view remains subscribed.
1066
1067## 15.3 Snapshots and deltas
1068
1069Initial subscription sends a CHUNK_SNAPSHOT containing authored/runtime
1070tile state, currently visible entities and unexpired ground item stacks.
1071Afterwards, revisioned CHUNK_DELTA messages report tile changes, entity
1072spawn/move/change/despawn events and ground-item appear/change/despawn
1073events. Full chunks are not retransmitted every tick.
1074
1075Entity `move` events carry the new integer tile and the current gait so
1076the client can lerp over the walk or run interval. They do not carry a
1077fractional in-between position. Smooth walking is a client visual lerp
1078(section 21.5), not part of the replication payload.
1079
1080Chunk snapshots include the baked light map (section 8.6).
1081
1082Visible equipment is replicated as a compact appearance payload (body
1083sprite plus worn overlay layers and recolour parameters), not as the
1084entity's full inventory. Nearby clients can draw another player's armour
1085without receiving their bags.
1086
1087## 15.4 Visibility can span workers
1088
1089The gateway can source visible chunks from multiple workers. A player
1090may be authoritative on Worker A while one or more of the eight
1091neighbouring visible chunks are owned by Worker B. Client visibility
1092must never force simulation-region reassignment.
1093
1094# 16. Click-to-move and A\* pathfinding
1095
1096## 16.1 Command flow
1097
1098Client: MOVE_TO(tileX, tileY)
1099↓
1100Gateway validates/authenticates
1101↓
1102Owning worker validates target
1103↓
1104A\* calculates authoritative route
1105↓
1106Path component attached/updated
1107↓
1108MovementSystem advances the entity **one tile at a time** on the global
1109walk/run cadence (section 13.4)
1110
1111Authoritative `Position` is always an integer `tileX`, `tileY`. The server
1112does not store a sub-tile location for walking mobiles. When a movement
1113tick allows this gait to step, `MovementSystem` commits the next path
1114tile in a single jump. Combat, occupancy, pickup and interaction all use
1115that committed tile.
1116
1117Flying pigeons still ignore the ground navigation grid, but their
1118replicated ECS position is likewise a tile. The transit clock determines
1119which tile they occupy at a given time; the client may lerp the sprite
1120between those tiles like any other mobile.
1121
1122## 16.2 Initial A\* implementation
1123
1124For normal player clicks within the visible 3×3 chunks, the search space
1125is at most 48×48 = 2,304 tiles, so conventional A\* is a strong starting
1126point.
1127
1128- Binary heap priority queue for the open set.
1129
1130- Manhattan heuristic for four-direction movement; octile heuristic if
1131 diagonal movement is later allowed.
1132
1133- Reusable typed-array or pooled search buffers for hot paths to reduce
1134 allocation and garbage collection.
1135
1136- Rate-limit path requests per player and avoid recalculation every
1137 tick.
1138
1139- Use block passability, **open-chunk** bounds, and dynamic occupancy;
1140 ground is visual only. Tiles in closed or never-edited chunks are not
1141 legal path targets for players.
1142
1143## 16.3 Navigation revisions
1144
1145Each chunk maintains a navigation revision that increments when a
1146movement-affecting block changes. A path records the relevant revisions.
1147Static geometry changes can invalidate paths; temporary mobile occupancy
1148normally causes a short wait or small local re-path rather than
1149rebuilding every path.
1150
1151## 16.4 Long-distance extension
1152
1153If long-distance autonomous travel is added later, introduce
1154hierarchical pathfinding: region graph → chunk portals/edges → local
1155tile A\*. The client movement command interface does not need to change.
1156Server movement remains discrete tile steps; only the path length changes.
1157
1158# 17. Automatic update and restart scheduler
1159
1160## 17.1 Restart triggers
1161
1162A graceful restart is scheduled for the next midnight in configured
1163server-local time when either of these conditions occurs:
1164
1165- A new commit is detected on origin/master. The master branch is the
1166 live branch.
1167
1168- An administrator saves a world-editor change, creating/updating a
1169 pending authored world revision.
1170
1171Multiple triggers coalesce into one scheduled restart. The scheduler
1172stores all reasons so players and admins can see why a restart is
1173pending.
1174
1175## 17.2 Detecting live-code changes
1176
1177The running server periodically performs a non-destructive remote check,
1178for example git fetch origin master followed by comparison of the
1179running commit with origin/master. It does not update the checked-out
1180code while the game is live.
1181
1182## 17.3 Server-local midnight
1183
1184Midnight is calculated in a configured IANA time zone rather than by
1185adding 24 hours to the current time. This keeps behaviour correct across
1186daylight-saving transitions.
1187
1188## 17.4 Player-visible restart state
1189
1190Restart status is part of the server status sent to clients. Connected
1191players see that a restart is scheduled and the scheduled local time.
1192The server can also issue configurable countdown notices as the restart
1193approaches and includes the state immediately when a player logs in.
1194
1195RestartStatus {
1196scheduled: true,
1197scheduledAt: timestamp,
1198reasons: \["code-update", "world-update"\]
1199}
1200
1201## 17.5 Manual admin restart
1202
1203An authorised admin action can invoke the same graceful restart pipeline
1204immediately. This is not a separate “hard restart” path; it differs only
1205in scheduled time.
1206
1207## 17.6 Graceful restart sequence
1208
1209> **1.** Enter `DRAINING` / `RESTARTING` state and reject new logins.
1210>
1211> **2.** Broadcast the final restart notice.
1212>
1213> **3.** Disconnect player sessions cleanly and persist session state.
1214> Shutdown handling overrides normal offline-script retention so chunk
1215> unload cannot be blocked by a retiring process.
1216>
1217> **4.** Stop accepting new gameplay commands and finish the current
1218> safe tick boundary.
1219>
1220> **5.** Force-unload every resident region/chunk, ignoring normal
1221> `ChunkLoader` references. This invokes the ordinary chunk/entity unload
1222> persistence path exactly once.
1223>
1224> **6.** Flush the persistence service and close SQLite connections
1225> cleanly.
1226>
1227> **7.** Atomically write a restart request manifest. It records the
1228> restart reasons, whether a code deployment is requested, the target Git
1229> commit if known, and the pending world revision if one exists.
1230>
1231> **8.** Exit the Node.js game process cleanly. At this point the game
1232> process has no responsibility for updating or relaunching itself.
1233
1234## 17.7 systemd process supervisor
1235
1236The production Node.js process is owned by a `systemd` service. `systemd`
1237therefore already knows when the process has **fully exited**; no separate
1238polling process is needed. Only after the previous `ExecStart` process is
1239gone does `systemd` begin the next service start.
1240
1241The preferred lifecycle is:
1242
1243```text
1244Running Node.js server
1245 |
1246 | graceful planned restart or crash
1247 v
1248Node.js process fully exits
1249 |
1250 v
1251systemd starts the service again
1252 |
1253 +--> conditional update hook
1254 | |
1255 | +--> planned code deployment: git fetch/pull --ff-only
1256 | +--> world-only restart: no Git mutation
1257 | +--> crash/no restart manifest: no Git mutation
1258 |
1259 +--> optional dependency/build step if deployment changed code
1260 |
1261 v
1262Start Node.js server
1263 |
1264 v
1265Startup selects the new active world revision
1266 |
1267 v
1268Gateway opens when the world reports READY
1269```
1270
1271### 17.7.1 Why Git pull must be conditional
1272
1273A naive `ExecStartPre=git pull` on **every** restart is unsafe. Suppose a
1274new commit is detected at 14:00 and correctly scheduled for midnight, but
1275the game process crashes at 16:00. An unconditional pull would deploy the
1276new commit immediately during crash recovery, bypassing the scheduled
1277maintenance window.
1278
1279Therefore the restart manifest distinguishes an intentional deployment
1280restart from an ordinary process failure:
1281
1282```json
1283{
1284 "reason": ["code-update", "world-update"],
1285 "deployCode": true,
1286 "targetCommit": "<optional commit hash>",
1287 "pendingWorldRevision": 184
1288}
1289```
1290
1291The manifest should be written using a temporary file plus atomic rename
1292so the supervisor never consumes a half-written request. The supervisor
1293consumes/removes the request only after it has successfully interpreted
1294it.
1295
1296If the Node.js process dies without a valid deployment request, `systemd`
1297restarts the **currently checked-out version**. This gives fast crash
1298recovery without prematurely deploying pending code.
1299
1300### 17.7.2 Suggested systemd shape
1301
1302A production unit can conceptually look like this:
1303
1304```ini
1305[Unit]
1306Description=Tile MMO Server
1307After=network-online.target
1308Wants=network-online.target
1309
1310[Service]
1311Type=simple
1312User=tilemmo
1313Group=tilemmo
1314WorkingDirectory=/srv/tile-mmo/current
1315
1316# This hook checks the restart manifest. It pulls/builds only when an
1317# intentional deployment was requested. Prefixing with '+' optionally
1318# allows the hook to run with privileges different from the game user.
1319ExecStartPre=+/usr/local/sbin/tile-mmo-update-if-requested
1320ExecStart=/usr/bin/node /srv/tile-mmo/current/dist/server.js
1321
1322Restart=always
1323RestartSec=5s
1324TimeoutStopSec=120s
1325KillSignal=SIGTERM
1326
1327[Install]
1328WantedBy=multi-user.target
1329```
1330
1331`Restart=always` is appropriate here because an explicit
1332`systemctl stop tile-mmo` does not cause systemd to restart the unit,
1333while a clean in-game restart exit and an unexpected crash both do.
1334
1335The exact paths, build command and privilege split are deployment
1336details, but the important invariant is that the **Node.js process does
1337not pull Git itself**.
1338
1339### 17.7.3 Code-update, world-update and crash behaviour
1340
1341| Situation | Restart manifest | Git pull before restart | World revision |
1342|---|---|---|---|
1343| Scheduled code update | `deployCode=true` | Yes, fast-forward only | Activate pending revision if present |
1344| World-editor-only update | `deployCode=false` | No | Activate pending revision |
1345| Manual deployment restart | Explicit admin intent | As requested | Activate pending revision if present |
1346| Unexpected Node.js crash | Missing/invalid | **No** | Continue current active revision |
1347| `systemctl stop` | Irrelevant | No automatic restart | N/A |
1348
1349This preserves the midnight deployment promise even when the game crashes
1350before the scheduled maintenance window.
1351
1352## 17.8 Failure behaviour
1353
1354Deployment should fail closed. If Git cannot fast-forward, a build or
1355migration fails, or startup validation fails, the game must not open to
1356players on a partially updated state. The update hook should log the
1357failure clearly and return non-zero; systemd may retry according to its
1358restart/start-limit policy. Databases remain intact, and backups or
1359snapshots before schema migrations are recommended.
1360
1361A failed **crash recovery** that did not request deployment must not
1362silently switch to a newer Git commit as a recovery strategy.
1363
1364# 18. Future player scripting architecture
1365
1366## 18.1 Scope
1367
1368The custom scripting language is explicitly a later feature. Version 1
1369only needs architectural hooks so adding scripts does not require
1370replacing the player-control or simulation model.
1371
1372## 18.2 Controller abstraction
1373
1374All player actions should already pass through an internal command
1375interface. Manual client input is therefore one possible controller. A
1376future script is another controller that emits the same validated action
1377intentions.
1378
1379```text
1380ClientController ─┐
1381 ├─> ActionCommand queue ─> authoritative game systems
1382ScriptController ─┘
1383```
1384
1385Scripts never mutate ECS components directly. They request actions such
1386as MoveTo, Interact or Attack and receive the same validation as a human
1387client.
1388
1389## 18.3 Online scripted mode
1390
1391A logged-in player may enable the script while remaining connected and
1392observing the game. Control mode explicitly determines whether manual
1393input or the script is currently producing gameplay commands. The server
1394remains authoritative either way.
1395
1396## 18.4 Logout with active script
1397
1398If a player has configured offline script execution, logout removes the
1399network/controller connection but keeps the player entity alive. The
1400entity changes to an offline script-controlled state and continues
1401acting until it dies or its configured offline duration expires.
1402
1403Player online
1404Player + NetworkIdentity + ChunkLoader + Controller
1405↓ logout with offline scripting
1406Player + ScriptController + ChunkLoader + OfflineUntil
1407↓ death OR expiry
1408persist player state → remove runtime entity
1409
1410## 18.5 Offline scripted players and loading
1411
1412An offline scripted player must continue to stimulate the world it
1413traverses, so it retains a ChunkLoader. This is powerful but potentially
1414expensive: thousands of offline scripts could keep large parts of the
1415world active. Offline duration, script CPU budget and concurrent
1416offline-script limits therefore become explicit resource policy, not
1417implementation accidents.
1418
1419## 18.6 Restart continuity
1420
1421A planned restart persists the offline-script state and expiry time,
1422force-unloads the old process, and rehydrates still-valid offline
1423scripted players during startup. This is why the startup index for
1424persistent ChunkLoaders is part of the base architecture.
1425
1426## 18.7 Scripting language safety requirements
1427
1428When the language is implemented, it should be interpreted/compiled into
1429a purpose-built sandbox rather than evaluated as JavaScript. At minimum
1430it should enforce:
1431
1432- No file-system, operating-system, database or arbitrary network
1433 access.
1434
1435- No eval or escape into Node.js objects.
1436
1437- Per-tick/per-event instruction budgets and bounded memory.
1438
1439- Rate-limited expensive operations such as path requests and world
1440 queries.
1441
1442- Capability-based read APIs for nearby visible/known world state.
1443
1444- Action output only through the normal server command pipeline.
1445
1446- Persistable script variables/state if offline execution must survive
1447 restarts.
1448
1449- Deterministic or tightly controlled timing semantics where practical.
1450
1451An event-driven language is preferable to running every player script
1452continuously at full simulation frequency. Events such as arrival,
1453attack, nearby entity changes or timer expiration can wake scripts only
1454when useful.
1455
1456# 19. Security and administration
1457
1458- World-editor endpoints require an explicit admin role and separate
1459 server-side authorisation checks.
1460
1461- Client-supplied entity/player IDs are never trusted as authority;
1462 authenticated connection/session context identifies the actor.
1463
1464- World-editor data is validated against known ground, block, item and mob
1465 definitions before database write.
1466
1467- Admin restart and deployment controls use the same authenticated
1468 administration layer.
1469
1470- The Node.js game process should run as a dedicated unprivileged user.
1471 Where practical, source-update permission belongs only to the systemd
1472 update hook (for example a privileged `ExecStartPre` helper), leaving
1473 the running Node.js process unable to modify its own checkout.
1474
1475- SQLite writes are parameterised and centralised through
1476 persistence/editor services.
1477
1478- Inventory, vault, cheque and courier mutations are server-authoritative.
1479 Clients cannot invent cheque IDs, forge cargo, or credit a vault.
1480
1481- Attack hit/miss and damage are server-authoritative. Clients cannot supply
1482 a roll or a damage result. Shop purchase prices are computed at buy time
1483 on the server.
1484
1485# 20. Recommended process topology
1486
1487```text
1488Clients
1489 |
1490 v
1491WebSocket/API Gateway
1492 |
1493 +-- Region Coordinator ----> Simulation Worker A
1494 | <--> Simulation Worker B
1495 |
1496 +-- Communication Service --> proximity speech
1497 |
1498 +-- CourierService ---------> pigeon cargo / transit
1499 |
1500 +-- BankService ------------> shared vaults / cheques / reservations
1501 |
1502 +-- MarketService ----------> order book / escrow / trades / last-sale index
1503 |
1504 +-- Persistence Service ----> state.sqlite
1505 |
1506 +-- Admin / World Editor ---> world.sqlite
1507
1508External process supervision:
1509systemd ---> conditional deployment hook ---> Node.js relaunch
1510```
1511
1512# 21. Player client architecture
1513
1514## 21.1 FrameworkV3 as a git submodule
1515
1516The player-facing client is built on the shared FrameworkV3 library:
1517
1518<https://gitlab.com/Timfa/frameworkv3>
1519
1520FrameworkV3 contains generic reusable client-side code. Game-specific rendering,
1521UI, input, assets and protocol handling live in this repository, on top of
1522that library. They are not patched into FrameworkV3 unless they are genuinely
1523reusable across games.
1524
1525This repository vendors FrameworkV3 as a **git submodule** rather than
1526copying its source or depending on an unpublished global install.
1527
1528```text
1529mmo/
1530 client/
1531 frameworkv3/ # git submodule → gitlab.com/Timfa/frameworkv3
1532 src/ # this game's client: protocol, UI, world view, assets
1533 server/ # Node.js ECS backend; does not import FrameworkV3
1534```
1535
1536The submodule path is `client/frameworkv3`. A clone of this repo is not
1537client-buildable until submodules are present:
1538
1539```text
1540git clone --recurse-submodules <this-repo>
1541# or, in an existing checkout:
1542git submodule update --init --recursive
1543```
1544
1545The submodule records a **pinned commit**. Bumping FrameworkV3 is an explicit
1546commit in this repository (new submodule SHA). Game code must not rely on an
1547uncommitted dirty checkout of the submodule.
1548
1549Build order:
1550
1551```text
15521. Build FrameworkV3 from client/frameworkv3
15532. Build this game's client against that output
15543. The Node.js server is a separate build and does not link FrameworkV3
1555```
1556
1557The exact FrameworkV3 build command follows that project's own instructions.
1558This game's client build must consume the framework's public/build artefacts,
1559not fork its internals.
1560
1561CI and developer machines check out submodules before the client job. A
1562missing or uninitialized submodule is a failed client build, not a fallback
1563to a system copy of FrameworkV3.
1564
1565If this repo's `master` also ships the built web/desktop client from the
1566same process that deploys the game server, a submodule bump is just another
1567commit and follows the normal midnight restart/deploy path. The running
1568Node.js game process still does not compile or import FrameworkV3.
1569
1570The backend remains the authoritative Node.js ECS simulation described in this
1571document. The client does **not** need to use ECS. It receives only a small
15723×3-chunk view plus player/UI state, so a conventional object/view-model model is
1573simpler and entirely appropriate.
1574
1575## 21.2 Server/client model separation
1576
1577Backend ECS components are not treated as a shared client object model. Network
1578messages form the contract between the two sides.
1579
1580```text
1581Authoritative Node.js ECS
1582 |
1583 | snapshots / deltas / UI state
1584 v
1585Network protocol DTOs
1586 |
1587 v
1588Built FrameworkV3 (from client/frameworkv3 submodule)
1589 |
1590 v
1591This game's client code (client/src)
1592```
1593
1594The two projects may share protocol schemas, enums or generated message types,
1595but the client must not depend on the internal layout of ECS component storage.
1596That allows server internals to be optimised without forcing corresponding
1597client rewrites.
1598
1599## 21.3 Sprite size, pivot and Y-sort
1600
1601World sprites may be any pixel size. The gameplay tile remains 16×16.
1602Each sprite is placed with an automatic pivot: **horizontally centred**,
1603and **8 pixels up from the bottom** of the sprite. That pivot sits on the
1604tile centre, so a 16×16 sprite still fills the tile and a taller sprite
1605stands on the same feet line and extends upward.
1606
1607Each sprite kind — **grounds**, **blocks**, **items**, **mobs**, and
1608**characters** — uses its own per-type asset folder
1609(`client/assets/<kind>/<key>/`). Every base PNG in that folder is a
1610**visual state**. Filenames ending in `-bloom`, `-equip`, or combinations
1611such as `-equip-bloom` are **companions**, not states: `torch-bloom.png`
1612is the bloom overlay for state `torch`, `{state}-equip.png` is the worn
1613equipment overlay for that state, and `{state}-equip-bloom.png` is the
1614bloom overlay for that equip sprite. Companions always live in the same
1615folder as their base state and are never listed as placeable editor
1616states. Image names follow `layer:key:state` (plus `:equip` / `:bloom`
1617suffixes). States are not listed in the type definition: the first base
1618filename in alphabetical (numeric) order is the default. A later gameplay
1619system may set a named state on a placed tile (for example a door
1620`closed` / `open`); unknown names fall back to the default. The editor
1621mouse wheel cycles these states.
1622
1623Bloom companions are drawn on a separate Framework **bloom** render
1624layer that uses `Shader.getBloomPostChain(...)`. Bloom post-chain
1625parameters are live world settings under the Graphics tab.
1626
1627Each type definition may set sprite-sheet playback for every state PNG:
1628
1629```text
1630frames // sub-images in the sheet; default 1
1631framesPerRow // columns in the sheet; default 1
1632animationSpeed // seconds per frame; 0 means still
1633```
1634
1635Blocks and mobiles with oversized sprites are **Y-sorted**: sprites
1636higher on the screen draw behind sprites lower on the screen, using the
1637pivot's world Y (the occupied tile, or the interpolated foot position
1638while walking). Ground tiles and the night overlay stay behind and in
1639front of that pass respectively.
1640
1641Nearest-neighbour sampling still applies so pixels stay sharp under
1642viewport zoom. Zoom scales the whole view uniformly; it is not a
1643per-sprite size override.
1644
1645## 21.4 Viewport, camera and zoom
1646
1647In normal play the viewport is **always centered on the local player's
1648character**. The camera does not free-pan. Scrolling the world happens
1649only because the player moved.
1650
1651The player may zoom in and out within configured minimum and maximum
1652bounds (for example 1× to 4×; the exact numbers are a game setting). Zoom
1653does not move the camera off the player and does not change server
1654visibility: the client still receives only the 3×3 chunk window.
1655
1656The admin world editor is the exception: it frames the selected 16×16
1657chunk and navigates by chunk, as in section 8.1.
1658
1659## 21.5 Client movement interpolation
1660
1661The server jumps mobiles from tile to tile. The client draws a visual
1662lerp between the previous replicated tile and the new one over the
1663interval implied by gait and `WorldSettings` (walk: `1 / walkTilesPerSecond`,
1664run: half of that). If a delta arrives late, clamp the remaining lerp.
1665That lerp is presentation only:
1666
1667- Hit tests, range, pickup and occupancy use the authoritative tile.
1668- A corrected server position snaps the interpolation target; the client
1669 does not accumulate drift.
1670- Interpolation does not entitle the client to send fractional positions.
1671
1672## 21.6 Equipment layers and recolouring
1673
1674A mob (including a player character) is drawn as a **stack of sprites**
1675on the same tile: the body sprite (male or female from character
1676sex, or the mob archetype body), then each piece of visible equipment.
1677Overlays are not baked into the body art.
1678
1679```text
1680draw order (back → front, default)
1681 1. body / mob base
1682 2. boots
1683 3. legs
1684 4. chest
1685 5. head
1686 6. off-hand
1687 7. weapon
1688```
1689
1690Slot draw order is data so a cloak or a two-handed sprite can be inserted
1691without a renderer rewrite. Overlay sprites use the same automatic pivot
1692as other world art (horizontal centre, 8 pixels from the bottom).
1693
1694Equipment items stay in dedicated **equipment slots**, not in the 32
1695inventory slots, while worn. `EquipItem(slotIndex)` moves a legal item
1696from inventory into the matching equipment slot, returning any previously
1697worn item to inventory if there is space. `UnequipItem(equipSlot)` does
1698the reverse. The weapon equipment slot is what combat uses; it replaces
1699the older “wielded flag on an inventory slot” idea.
1700
1701Non-player mobs may carry an `Equipment` component or a simpler appearance
1702list on the mob definition so a guard can show armour without a player
1703inventory.
1704
1705```text
1706Equipment
1707- slots: { head?, chest?, legs?, boots?, weapon?, offhand?, ... }
1708
1709ItemDefinition.equipment?
1710- slot
1711- overlaySpriteId
1712- recolourableChannels?: ["metal"] // omitted if the art is not recoloured
1713- materialId? // e.g. iron, steel; used with "metal"
1714```
1715
1716Inventory icons and worn overlays may be different 16×16 files. Both are
1717world sprites and both go through the size check.
1718
1719### Recolourable equipment
1720
1721Some gear shares one overlay and is tinted per material. Metal armour is
1722the initial case: iron, steel and later metals are not separate full-size
1723art sets.
1724
1725```text
1726MaterialDefinition
1727- materialId // iron, steel, ...
1728- displayName
1729- channel // metal for armour; later channels may include cloth
1730- colour // destination RGB for that channel
1731```
1732
1733A recolourable overlay is authored as:
1734
1735- the 16×16 overlay sprite, with shading in the channel regions, and
1736- an optional 16×16 **channel mask** of the same dimensions, whose pixels
1737 name which recolour channel they belong to (for example a reserved mask
1738 colour meaning `metal`). Unmasked pixels are drawn unchanged.
1739
1740At draw time, masked pixels keep the overlay’s relative brightness
1741(highlights and shadows) and replace the hue/saturation with the
1742item’s `MaterialDefinition.colour`. The client must not invent a colour;
1743the server sends the material id (or the already-resolved colour) on the
1744appearance layer.
1745
1746Iron plate and steel plate therefore share `overlaySpriteId = platebody`
1747and differ only by `materialId`. Non-metal unique art omits
1748`recolourableChannels` and is blitted as authored.
1749
1750Recolour happens on the client as a presentation step. It does not change
1751item identity, combat stats or inventory. Nearby observers receive enough
1752appearance data to apply the same layers and tints.
1753
1754## 21.7 World time and night shading
1755
1756The client treats **world time** as server time minus 1200 years (section
175713.5). It uses that clock-of-day to shade the 3×3 view.
1758
1759At night, tiles that the baked light map says are unreachable from any
1760static light are drawn darker. Tiles a light can reach stay brighter.
1761Light does not bleed through walls: the mask was raycast through passable
1762tiles at editor save, including across chunk borders, so a torch on the
1763edge of one chunk can light tiles in the next.
1764
1765By day, ambient light is full and the baked mask does not darken the
1766ground. The day/night curve (how dark “night” is, dusk length) can stay a
1767world setting or a later tuning value; the invariant is that night uses
1768baked reachability, not a per-frame raycast.
1769
1770The world-editor night-to-day slider is the same shading function, driven
1771by the slider instead of the clock, so an admin can preview a chunk at
1772any light level without changing live world time.
1773
1774# 22. Items, inventory and ground drops
1775
1776## 22.1 Item definitions
1777
1778Every obtainable object is an `ItemDefinition`. Stacking, uniqueness and
1779later economy rules are data on that definition, not special cases in UI
1780code.
1781
1782```text
1783ItemDefinition
1784- itemId
1785- displayName
1786- description
1787- seedValue // base price before player-market adaptation
1788- stackable
1789- maxStackSize // default 99 for stackable items
1790- uniqueInstance // true for letters, filled cheques, and similar
1791- category: ingredient | intermediate | finished | document | other
1792- npcShopAllowed
1793- gatherSources
1794- craftingRecipe(s)
1795- dropTableSources
1796- attack?: AttackProfile // weapons; omitted for non-weapons
1797- equipment?: // worn/wielded visuals; see 21.6
1798 slot
1799 overlaySpriteId
1800 recolourableChannels?
1801 materialId?
1802```
1803
1804A stackable item with no instance data merges with an identical `itemId` in
1805the same container up to `maxStackSize`. Unique-instance items never merge;
1806each occupies its own slot at quantity 1.
1807
1808**Currency is not an inventory item.** Carried money is a numeric `Currency`
1809balance on the player. Banked money is a numeric balance on that player's
1810vault. Coins do not occupy inventory slots and cannot be dropped on the
1811ground in this model.
1812
1813How most items are obtained is specified later. Two source families already
1814fit this model without changing it:
1815
1816- Ground-item spawners in the world editor, analogous to mob spawners.
1817- Later harvesting from the environment by players.
1818
1819Paper, blank cheques and letters are specified now because communication,
1820banking and pigeons depend on them.
1821
1822## 22.2 Player inventory
1823
1824A player inventory has exactly **32 slots**.
1825
1826```text
1827Inventory
1828- slots[32]: empty | ItemStack
1829
1830ItemStack
1831- itemId
1832- quantity // 1 for unique-instance items
1833- instance?: ItemInstance // present only when uniqueInstance is true
1834- origin?: ItemOrigin // crafter or shop NPC; see 22.6
1835```
1836
1837Rules:
1838
1839- A stack occupies exactly one slot, regardless of quantity.
1840- Inserting a stackable item first tries to merge into an existing compatible
1841 stack whose combined quantity would not exceed `maxStackSize`. Stacks are
1842 compatible only when `itemId` matches and `origin` matches (including both
1843 being empty). Any remainder needs an empty slot, or the whole action fails.
1844- Moving, swapping and splitting stacks are ordinary server-validated
1845 commands. The client never asserts the resulting inventory.
1846- Inventory, wallet and vault contents are **player-private UI state**. They
1847 are not part of 3×3 chunk replication. Other clients see ground items and
1848 pigeon entities, not another player's bags or a pigeon's cargo.
1849- Logout and restart persist the full inventory and carried currency in
1850 `state.sqlite`.
1851
1852## 22.3 Paper and letters
1853
1854Blank paper is a stackable item.
1855
1856Writing consumes one paper and produces a **letter**: a unique-instance item
1857whose instance data is text written by a player. A letter is not a mail
1858record and has no inherent recipient. It is just paper with writing on it.
1859
1860```text
1861LetterInstance
1862- letterId
1863- authorPlayerId
1864- body
1865- writtenAt
1866```
1867
1868If the paper stack's quantity is 1, the slot may be converted in place into
1869the letter. If quantity is greater than 1, writing requires a free inventory
1870slot for the new letter and decrements the paper stack.
1871
1872Reading a letter inspects its instance data. Sending a letter is the same
1873pigeon-cargo action used for any other item stack.
1874
1875Maximum letter length is a defined game rule and can be chosen during
1876implementation.
1877
1878## 22.4 Dropping items
1879
1880A player may drop an item stack, or part of a stack, onto their current tile.
1881
1882```text
1883GroundItem
1884- groundItemId
1885- tileX / tileY
1886- ItemStack
1887- droppedAt
1888- expiresAt // droppedAt + WorldSettings.groundItemDespawnDuration
1889- source // player-drop | later: item-spawner
1890- droppedByPlayerId?
1891```
1892
1893Rules:
1894
1895- Player-dropped items remain for `WorldSettings.groundItemDespawnDuration`
1896 (default **10 minutes**), then vanish forever.
1897- Anyone may pick up a ground item. There is no owner lock and no loot-rights
1898 delay.
1899- Ground items **do not block movement** and do not prevent a player from
1900 standing on that tile.
1901- Pickup requires the player to **stand on that tile**. The command names the
1902 `groundItemId` when several stacks share the tile.
1903- Pickup fails if the player's inventory cannot accept the stack (no legal
1904 merge and no empty slot). The ground item is unchanged.
1905- Several distinct stacks may occupy one tile at once.
1906- Later naturally spawned ground items use the same non-blocking
1907 representation, but their lifetime and respawn belong to the item spawner
1908 rather than this 10-minute player-drop timer.
1909
1910Dropped items are not `ChunkLoader`s and do not keep a chunk simulated.
1911
1912They **do** survive chunk unload until `expiresAt`, using timestamp expiry
1913rather than a per-tick countdown. On unload, unexpired ground items are
1914written to `state.sqlite`. On load or wake, items whose `expiresAt` is in
1915the past are discarded and never replicated. Simulating chunks also remove
1916them when the timestamp elapses.
1917
1918If a unique-instance item that encodes a bank reservation (a filled cheque)
1919expires on the ground or is otherwise destroyed without being redeemed, that
1920reservation is released and the reserved goods become available in the
1921issuer's vault again.
1922
1923## 22.5 Pickup and drop commands
1924
1925```text
1926DROP_ITEM(slotIndex, quantity?)
1927PICKUP_ITEM(groundItemId)
1928```
1929
1930Both are intentions. The owning worker validates the actor's tile, inventory
1931space and stack rules, then applies the result. Standing on a tile that has
1932ground items does not pick them up automatically.
1933
1934## 22.6 Item inspection, origin and displayed value
1935
1936Hovering an item — in inventory, a shop stock list, or on the ground — shows
1937at least:
1938
1939```text
1940ItemTooltip
1941- displayName
1942- description
1943- originLabel // who crafted it, or the shop NPC if bought there
1944- currentValue // undiscounted adapted value; see section 27
1945```
1946
1947Origin is stored on the stack:
1948
1949```text
1950ItemOrigin
1951- kind: crafted | shop | unknown
1952- playerId? // when crafted by a player
1953- npcId? // when bought from a shop NPC
1954```
1955
1956The origin label is the crafting player's name, or the shop NPC's name when
1957the stack was bought from that NPC. Harvested, looted or otherwise unstamped
1958stacks use `unknown` and omit the origin line until later content says
1959otherwise. Buying from a shop stamps that NPC as origin. Crafting stamps the
1960crafter. Shop-bought goods are not treated as crafted by the NPC; the NPC
1961name simply occupies that inspection field.
1962
1963`currentValue` uses the same last-sale lerp as shopkeepers (section 27.6) but
1964**without** the per-shop discount. It is informational. The client must not
1965recompute it every simulation tick. The player UI may refresh displayed
1966values at most once per minute, from the last-sale record plus `seedValue`.
1967The actual shop purchase price is always computed server-side at the moment
1968of purchase.
1969
1970# 23. Player communication and carrier pigeons
1971
1972## 23.1 Proximity chat is the default
1973
1974Ordinary chat is spatial. A player speaks from a world position and only nearby
1975players receive a useful version of the message. Legibility decreases as the
1976recipient gets farther from the speaker.
1977
1978Readability uses Euclidean tile distance against the 16-tile chunk size:
1979
1980```text
1981distance <= 8 tiles // half a chunk: full plaintext
19828 < distance < 16 // linear falloff, e.g. 12 tiles → 50% readability
1983distance >= 16 tiles // a full chunk: 0% readability, no bubble
1984```
1985
1986The speaker always receives their own trimmed plaintext. Other recipients receive
1987a server-obscured copy: letters and digits may become `.` with probability
1988`1 - readability`; spaces and punctuation stay. At 0% readability the server
1989sends nothing, so the client never draws a bubble.
1990
1991Enter opens a bottom-of-screen line (max `chatMaxCharacters`, default 100).
1992Enter again trims and sends `CHAT_SAY`. Escape cancels. The client shows
1993`CHAT_BUBBLE` above the speaker.
1994
1995For example:
1996
1997```text
1998Near: I'm really far away
1999Farther: I'm re...y far aw.y
2000Very far: I'...re..ly..ar.aw.y
2001Beyond range: no message
2002```
2003
2004Crucially, degradation is performed **server-side**. The server must not send the
2005full plaintext to a distant client and merely ask that client to obscure it,
2006because a modified client could then recover speech it was not supposed to
2007understand.
2008
2009A chat message therefore conceptually contains:
2010
2011```text
2012ChatSpeech
2013- messageId
2014- speakerEntityId
2015- originX / originY
2016- createdAt
2017- text
2018```
2019
2020The communication service performs a spatial recipient query and derives the
2021recipient-specific legible representation before routing it through the gateway.
2022Chat routing is separate from normal 3×3 chunk replication, so the eventual
2023hearing/text range does not have to equal the visual chunk-subscription radius.
2024
2025## 23.2 Persistent player groups
2026
2027Players can create permanent groups and invite other players into them. Groups
2028are durable social entities stored in `state.sqlite`, with membership surviving
2029logout and server restart.
2030
2031A minimal model contains:
2032
2033```text
2034PlayerGroup
2035- groupId
2036- name
2037- owner / roles
2038- createdAt
2039
2040PlayerGroupMember
2041- groupId
2042- playerId
2043- role
2044- joinedAt
2045```
2046
2047Invite, accept, leave, kick and role-management operations are authoritative
2048server actions.
2049
2050Group membership does **not** create magical long-distance communication. If
2051members are close enough, they can communicate through the normal proximity
2052rules. Communication to distant group members means sending items — including
2053letters — by carrier pigeon, the same mechanism available to any player.
2054
2055If group-wide letter sending is later supported, it is an addressing
2056convenience that still consumes one paper/letter item and one pigeon dispatch
2057per recipient. The group is not a global instant chat channel.
2058
2059## 23.3 Pigeons carry cargo, not messages
2060
2061A carrier pigeon is a free physical courier. It does not send a chat packet.
2062It carries **either**:
2063
2064- an amount of the sender's carried currency, or
2065- exactly one item stack (a letter, a filled cheque, blank paper, or any
2066 other stack)
2067
2068One pigeon cannot carry both money and an item, and cannot carry two item
2069stacks. Dispatching a pigeon is **free**, so a player who wants to move
2070several stacks sends several pigeons one after another.
2071
2072Cargo is removed from the sender immediately and placed into durable transit.
2073A crash or restart cannot duplicate that cargo or silently erase it.
2074
2075Pigeons are not inventory items. Any player may dispatch one from anywhere,
2076provided they have valid cargo.
2077
2078```text
2079SendPigeon
2080- destination: Player(playerId) | Bank
2081- cargo: Money(amount) | Item(slotIndex, quantity?)
2082```
2083
2084## 23.4 Destinations
2085
2086**Player destination.** The pigeon flies toward a character addressed by
2087**first name and last name**. The sender may type that pair, or pick a
2088friend from their friends list to fill the same fields. On arrival:
2089
2090- Money is added to the recipient's carried `Currency` if they are online;
2091 otherwise it is deposited into the recipient's bank.
2092- An item stack is placed in the recipient's inventory if they are online and
2093 have space (a legal merge or an empty slot). If they are offline or cannot
2094 accept the stack, the pigeon continues to the **nearest bank** and deposits
2095 the stack into the recipient's vault.
2096
2097This keeps offline and full-inventory delivery durable without a separate
2098mailbox object.
2099
2100**Bank destination.** The pigeon flies to the **nearest bank** to the dispatch
2101tile. Travel time is that aerial journey, even though every bank shares the
2102same vault. On arrival the cargo is deposited into the **sender's** vault,
2103except for the filled-cheque special case in section 24.7.
2104
2105"Nearest bank" is computed from authored Bank block positions in the pinned
2106world revision. If additional banks are added later, a pigeon sent to `Bank`
2107still lands at whichever bank is closest to where it was dispatched; the
2108goods then appear in the shared vault.
2109
2110## 23.5 Carrier pigeon transit
2111
2112A carrier pigeon must take time to cross the world; long-distance item and
2113currency delivery is intentionally not instantaneous.
2114
2115At MMO scale, however, every delivery should not keep an entire trail of regions
2116fully stimulated merely so a pigeon can advance. The recommended model is a
2117persistent courier transit record with world position/route/progress that can
2118advance through dormant space using coarse path segments and timestamps.
2119
2120```text
2121CourierTransit
2122- courierId
2123- cargo // Money(amount) | ItemStack
2124- senderPlayerId
2125- destination // Player(playerId) | Bank
2126- currentPosition
2127- route
2128- speed / timing state
2129- status
2130```
2131
2132A carrier pigeon is part of the shared physical world, not a private visual
2133belonging only to its sender or recipient. Whenever its calculated route passes
2134through a **simulating chunk**, the courier should materialise there as a normal
2135ECS `Mob` entity, regardless of whether the sender or recipient is nearby. Any
2136client whose normal 3x3 chunk subscription includes that pigeon receives it like
2137any other visible mobile entity and can therefore see unrelated pigeons flying
2138past in the distance.
2139
2140The visible pigeon does **not** receive `ChunkLoader`. It exists because the chunk
2141is already simulating for some other reason. If it leaves the last relevant
2142simulating chunk, its exact position/progress is folded back into the durable
2143`CourierTransit` record and the ECS instance can disappear while the journey
2144continues abstractly. If a dormant/unloaded part of its route later becomes
2145simulated while the pigeon should currently be inside it, the owning worker
2146materialises the pigeon at the position implied by the transit clock and route.
2147
2148```text
2149Dormant route Simulating chunk Dormant route
2150
2151abstract transit --------> ECS pigeon visible to clients --------> abstract transit
2152 | | |
2153 Player A Player B unrelated observer
2154```
2155
2156This means a player standing halfway between sender and recipient can see the
2157pigeon fly through their area even though the cargo has nothing to do with
2158them. Unrelated clients receive the pigeon entity, not the cargo contents. It
2159preserves the sense that deliveries physically cross the world without
2160requiring thousands of deliveries to become thousands of permanent
2161`ChunkLoader`s.
2162
2163Because pigeons fly rather than use the ground navigation grid, their coarse
2164route can initially be represented by direct or waypoint-based aerial segments.
2165This makes deterministic materialisation from route + elapsed time considerably
2166simpler than it would be for a ground-based courier.
2167
2168If future gameplay allows pigeons to be intercepted, killed or rerouted anywhere
2169along their journey, the transit model can be made progressively more detailed;
2170that interaction is not required by the initial courier design.
2171
2172## 23.6 Courier service
2173
2174A dedicated `CourierService` should own durable cargo and delivery state.
2175Simulation workers may own visible pigeon entities while the service owns the
2176durable fact that a delivery exists.
2177
2178```text
2179Player action -> CourierService -> durable cargo/transit
2180 |
2181 +-> visible pigeon when needed
2182 |
2183 +-> inventory, wallet or BankService deposit
2184```
2185
2186This separation is also useful for marketplace settlement, which uses the same
2187carrier-pigeon delivery infrastructure for remote counterparties.
2188
2189## 23.7 Character friends
2190
2191Friendships are **character-to-character**, stored in `state.sqlite`. They
2192are not account-wide. A hovering client shows only the nearby character's
2193**first name**. Clicking that character opens an inspect modal with first
2194and last name and a friend-request action.
2195
2196A friend request must be accepted (or a reverse request counts as accept).
2197Either character may remove the friendship; it then disappears for both.
2198Incoming and outgoing requests and the friends list are shown in a Friends
2199panel. Deleting a character clears its requests and friendships.
2200
2201The friends list is an addressing book for later pigeon dispatch: pick a
2202friend to fill first and last name, or type a name pair that the server
2203resolves.
2204
2205```text
2206FriendRequest
2207- fromCharacterId
2208- toCharacterId
2209- createdAt
2210
2211Friendship
2212- characterIdA // min(id1, id2)
2213- characterIdB // max(id1, id2)
2214- createdAt
2215```
2216
2217# 24. Bank, cheques and shared vaults
2218
2219## 24.1 Bank location and access
2220
2221A bank exists at or near the central marketplace as an authored Bank block.
2222Deposit, withdraw, cheque issue and in-person cheque redemption require
2223server-validated access to a bank interaction; the bank is not a global menu
2224usable from anywhere.
2225
2226Pigeon dispatch to `Bank` is the exception: that command may be issued from
2227anywhere, and the goods become available only after the pigeon arrives.
2228
2229## 24.2 One shared vault
2230
2231Each **character** has a single vault in `state.sqlite`:
2232
2233```text
2234CharacterVault
2235- characterId
2236- bankedCurrency
2237- stacks[]
2238- reservations[]
2239```
2240
2241Capacity is unlimited: there is no slot cap. Per-stack stacking rules still
2242apply (`maxStackSize`; unique instances never merge), so 200 blank paper is
2243stored as 99 + 99 + 2 rather than one unbounded pile.
2244
2245If more banks are authored later, **all banks are linked**. Withdrawing at
2246bank B can retrieve goods deposited at bank A. The vault is not per-branch.
2247
2248Pigeon deposits affect *when* goods become available, not *which* vault they
2249enter. After the pigeon arrives at the nearest bank, the goods appear in the
2250same shared vault accessible from every bank.
2251
2252## 24.3 Deposit and withdraw
2253
2254While interacting with a bank, a player may:
2255
2256- Deposit any carried currency and any inventory stacks, in whole or in part.
2257- Withdraw currency into the carried wallet.
2258- Withdraw an item stack, or part of a stack, into inventory, subject to the
2259 32-slot and merge rules.
2260- Claim items or currency from the account **inheritance tab** into this
2261 character's vault (section 24.9).
2262
2263Goods reserved by an outstanding filled cheque cannot be withdrawn by the
2264issuer until that cheque is redeemed or voided.
2265
2266## 24.4 Blank cheques
2267
2268A player at a bank may request blank cheques.
2269
2270- Blank cheques are a stackable item with `maxStackSize` 99.
2271- The bank counts blank cheques already in the player's **inventory** (not
2272 the vault) and issues only enough to bring that total to 99.
2273- If the player already holds 99, the bank issues none.
2274- Issued cheques go into inventory, merging into an existing blank-cheque
2275 stack when possible. If the player holds none and has no empty slot, the
2276 request fails.
2277
2278The bank will not issue more than 99 blank cheques into inventory, even on
2279repeated requests.
2280
2281## 24.5 Filling a cheque
2282
2283Using a blank cheque at a bank lets the issuer pick vault goods and a
2284**quantity**. For stackable items they choose an `itemId` and quantity; the
2285quantity may be larger than one `maxStackSize`, and the reservation covers
2286that many available (unreserved) items of that type in the vault. For
2287unique-instance items they choose that exact instance and the quantity is 1.
2288
2289```text
2290FilledChequeInstance
2291- chequeId
2292- issuerPlayerId
2293- itemId
2294- quantity
2295- instance?: ItemInstance // set when the reserved goods are unique
2296- createdAt
2297```
2298
2299Filling:
2300
23011. Validates that the vault has at least `quantity` of that item available
2302 (not already reserved). Unique instances must still be present and unreserved.
23032. Reserves those goods in the issuer's vault. Reserved goods cannot be
2304 withdrawn, sold or reserved again.
23053. Consumes one blank cheque. If that was the last cheque in the slot, the
2306 slot becomes the filled cheque in place; otherwise a free slot is required
2307 for the filled cheque.
2308
2309A filled cheque is a unique-instance **bearer** item. It does not stack.
2310Whoever holds it may redeem it. Cheques specify vault items and a quantity,
2311not carried currency. Money is moved with a pigeon, or by depositing and
2312withdrawing at a bank.
2313
2314## 24.6 Redeeming a cheque in person
2315
2316The bearer interacts with any bank and redeems the filled cheque.
2317
2318- The server moves the reserved goods from the **issuer's** vault into the
2319 **bearer's inventory**, subject to inventory space. A quantity larger than
2320 `maxStackSize` becomes as many stacks as needed.
2321- The cheque item is consumed.
2322- If inventory cannot accept the resulting stacks, redemption fails and both
2323 cheque and reservation remain unchanged.
2324
2325The bearer may then deposit those goods into their own vault if they wish.
2326
2327## 24.7 Redeeming a cheque by pigeon
2328
2329If the bearer dispatches a pigeon whose cargo is a filled cheque and whose
2330destination is `Bank`:
2331
2332- The pigeon flies to the nearest bank from the dispatch tile.
2333- On arrival, `BankService` transfers the reserved goods from the **issuer's**
2334 vault into the **pigeon's sender's** vault.
2335- The cheque is consumed in transit; it is not deposited as an item.
2336
2337The receiver of the transfer is whoever sent that pigeon, not the original
2338cheque issuer. This is how a cheque moves goods from one vault to another
2339without the receiver standing at a bank.
2340
2341Sending a filled cheque to a **player** delivers the cheque item itself (or
2342into that player's bank if they cannot hold it). It does not redeem it.
2343
2344## 24.8 Bank service
2345
2346Vault mutation, cheque issue, reservation, in-person redemption and
2347pigeon-arrival deposits are owned by a single authoritative `BankService`
2348(or an equivalently serialised service) so two concurrent withdrawals,
2349cheque fills or pigeon arrivals cannot double-spend the same goods.
2350
2351```text
2352Bank interaction or pigeon arrival
2353 |
2354 v
2355BankService
2356 - shared vault
2357 - reservations
2358 - cheque issue / redeem
2359 |
2360 +-> inventory / currency on the acting player when in person
2361 |
2362 +-> vault credit on pigeon arrival
2363```
2364
2365Cheque identifiers are server-issued. A client cannot forge a claim against
2366another player's vault.
2367
2368## 24.9 Inheritance bank tab
2369
2370Each **account** has one inheritance tab, separate from every character
2371vault:
2372
2373```text
2374AccountInheritance
2375- accountId
2376- currency
2377- stacks[]
2378```
2379
2380It is written only when a character of that account is permanently deleted
2381(section 14.6). Any of that player's living characters can move stacks and
2382currency from this tab into their own vault at a bank. They cannot deposit
2383into inheritance except through character deletion.
2384
2385# 25. Central marketplace and order matching
2386
2387## 25.1 Marketplace location
2388
2389A central marketplace exists at or near the centre of the game world. Creating,
2390modifying or cancelling market orders requires server-validated access to the
2391marketplace interaction; the marketplace is not intended to be a global menu
2392that can be used from anywhere.
2393
2394Orders themselves remain durable after the player leaves the marketplace or
2395logs out.
2396
2397## 25.2 No public list of sell orders
2398
2399The market is an order book, but players do not browse a list of individual
2400items currently offered for sale.
2401
2402A seller submits:
2403
2404```text
2405SellOrder
2406- item / item definition
2407- quantity
2408- minimum unit/total price
2409```
2410
2411A buyer submits:
2412
2413```text
2414BuyOrder
2415- requested item / matching criteria
2416- quantity
2417- maximum unit/total price
2418```
2419
2420The UI may know which item types exist and may eventually show historical data,
2421but it does not expose the live asks in a way that lets a buyer simply pick a
2422listed seller.
2423
2424## 25.3 Escrow
2425
2426Market orders escrow the asset required to honour them. Escrow is taken from
2427carried inventory and carried currency. The marketplace sits next to the bank,
2428so a player can withdraw from the vault immediately before placing an order.
2429
2430- Creating a sell order removes/reserves the offered item stack from the
2431 seller's inventory.
2432- Creating a buy order removes/reserves the buyer's maximum offered currency.
2433- Cancelling an unmatched order returns the escrowed asset through the defined
2434 settlement/delivery rules.
2435
2436This prevents double spending, selling the same item twice, or a buyer spending
2437currency after placing a bid.
2438
2439## 25.4 Matching rules
2440
2441A buy and sell order match when:
2442
2443```text
2444buyerMaximum >= sellerMinimum
2445```
2446
2447Sell orders are considered cheapest first. Within the same minimum price, a
2448stable creation sequence/FIFO rule should be used unless later game rules choose
2449otherwise.
2450
2451For a symmetric order book, buy orders are naturally prioritised by highest
2452maximum bid and then oldest sequence. This means a newly submitted sell order
2453matches the best compatible existing bid, while a newly submitted buy order
2454matches the cheapest compatible existing ask.
2455
2456The trade price is exactly the midpoint between the two limits:
2457
2458```text
2459tradePrice = midpoint(buyerMaximum, sellerMinimum)
2460```
2461
2462Example:
2463
2464```text
2465Seller minimum: 80
2466Buyer maximum: 100
2467Trade price: 90
2468```
2469
2470The exact rounding rule when integer currency produces a half-unit midpoint is a
2471defined-but-still-open game rule and must be deterministic.
2472
2473## 25.5 Immediate side versus pigeon side
2474
2475The order that is submitted last is the order that triggers the match.
2476
2477The player who submitted that matching order receives the acquired asset
2478immediately because they are currently present at the marketplace interaction
2479(item stack into inventory, or currency into the carried wallet). The
2480pre-existing counterparty receives their acquired item or currency through a
2481carrier pigeon whose destination is `Bank`, landing at the nearest bank to the
2482marketplace. On arrival the settlement is deposited into that counterparty's
2483shared vault. This remains valid if they are offline.
2484
2485```text
2486Existing sell + new matching buy
2487-> new buyer receives item immediately
2488-> existing seller receives payment by pigeon to bank
2489
2490Existing buy + new matching sell
2491-> new seller receives payment immediately
2492-> existing buyer receives item by pigeon to bank
2493```
2494
2495If a trade requires more than one item stack (for example a quantity that does
2496not fit in a single `maxStackSize`), the older counterparty receives as many
2497free sequential pigeons as needed. Each pigeon still carries only one stack or
2498only currency.
2499
2500Any unused part of buy-order currency escrow caused by the midpoint price is
2501returned immediately to the triggering player when they are the buyer, and
2502returned by the settlement pigeon into the older counterparty's vault when
2503they were the buyer.
2504
2505## 25.6 Market service and atomicity
2506
2507Marketplace matching should not live inside an arbitrary region worker. Use a
2508single authoritative `MarketService` (or an equivalently serialised partitioned
2509service later) so two simultaneous orders cannot both consume the same escrow.
2510
2511Order insertion, matching, escrow movement and creation of the resulting
2512settlement deliveries are committed atomically in `state.sqlite`.
2513
2514Conceptually:
2515
2516```text
2517Marketplace interaction
2518 |
2519 v
2520MarketService
2521 - durable order book
2522 - escrow
2523 - deterministic matching
2524 - trade record
2525 |
2526 +-> immediate settlement to triggering player's inventory or wallet
2527 |
2528 +-> CourierService pigeon to Bank for the older counterparty
2529 |
2530 +-> last-sale index update for that itemId
2531```
2532
2533The system should also retain an immutable trade record for auditing and recovery.
2534
2535## 25.7 Last player-market sale per item
2536
2537Each successful player-market match updates a single durable record for that
2538`itemId`. There is no price history series — only the latest sale:
2539
2540```text
2541ItemLastMarketSale
2542- itemId
2543- lastTradePrice // unit price of that match (the midpoint)
2544- lastTradeAt
2545- priceFrom // evaluated undiscounted value at lastTradeAt
2546```
2547
2548`priceFrom` is not a history log. It is the lerp origin captured at the
2549moment of this sale so the displayed price does not jump back to seed when
2550a new trade occurs:
2551
25521. Evaluate the current undiscounted value at `now` using the previous
2553 last-sale record (or `seedValue` if none exists).
25542. Store that value as `priceFrom`, store the new trade's unit price as
2555 `lastTradePrice`, and store `now` as `lastTradeAt`.
2556
2557Shopkeepers and item tooltips both read this record. They do not tick it;
2558they evaluate it from timestamps when a shop is opened, a purchase is
2559attempted, or a tooltip refresh is requested.
2560
2561# 26. Combat
2562
2563## 26.1 Every combatant can attack
2564
2565Players, enemies, animals and any other mobile with a `Combat` component can
2566attack. Shopkeepers and other non-fighting NPCs simply omit `Combat`, or
2567never issue attack commands.
2568
2569Attacking is an intention. The client (or AI, or a future script) sends
2570`ATTACK(targetEntityId)`. The owning worker validates range, line-of-use,
2571the current attack profile and cooldown, then resolves hit and damage
2572authoritatively. The client never supplies a hit result or a damage number.
2573
2574Cross-worker attacks already use `REMOTE_ACTION(attack intent)`: the worker
2575that owns the target applies the authoritative result.
2576
2577## 26.2 Attack profiles
2578
2579The current attack comes from the wielder's selected profile: a wielded
2580weapon's `AttackProfile`, a selected spell, or a default unarmed melee
2581profile when nothing is wielded.
2582
2583```text
2584AttackProfile
2585- attackId
2586- mode: melee | ranged | magic
2587- rangeTiles // melee is always 1; ranged/magic from the item or spell
2588- hitSkillId
2589- damageSkillId
2590```
2591
2592```text
2593SpellDefinition
2594- spellId
2595- displayName
2596- AttackProfile // mode = magic, hitSkillId = Magic, damageSkillId = Mind
2597- other costs/effects // later content
2598```
2599
2600Typical weapon mappings:
2601
2602```text
2603Sword -> melee, range 1, hit Swordfighting, damage Strength
2604Axe -> melee, range 1, hit Axefighting, damage Strength
2605Bow -> ranged, range from item, hit Archery, damage Dexterity
2606Spell -> magic, range from spell, hit Magic, damage Mind
2607Unarmed -> melee, range 1, hit Unarmed, damage Strength
2608```
2609
2610The exact weapon and spell catalogue is content. The pairing rule is not:
2611melee weapons use a weapon skill plus **Strength**, ranged weapons use a
2612weapon skill plus **Dexterity**, and spells use **Magic** plus **Mind**.
2613
2614`EquipItem(slotIndex)` moves a legal item from inventory into the matching
2615equipment slot (section 21.6). The **weapon** slot supplies the current
2616`AttackProfile`. `SelectSpell(spellId)` selects a spell the actor is
2617allowed to use. The selected profile determines range and both skills.
2618
2619## 26.3 Melee range
2620
2621A melee attack is legal only when the attacker stands on **one of the eight
2622tiles surrounding** the target's tile: orthogonal or diagonal, Chebyshev
2623distance exactly 1. The attacker cannot melee from the target's own tile.
2624
2625```text
2626. . .
2627. T . attacker must occupy one of the eight `.` tiles
2628. . .
2629```
2630
2631This adjacency rule is independent of whether ordinary walking is four- or
2632eight-directional.
2633
2634## 26.4 Ranged attacks and spells
2635
2636Ranged weapons and spells may fire from further away. Maximum Chebyshev
2637distance is `rangeTiles` on that item or spell. Distance 0 (same tile) is
2638not a legal ranged/spell attack unless a later exception is defined.
2639
2640The attacker must still occupy a simulating chunk and satisfy any later
2641line-of-sight rule. Exact obstruction rules are an open content decision;
2642range itself is not.
2643
2644## 26.5 Hit roll
2645
2646Whether the attack lands is a server-side roll driven by the **hit skill**
2647of the current profile (Swordfighting, Axefighting, Archery, Magic, Unarmed,
2648and so on). The client does not roll.
2649
2650The exact hit curve, any defender contribution from Defence, and the RNG
2651are later tuning. The invariant is that the hit chance is a function of the
2652attacker's hit-skill level, not of Strength, Dexterity or Mind.
2653
2654A miss deals no damage.
2655
2656## 26.6 Damage
2657
2658On a hit, damage is determined by the **damage skill**:
2659
2660- Melee → Strength
2661- Ranged → Dexterity
2662- Magic → Mind
2663
2664Weapon or spell base damage and the defender's mitigation (including whether
2665Defence reduces damage) are later tuning. The governing damage skill is not.
2666
2667## 26.7 Experience split
2668
2669When a **player** successfully hits, the attack's XP award is split equally
2670between the hit skill and the damage skill:
2671
2672```text
2673totalXp = attack xp formula for this successful hit
2674hitSkill += totalXp / 2
2675damageSkill += totalXp / 2
2676```
2677
2678Example: a sword hit awards half its XP to Swordfighting and half to
2679Strength. A bow hit splits Archery and Dexterity. A spell hit splits Magic
2680and Mind.
2681
2682If an unusual profile ever named the same skill twice, XP is awarded once,
2683not doubled. Misses award no combat XP. Ordinary mobs do not earn XP; their
2684`Skills` component is filled from the mob archetype and stays at those
2685levels.
2686
2687Non-combat actions remain single-skill as in section 27.4.
2688
2689## 26.8 Mob combat stats
2690
2691```text
2692MobDefinition
2693- ...
2694- skillLevels: { skillId → level }
2695- defaultAttack: attackId | unarmed
2696```
2697
2698A wolf might have Unarmed and Strength. An archer guard might have Archery
2699and Dexterity. Those levels feed the same hit and damage resolution as
2700players.
2701
2702# 27. Player-driven economy and skill progression
2703
2704## 27.1 Item-source philosophy
2705
2706The economy is intentionally player-driven.
2707
2708Normal NPC shops should sell only basic ingredients. The vast majority of
2709materials are gathered directly from the world by players. Finished goods are
2710normally produced by player crafting/professions.
2711
2712The only normal non-player source of finished items is enemy or boss loot.
2713
2714This gives four broad source paths, with ground-item spawners as an additional
2715early world source once content defines them:
2716
2717```text
2718World gathering / harvesting -> ingredients
2719Ground-item spawners --------> some world items, later specified
2720Basic NPC shops -------------> limited basic ingredients
2721Player production -----------> intermediate/final products
2722Enemies and bosses ----------> loot, including possible finished items
2723```
2724
2725Stacking, unique instances, letters and cheques are defined in section 22.
2726Economy-facing fields remain on the same `ItemDefinition`:
2727
2728```text
2729ItemDefinition
2730- itemId
2731- displayName / description / seedValue
2732- stackable / maxStackSize / uniqueInstance
2733- category: ingredient | intermediate | finished | document | other
2734- npcShopAllowed
2735- gatherSources
2736- craftingRecipe(s)
2737- dropTableSources
2738- attack?: AttackProfile
2739- equipment?: slot / overlaySpriteId / recolourableChannels / materialId
2740```
2741
2742Content validation can then reject an ordinary shop inventory that accidentally
2743contains a finished product unless explicitly permitted by a future exception.
2744
2745## 27.2 No player classes
2746
2747Players do not choose a class. Capabilities and progression come from independent
2748skills.
2749
2750Examples include:
2751
2752- Swordfighting, Axefighting, Archery, Magic, Unarmed
2753- Strength, Dexterity, Mind
2754- Defence
2755- Lumbering
2756- Fishing
2757- Smithing
2758
2759The final skill list is game content and is not limited to skills found in any
2760particular inspiration game.
2761
2762## 27.3 Skill state
2763
2764Skill progression is persistent player state.
2765
2766```text
2767SkillProgress
2768- skillId
2769- xp
2770```
2771
2772Level should preferably be derived from XP and the skill's level curve rather
2773than stored as an independent source of truth, although it may be cached.
2774
2775```text
2776SkillDefinition
2777- skillId
2778- displayName
2779- levelCurve
2780- maxLevel (if any)
2781```
2782
2783## 27.4 Actions are governed by skills
2784
2785Every gameplay action that participates in progression is associated with a
2786governing skill. Combat attacks are the explicit exception: they have a hit
2787skill and a damage skill, and split XP equally between them (section 26.7).
2788
2789```text
2790ActionDefinition
2791- actionId
2792- governingSkillId
2793- requiredLevel
2794- xpAward / xpFormula
2795- other requirements
2796```
2797
2798Examples:
2799
2800```text
2801Cut tree -> Lumbering
2802Catch fish -> Fishing
2803Forge sword -> Smithing
2804Sword hit -> Swordfighting + Strength (equal split)
2805Bow hit -> Archery + Dexterity (equal split)
2806Spell hit -> Magic + Mind (equal split)
2807Defensive act -> Defence
2808```
2809
2810The server validates the action, performs the authoritative outcome, and then
2811awards XP according to the action result. A client cannot claim XP independently.
2812
2813## 27.5 Skills replace class restrictions
2814
2815Equipment, recipes, actions, gathering nodes and other content may require skill
2816levels, but there is no permanent class gate. A player can train any combination
2817of skills over time.
2818
2819This also fits the future scripting model: scripts issue normal actions, and
2820successful scripted actions use exactly the same skill checks and XP rules as
2821manual player actions.
2822
2823## 27.6 NPC shops and market-adapted prices
2824
2825Named shop NPCs can sell items to players. They are not the player marketplace
2826and they do not expose live sell orders. A shop interaction requires being at
2827that NPC.
2828
2829Stock remains constrained by `npcShopAllowed` and the ingredient-only rule in
283027.1. Each shop NPC has a hidden discount that players never see:
2831
2832```text
2833ShopNpc
2834- npcId
2835- hiddenDiscount // multiplier, e.g. 0.9; not shown to clients
2836- stock[] // itemIds this NPC sells
2837```
2838
2839Until an `itemId` has a player-market last-sale record, the undiscounted
2840value is `seedValue` from the item definition.
2841
2842When a last-sale record exists, both tooltips and shops evaluate a timestamp
2843lerp that does not require a per-tick update:
2844
2845```text
2846t = min(1, (now - lastTradeAt) / WorldSettings.shopPriceLerpDuration)
2847undiscounted = lerp(priceFrom, lastTradePrice, t)
2848shopPrice = undiscounted * thatNpc.hiddenDiscount
2849```
2850
2851`lerp(a, b, t) = a + (b - a) * t`. After the configured lerp duration
2852(default one hour), `t` is capped at 100% and the value rests on the last
2853player-market unit price (times discount, for shops) until another
2854player-market sale occurs.
2855
2856A new player-market sale captures the then-current `undiscounted` value as
2857`priceFrom` (section 25.7), so the lerp restarts toward the new last price
2858without jumping back to seed.
2859
2860Integer currency must be rounded deterministically at evaluation time. Shop
2861purchase price is computed on the server at the instant of `BuyFromShop`.
2862Displayed tooltip value is the undiscounted figure and may be refreshed at
2863most once per minute (section 22.6).
2864
2865Buying from a shop removes the listed price from the player's carried
2866currency, puts the stack in inventory subject to the 32-slot rules, and
2867stamps `ItemOrigin.kind = shop` with that NPC. Shops in this model sell to
2868players; they do not buy player goods unless a later iteration adds that.
2869
2870# 28. Suggested implementation phases
2871
2872## Phase 1 — Single-worker playable core
2873
2874- World coordinate helpers, 16×16 chunks and 4×4-chunk regions.
2875
2876- Ground/block tile model and chunk spatial occupancy.
2877
2878- Basic ECS and fixed simulation tick.
2879
2880- ChunkLoader reference counting and sleeping/unloading.
2881
2882- Isolated simulation workers behind a clone-on-boundary protocol
2883 (in-process default; `worker_threads` optional).
2884
2885- world.sqlite read path and state.sqlite persistence service.
2886
2887- Admin world editor: chunk navigation, open/closed flag, default grass for
2888 unsaved chunks, ground/block paint, light-emitting blocks, baked
2889 cross-chunk light maps, night-to-day preview slider, world settings modal
2890 with live apply and a settings edit log, per-chunk changelog, chunk save
2891 to pending revision.
2892
2893- SpawnerSystem for at least one non-persistent mob archetype.
2894
2895- WebSocket gateway, stub `admin-<n>` auth until auth.timfalken.com,
2896 character create/select/delete, authoritative command queue and 3×3 chunk
2897 replication.
2898
2899- Click-to-move with server-side A\*, global walk/run cadence (default 2
2900 tiles/s walk, run every movement tick, walk every other), and `SetGait`.
2901
2902- FrameworkV3 git submodule at `client/frameworkv3`, built first, then a
2903 game-specific client on top of it with 16×16 sprites, load-time and CI
2904 rejection of wrong-sized art (including equipment overlays and recolour
2905 masks), layered worn equipment with material recolouring, a
2906 player-centered viewport with bounded zoom, client-only lerp of
2907 tile-to-tile movement, and night shading from baked light maps.
2908
2909- 32-slot player inventory, stack merging, drop/pickup, and 10-minute
2910 non-blocking ground items.
2911
2912- Paper items that can be written into unique letter items.
2913
2914- Basic proximity chat with server-side distance degradation.
2915
2916- Persistent player skill state, including Strength, Dexterity and Mind, and
2917 at least a small initial set of skill-governed actions.
2918
2919- Melee and ranged/spell attack validation (8-tile melee adjacency, item/spell
2920 range), server-side hit rolls, damage from the matching damage skill, and
2921 equal XP split on a successful player hit.
2922
2923- Graceful forced-unload shutdown.
2924
2925## Phase 2 — Operations and live deployment
2926
2927- RestartScheduler and player-visible scheduled restart state.
2928
2929- origin/master change detection.
2930
2931- `systemd` service supervision and conditional deployment hook.
2932
2933- World-revision activation on restart.
2934
2935- Admin immediate restart.
2936
2937- Migration, backup and startup readiness checks.
2938
2939## Phase 3 — Multi-worker world
2940
2941- Multiple isolated simulation workers and neighbour-sticky region ownership
2942 (shipped); dynamic load rebalance remains.
2943
2944- Cross-worker entity transfers (shipped).
2945
2946- Border ghosts for occupancy/pathfinding (shipped); remote combat actions remain.
2947
2948- Gateway subscriptions spanning multiple workers (shipped).
2949
2950- Load metrics and neighbour-aware region balancing remain.
2951
2952## Phase 4 — World depth, social systems and economy
2953
2954- Persistent named NPCs and other persistent mob archetypes.
2955
2956- Spawner persistent-instance index and duplicate prevention.
2957
2958- Optional durable gameplay chunk overrides, written only on unload.
2959
2960- Hierarchical pathfinding if long-distance autonomous travel needs it.
2961
2962- Persistent player groups and invitations.
2963
2964- Carrier-pigeon cargo transit: free dispatch, money or one item stack,
2965 player or nearest-bank destinations, including offline/full-inventory
2966 fallback to the recipient vault.
2967
2968- Shared unlimited **character** bank near the marketplace, account
2969 inheritance tab on character delete, blank cheques filled to 99, reserved
2970 filled cheques, in-person redemption and pigeon-to-bank cheque transfers.
2971
2972- Central marketplace, escrow, deterministic order matching, pigeon-to-bank
2973 settlement for the older counterparty, and a per-item last-sale record for
2974 shop/tooltip adaptation.
2975
2976- NPC shops that sell `npcShopAllowed` stock at seed value lerped toward the
2977 last player-market price over `shopPriceLerpDuration`, with a hidden per-shop discount.
2978
2979- Item inspection: name, description, origin (crafter or shop NPC) and
2980 undiscounted current value, refreshed at most once per minute.
2981
2982- Player crafting/gathering economy rules and shop-content validation.
2983
2984- Broader skill catalogue, progression curves and skill-gated content.
2985
2986## Phase 5 — Player scripting
2987
2988- Custom language grammar/compiler/interpreter.
2989
2990- ScriptController and event API.
2991
2992- CPU/memory/query quotas and sandboxing.
2993
2994- Online scripted control mode.
2995
2996- Offline retained player entities with expiry and ChunkLoader
2997 behaviour.
2998
2999- Persisted/restart-safe script state.
3000
3001# 29. Core invariants
3002
3003| **Invariant** | **Rule** |
3004|------------------------|--------------------------------------------------------------------------------------------------------|
3005| Server authority | Clients send intent; the server computes and owns outcomes. |
3006| Region ownership | Exactly one simulation worker authoritatively owns a region. |
3007| Entity ownership | Exactly one worker authoritatively owns an entity. |
3008| Remote mutation | Workers never directly mutate remote authoritative state. |
3009| Spatial separation | Region residency, chunk simulation and client visibility remain distinct. |
3010| Persistence separation | Persistent and ChunkLoader are independent entity traits. |
3011| Chunk persistence | Normal dirty chunk state is written on unload, not periodically. |
3012| World authoring | Editor changes create pending authored state; the running server stays pinned to its startup revision. Each chunk save appends an admin-attributed diff changelog. |
3013| Restart path | Planned restart force-unloads the world and reuses the ordinary unload save path. |
3014| Control | Human and future scripted control both emit validated action commands. |
3015| Deployment | The game exits gracefully; systemd relaunches it and only pulls/builds when an intentional deployment manifest requests it. |
3016| Client architecture | FrameworkV3 is a git submodule under `client/frameworkv3`, built before game client code; backend ECS internals do not become the client object model. |
3017| Sprites | World sprites may be any size. Pivot is horizontal centre and 8px from the sprite bottom, on the tile centre. Ground/block types load visual states from a per-type folder (first alphabetical PNG is default). Sheets use `frames`, `framesPerRow`, `animationSpeed`. Blocks and mobiles Y-sort north-behind-south. |
3018| Appearance | Visible gear is layered 16×16 overlays on the mob; recolourable channels (such as metal) use material colour without duplicate art sets. Nearby clients receive appearance layers, not another player's inventory. |
3019| Play camera | The play viewport is centered on the local player. Only the admin world editor uses a free chunk camera. |
3020| Movement | All ground mobiles share a global walk/run cadence from world settings; the server commits integer tiles; clients lerp for presentation only. |
3021| World time | World calendar time is server time minus 1200 years. Night darkens tiles the baked light map cannot reach. |
3022| World settings | Tick timers and global constants (including night darkness) are authored in the editor modal, applied immediately on save, and recorded in a settings edit log. Chunk map data remains revision-pinned. |
3023| Baked light | Static light reach is raycast through passable tiles on chunk save, may cross chunks, and is not recomputed every tick. |
3024| Ground items | Player drops last `groundItemDespawnDuration` (default 10 minutes), block nobody, and are picked up only by a player standing on that tile. |
3025| Shop prices | NPC shop prices lerp from the captured pre-sale value toward the last player-market unit price over `shopPriceLerpDuration` (default one hour), times a hidden per-shop discount. |
3026| Proximity speech | Distant clients never receive unobscured plaintext that game rules say they cannot understand. |
3027| Courier cargo | Pigeons carry money or one item stack, never a chat packet; cargo is durable in transit and remains delayed. |
3028| Inventory | A player has 32 slots; a stack occupies one slot; the client never asserts inventory, wallet or vault results. |
3029| Shared bank | Every bank reads the same **character** vault; pigeon deposits become available only after arrival at the nearest bank. |
3030| Closed chunks | Closed or never-edited chunks are visible but not enterable; never-edited terrain is default grass with no blocks. |
3031| Accounts | Login is auth.timfalken.com (or `admin-<n>` stub). Characters belong to an account; one may be in the world at a time. |
3032| Names | Surnames are globally unique per account; first+last is unique per account; names free only after permanent delete. |
3033| Inheritance | Deleted characters dump inventory, equipment, wallet and vault into an account inheritance tab other characters can claim. |
3034| Cheques | Filling a cheque reserves vault goods; the bearer item is the claim; destruction without redemption releases the reservation. |
3035| Marketplace escrow | Every open order is fully backed by escrow and matching/settlement is atomic and deterministic. |
3036| Combat | Melee requires an 8-neighbour tile; ranged/spell range comes from the item or spell; hit uses the weapon skill; damage uses Strength, Dexterity or Mind. |
3037| Progression | Players have no classes; non-combat actions award XP to one governing skill; a successful attack splits XP equally between hit and damage skills. |
3038
3039# 30. Important edge cases to preserve during implementation
3040
3041- A ChunkLoader crossing a region boundary can change
3042 residency/simulation references and worker ownership in the same tick;
3043 ordering must avoid temporary double ownership.
3044
3045- A player at a worker boundary may receive visible chunks from multiple
3046 workers without moving ownership solely for rendering.
3047
3048- A planned restart must ignore normal ChunkLoader retention when
3049 forcing the world to unload.
3050
3051- A world-editor save must never cause newly loaded chunks in the
3052 current process to use the pending revision. It must append a changelog
3053 record naming the admin, timestamp and tile diffs.
3054
3055- Pathfinding and player movement must reject tiles in closed or
3056 never-edited chunks even when those chunks are in the 3×3 view.
3057
3058- Two accounts must not claim the same surname. One account may reuse its
3059 surname; first+last must stay unique on that account until permanent
3060 delete.
3061
3062- Marking a character for deletion must not free the name or move items
3063 until the delay elapses. Cancelling must restore playability.
3064
3065- Character deletion must notify the account email (or log, on stub auth).
3066 Permanent delete must void that character's issued cheques, then move
3067 inventory, equipment, wallet and vault into the account inheritance tab.
3068
3069- Saving a chunk must rebake that chunk's light map and any neighbour
3070 chunks within max light range, using passable-tile raycasts. Light from
3071 a source in chunk A may appear in chunk B.
3072
3073- A mob definition must not carry its own walk/run speed; gait only
3074 selects every-other vs every movement tick on the global cadence.
3075
3076- World-settings saves must not apply to the live process; they wait for
3077 the same pending-revision restart as chunk edits.
3078
3079- Night shading must not light a tile the baked mask marks unreachable,
3080 even if a torch is nearby through a wall.
3081
3082- Oversized block and mob sprites must Y-sort so objects higher on the
3083 screen draw behind objects lower on the screen. Closed-chunk edges
3084 facing an open chunk must show a red border in the client.
3085
3086- Equipping must not leave two items in the same equipment slot. Unequip
3087 into a full inventory must fail and leave the item worn.
3088
3089- Nearby clients must not receive another player's inventory in order to
3090 draw their armour; appearance layers and material ids are sufficient.
3091
3092- A client build without `client/frameworkv3` initialized must fail rather
3093 than silently using some other FrameworkV3 install.
3094
3095- Client interpolation of movement must not be treated as authority. Combat
3096 range and pickup use the server tile, not the lerped draw position.
3097
3098- The play camera must remain centered on the local player. Zoom must not
3099 expand the subscribed chunk set.
3100
3101- A persistent mob spawned by a spawner must not be duplicated merely
3102 because it moved out of the spawner’s loaded area.
3103
3104- A non-persistent mob disappears when its chunk is actually unloaded,
3105 not merely when it becomes dormant.
3106
3107- If a persistent ChunkLoader or offline scripted player exists after
3108 restart, startup must discover it from an index without loading the
3109 entire world.
3110
3111- A pending code update followed by an unrelated Node.js crash must
3112 restart the currently deployed commit rather than deploying early.
3113
3114- Negative coordinates, daylight-saving midnight calculation, duplicate
3115 transfer messages and failed deployment migrations should all have
3116 explicit tests.
3117
3118- Proximity chat degradation must happen before plaintext reaches an unauthorised
3119 distant client; rendering-only obfuscation is not sufficient.
3120
3121- Carrier-pigeon deliveries must survive restarts and recipient logout without
3122 requiring every traversed chunk to remain stimulated.
3123
3124- A pigeon carrying an item to a player whose inventory cannot accept it must
3125 not destroy the cargo; it deposits into that player's vault via the nearest
3126 bank.
3127
3128- Two concurrent bank withdrawals, cheque fills or pigeon-arrival deposits must
3129 not spend the same vault goods twice.
3130
3131- Filling two cheques against the same vault stack must reserve disjoint
3132 quantities or reject the second fill.
3133
3134- A filled cheque that expires on the ground must release its reservation and
3135 must not remain redeemable.
3136
3137- A player-dropped ground item must not block movement, must not keep its chunk
3138 loaded, and must still be present after a chunk unload/reload if `expiresAt`
3139 has not passed.
3140
3141- Pickup of a ground item from a tile the player is not standing on must fail.
3142
3143- Requesting blank cheques must never raise the player's carried blank-cheque
3144 count above 99.
3145
3146- A marketplace match must atomically consume both escrows exactly once, even if
3147 two compatible orders arrive concurrently.
3148
3149- A matching market order from an online player may settle immediately for that
3150 player while the older/offline counterparty's delivery remains durable.
3151
3152- Skill XP is awarded only after authoritative action resolution, never directly
3153 from a client-reported result. A successful player attack splits that XP;
3154 a miss awards none.
3155
3156- A melee attack from the target's own tile, or from Chebyshev distance greater
3157 than 1, must fail. A ranged or spell attack beyond that item or spell's
3158 `rangeTiles` must fail.
3159
3160- A new player-market sale must capture the then-current undiscounted lerp
3161 value as `priceFrom` so shop and tooltip prices do not jump back to seed.
3162
3163- Two shop NPCs may charge different prices for the same item at the same
3164 instant because each applies its own hidden discount to the same lerp.
3165
3166- Item tooltip value must not be recomputed every tick; a one-minute refresh
3167 is sufficient. Purchase price is still evaluated at the moment of buy.
3168
3169# 31. Decisions through version 0.12
3170
3171- Chunk persistence is unload-driven rather than periodic.
3172
3173- The authored tile model has separate visual ground and functional
3174 block layers.
3175
3176- Mobile actors remain ECS entities and are not authored as painted tile
3177 contents.
3178
3179- Spawner blocks are editor-placeable and configurable per instance;
3180 persistence belongs to the spawned mob type.
3181
3182- world.sqlite is an authored, revisioned world source; state.sqlite
3183 holds runtime durable state.
3184
3185- Editor changes are staged for activation on restart instead of
3186 hot-patching the running world.
3187
3188- Code/world changes schedule a player-visible midnight restart; admins
3189 can trigger the same graceful pipeline immediately.
3190
3191- Git pull/build/relaunch belongs to `systemd` supervision after the
3192 game process has safely exited.
3193
3194- Deployment is manifest-driven: crash recovery restarts the currently
3195 checked-out commit, while only an intentional deployment restart may
3196 fast-forward `master`.
3197
3198- Future player scripting is modelled as an alternative controller
3199 producing normal server action commands.
3200
3201- Offline scripted players may remain in-world as ChunkLoaders until
3202 death or expiry and must survive planned restarts through persistence.
3203
3204- The player client is built on FrameworkV3, included as the git submodule
3205 `client/frameworkv3` and built first so this game's client code can layer on
3206 top. The client does not need an ECS and consumes protocol state
3207 independently of backend ECS storage. The Node.js server does not import
3208 FrameworkV3.
3209
3210- World sprites may be any pixel size. Each is placed with a pivot at
3211 horizontal centre and 8 pixels from the sprite bottom, on the tile
3212 centre. Blocks and mobiles are Y-sorted. The player may zoom the whole
3213 viewport within configured bounds; sprites are not scaled individually.
3214
3215- Visible equipment is drawn as extra 16×16 layers on the mob, including
3216 players. Worn items occupy equipment slots, not the 32 inventory slots.
3217 Nearby clients replicate appearance layers only, never another player's
3218 inventory.
3219
3220- Recolourable gear (metal armour) shares one overlay sprite and a 16×16
3221 channel mask. Material definitions supply the metal colour; luminance of
3222 the overlay is preserved. Iron and steel plate are different items with
3223 the same art and different `materialId`.
3224
3225- The play camera is always centered on the local player. The admin world
3226 editor is the only exception, and it frames one chunk at a time.
3227
3228- Authoritative movement is a tile-to-tile jump on a **global** cadence:
3229 default walk 2 tiles/s, run double. Walk steps every other movement tick;
3230 run steps every movement tick. Mobs do not set their own speed. Clients
3231 lerp for visuals only and never send interpolated positions.
3232
3233- Admins edit global tick timers and constants in a world-settings modal.
3234 Saving applies those values immediately to the live process and appends
3235 a settings changelog. Chunk map saves still wait on the pending world
3236 revision.
3237
3238- World calendar time is server time minus 1200 years, same IANA zone as
3239 midnight restarts. At night the client darkens tiles the baked light map
3240 cannot reach.
3241
3242- Static light is baked on chunk save by raycast through passable tiles,
3243 including across chunk borders. The editor has a night-to-day slider for
3244 preview only.
3245
3246- Each world-editor chunk save stores who edited it, when, and a bullet
3247 diff of ground changes, block placements, block replacements and block
3248 removals at world tile coordinates.
3249
3250- Default speech is proximity-based and becomes less legible with distance.
3251 Long-distance exchange is physical: a pigeon carries money or one item stack.
3252 A letter is paper with player-written text, not a separate mail record.
3253
3254- Permanent player groups are social/addressing structures and do not create an
3255 instant global chat channel.
3256
3257- Carrier-pigeon transit is persistent but does not automatically keep every
3258 traversed chunk simulated. Whenever a pigeon passes through a chunk that is
3259 already simulating, it materialises as an ECS `Mob` and is visible to any
3260 nearby client whose normal chunk subscription includes it, even if that client
3261 is unrelated to the delivery. Unrelated clients do not receive cargo contents.
3262
3263- A player has a 32-slot inventory. Stackable items occupy one slot. Currency is
3264 a numeric wallet/vault balance, not an inventory item.
3265
3266- Player-dropped items lie on the tile for `groundItemDespawnDuration`
3267 (default 10 minutes), block nobody, and may be picked up by anyone standing
3268 on that tile. They survive unload until expiry via timestamps.
3269
3270- The bank near the marketplace holds an unlimited **character** vault.
3271 Later banks are linked to the same vault. Pigeons may deposit money or one
3272 stack into the sender's vault after arriving at the nearest bank. An
3273 account-level inheritance tab receives a deleted character's goods.
3274
3275- Blank cheques are issued at a bank up to a carried total of 99. Filling a
3276 cheque reserves a vault item quantity. The filled cheque is a bearer item.
3277 In-person redemption withdraws into the bearer's inventory. Sending the cheque
3278 to the bank by pigeon transfers the reserved goods into the pigeon's sender's
3279 vault.
3280
3281- The central marketplace hides individual live sell listings and matches durable
3282 escrowed buy/sell orders at the midpoint of compatible bid/ask limits.
3283 Quantities are item stacks.
3284
3285- The newest matching market participant receives the trade result locally; the
3286 older counterparty receives theirs by pigeon into their bank.
3287
3288- NPC shops remain restricted to `npcShopAllowed` basic ingredients. They sell
3289 to players at
3290 `lerp(priceFrom, lastTradePrice, min(1, (now - lastTradeAt) / shopPriceLerpDuration))`
3291 times a hidden per-shop discount. With no player-market sale yet, the
3292 undiscounted value is `seedValue`. Tooltips use the same lerp without the
3293 discount and refresh at most once per minute.
3294
3295- Hovering an item shows name, description, origin (crafter, or shop NPC name
3296 if bought there) and current undiscounted value.
3297
3298- All combatants can attack. Melee requires standing on one of the eight
3299 neighbouring tiles. Ranged attacks and spells use the item's or spell's
3300 range. The hit roll uses the weapon skill; damage uses Strength (melee),
3301 Dexterity (ranged) or Mind (magic). Successful player-attack XP is split
3302 equally between those two skills.
3303
3304- Player progression is skill-based rather than class-based. Non-combat
3305 actions award XP to one governing skill; combat hits split XP as above.
3306
3307- Never-edited chunks are default grass, no blocks, and **closed**. The
3308 editor opens or closes each chunk. Closed chunks are visible but not
3309 enterable.
3310
3311- Accounts authenticate at auth.timfalken.com. Until that service is up,
3312 each connection is stub `admin-<n>` (n = connected client count including
3313 this one) and is treated as admin.
3314
3315- An account has unlimited characters and plays one at a time. Creation
3316 takes first name (not globally unique), last name (globally unique to the
3317 account, reusable on that account's other characters), and male/female.
3318 first+last must be unique for that account. This setup may change later.
3319
3320- Character deletion is a 24-hour (configurable) delay with email notify
3321 and cancel. Permanent delete frees names and moves inventory, equipment,
3322 wallet and vault to the account inheritance tab, which any of that
3323 player's characters can claim into their own vault.
3324
3325# 32. Open design decisions for later iterations
3326
3327These do not block the initial implementation, but should eventually be
3328specified explicitly:
3329
3330- Whether multiple mobile entities may occupy one tile and, if so, which
3331 categories can overlap.
3332
3333- Whether player movement is four-direction only or also supports
3334 diagonals. Combat melee adjacency already includes diagonals.
3335
3336- Exact hit-chance and damage curves, attack intervals/cooldowns, whether
3337 Defence modifies incoming hit chance or damage, and ranged/spell
3338 line-of-sight or obstruction rules.
3339
3340- Deterministic rounding when shop discount or lerp produces a fractional
3341 currency amount.
3342
3343- Exact equipment slot list, per-slot draw order exceptions (cloaks,
3344 two-handed weapons), and whether worn overlays have facing frames to
3345 match the mob.
3346
3347- Additional recolour channels beyond metal (for example cloth dyes) and
3348 the exact luminance-preserving remap function.
3349
3350- Exact camera zoom minimum, maximum and whether zoom is restricted to
3351 integer steps.
3352
3353- Exact night ambient curve (how dark, dusk length) and whether baked light
3354 stores a boolean reach mask or a distance/falloff value per tile.
3355
3356- Whether opening a door at runtime should rebake or ignore static light.
3357
3358- Exact simulation tick rate stays a world setting; lower-frequency AI and
3359 spawner cadences can still be tuned independently.
3360
3361- Exact world/chunk binary serialisation format and schema/version
3362 migration strategy.
3363
3364- Whether gameplay can permanently modify ground/block tiles in the
3365 initial release.
3366
3367- Spawner timing rules, spawn-point restrictions and behaviour when
3368 persistent spawned mobs travel very far away.
3369
3370- World-editor undo/redo and rollback UI. The per-chunk changelog is an audit
3371 log, not by itself an undo stack.
3372
3373- Exact restart warning intervals and whether admins can
3374 cancel/reschedule a planned restart.
3375
3376- Worker rebalance thresholds and whether regions may migrate while
3377 players are actively crossing their boundaries.
3378
3379- Future scripting language syntax, event model and resource quotas.
3380
3381- Group naming/roles, membership limits and whether group-wide letter sending
3382 is offered as an addressing convenience that still dispatches one pigeon and
3383 consumes one paper/letter per recipient.
3384
3385- Whether pigeons can eventually be intercepted, killed or redirected in transit.
3386
3387- Marketplace partial fills, cancellation rules, fees/taxes (if any),
3388 tie-breaking details and midpoint rounding for indivisible currency.
3389
3390- Whether market price history or aggregate statistics are visible despite live
3391 order listings remaining hidden.
3392
3393- Initial skill catalogue, XP curves, level caps, action XP formulas and the
3394 remaining interpretation of skills such as Defence.
3395
3396- Maximum letter body length and whether writing paper requires a desk or can be
3397 done from inventory anywhere.
3398
3399- Exact item catalogue, which items stack, per-item `maxStackSize` exceptions,
3400 harvest interactions and ground-item spawner parameters.
3401
3402- Whether death drops inventory, and whether dropped unique items other than
3403 cheques have destruction side-effects.
3404
3405- Whether the issuer can void a filled cheque without the bearer item being
3406 destroyed, and whether cheques can ever represent currency rather than items.
3407
3408- Whether a short dispatch interval is needed so many pigeons cannot leave in a
3409 single tick, even though sending remains free.
3410
3411- New-character spawn location (must be an open chunk) and name length /
3412 allowed-character rules.
3413
3414- Later changes to character creation beyond first name, last name and sex.
3415
3416# 33. Architectural summary
3417
3418ECS → what an entity is and what systems can act on it
3419Chunk → tile data, spatial lookup, simulation and client subscription
3420Region → residency and simulation-worker ownership
3421Coordinator→ where regions execute
3422Gateway → stable client connections, auth, character select, and command/update routing
3423world.sqlite→ authored versioned ground/block/spawner/light/settings world; unedited chunks are closed grass
3424state.sqlite→ accounts, characters, friends, vaults, inheritance, and other durable live-game state
3425systemd → process supervision and relaunch
3426Deployment hook → conditional Git update/build only for intentional deployment restarts
3427Controller → manual client input today; sandboxed player scripts later
3428FrameworkV3 → git submodule at `client/frameworkv3`; built first; game client code layers on top
3429Sprites → any size; pivot at horizontal centre, 8px from bottom; Y-sort blocks/mobs
3430Equipment → layered 16×16 overlays on mobs; metal armour shares art and recolours by material
3431Camera → play view centered on the local player; bounded zoom; editor is chunk-framed
3432Movement → global walk/run cadence (default 2 tiles/s walk, run double); server tile steps; client visual lerp
3433World time → server clock minus 1200 years; night darkens unlit tiles
3434Light → baked passable-tile raycast on editor save; shines across chunks
3435World settings → admin modal for tick timers and global constants; live apply
3436Inventory → 32 slots; stacks occupy one slot; letters are written paper items
3437Bank → per-character vault; account inheritance tab on character delete
3438Auth → auth.timfalken.com, stub admin-<n> until live; unlimited characters, one in world
3439Chunks → editor open/closed; default grass and closed until painted
3440Ground items → non-blocking, 10-minute player drops, pickup only while standing on the tile
3441Communication service → proximity speech
3442CourierService → pigeons carrying money or one item stack through durable transit
3443BankService → shared unlimited vaults, cheque reservations and redemption
3444MarketService → durable escrowed order book, matching, last-sale index and pigeon-to-bank settlement
3445Shop NPCs → sell allowed stock; price lerps toward last player-market sale over shopPriceLerpDuration, times a hidden discount
3446Combat → 8-tile melee, item/spell ranged range; hit skill roll; Strength / Dexterity / Mind damage; equal XP split
3447Skills → classless progression; non-combat XP to one skill; attack XP split hit/damage
3448
3449
3450# 34. Version history
3451
3452## 0.19
3453
3454- Playable item basis: 32-slot inventory, equipment overlays, carried coins,
3455 ground drops (10-minute player drops, pickup on the tile), bank vaults,
3456 and account inheritance on character delete. Spawner and bank blocks can
3457 be painted in the editor; spawners produce placeholder deer up to
3458 `maxAlive`. Missing art is temporary 16×16 PNGs under `client/assets/`
3459 so real sprites can drop in later by replacing those files.
3460
3461## 0.18
3462
3463- Server ECS uses compact worker-local `EntityHandle`s (recycled free list)
3464 alongside global `EntityId`s for storage, networking and transfer. `Path`
3465 is a separate component from `Movement`; players carry `NetworkIdentity`
3466 instead of putting `sessionId` on `character`. Nearby clients get
3467 `ENTITY_SPAWN` / compact `ENTITY_MOVE` (tile + gait) / `ENTITY_DESPAWN`
3468 rather than appearance-heavy moves or extra snapshots.
3469
3470## 0.17
3471
3472- Region workers own ECS worlds behind a clone-on-boundary protocol
3473 (optional `worker_threads`). ChunkLoader reference counts keep 3×3
3474 chunks simulating and 3×3 regions resident; other resident chunks stay
3475 dormant. Regions unload after the grace period and persist flagged
3476 entities. Crossing a foreign region transfers the only authoritative
3477 copy; ghosts cover border occupancy; client snapshots may span workers.
3478
3479## 0.16
3480
3481- Proximity chat: Enter opens a bottom input (max `chatMaxCharacters`,
3482 default 100). Enter sends a trimmed line; the speaker always sees their
3483 own text. Other players get a server-obscured bubble (full until 8
3484 tiles, linear to silent at 16 tiles). At 0% readability no bubble is
3485 sent. Walk/run `R` is ignored while the chat line is open.
3486
3487## 0.15
3488
3489- Hovering another player shows their first name. Clicking them opens an
3490 inspect modal (first + last name) to send a friend request. Requests
3491 must be accepted; removing a friend removes them on both sides. The
3492 friends list is the later pigeon address book.
3493
3494## 0.14
3495
3496- Ground and block types load visual states from per-type sprite folders
3497 (first alphabetical PNG is the default). Sprite definitions include
3498 `frames`, `framesPerRow` and `animationSpeed`. The editor previews the
3499 selected tool on hover and cycles states with the mouse wheel.
3500 Gameplay may set a named visual state (for example a door).
3501
3502## 0.13
3503
3504- World settings are live: an admin modal with categories, dirty-field
3505 highlighting, and a settings edit log. Save applies immediately
3506 (including `nightDarkness`) rather than waiting on a map revision.
3507
3508## 0.12
3509
3510- Chunks are open or closed in the world editor. Closed chunks stay visible
3511 but cannot be entered. Never-edited chunks are default grass with no
3512 blocks and are closed.
3513- Login uses auth.timfalken.com; until that is live, connections are stub
3514 `admin-<n>` (connected-client count including this one) and are admins.
3515- Accounts have unlimited characters, one in the world at a time. Creation
3516 is first name, unique account-owned last name, and male/female.
3517- Character deletion waits 24 hours with email and cancel. Permanent delete
3518 frees names and moves goods to an account inheritance bank tab.
3519
3520## 0.11
3521
3522- Made walk/run a global cadence from world settings (default 2 tiles/s
3523 walk, run double): walk steps every other movement tick, run every tick.
3524 Mob definitions do not set move speed.
3525- Added an admin world-settings modal for tick timers and global constants
3526 (shop lerp duration, drop lifetime, simulation tick, and the same class
3527 of values). Settings ride the pending world revision.
3528- World calendar time is server time minus 1200 years.
3529- Baked static lighting by passable-tile raycast on chunk save, including
3530 across chunk borders. Clients darken unreachable tiles at night. The
3531 editor has a night-to-day preview slider.
3532
3533## 0.10
3534
3535- Drew visible equipment as 16×16 overlay layers on mobs (including players),
3536 with worn items in equipment slots rather than the 32-slot inventory.
3537- Replicated compact appearance layers to nearby clients instead of another
3538 player's inventory.
3539- Recolourable metal armour shares one overlay plus a 16×16 channel mask;
3540 material definitions supply the metal colour while preserving shading.
3541
3542## 0.9
3543
3544- Vendored FrameworkV3 as the git submodule `client/frameworkv3`. The game
3545 client builds that library first and implements game-specific code on top
3546 of it. The Node.js server does not import the submodule.
3547
3548## 0.8
3549
3550- Required all world sprites (tiles, blocks, mobs, items) to be 16×16 pixels,
3551 rejected at load, with a CI unit test that reports and fails on any other
3552 size. Sprites are not individually scaled; the player may zoom the viewport
3553 within configured bounds.
3554- Locked the play camera to the local player. The admin world editor remains
3555 the only non-player-centered view.
3556- Made authoritative movement integer tile-to-tile steps. Clients lerp
3557 mobiles for presentation only.
3558- Added a per-chunk world-editor changelog: admin, timestamp, and bullet
3559 diffs for ground changes, block place/change/remove.
3560
3561## 0.7
3562
3563- Added combat for all mobs including players: melee from any of the eight
3564 neighbouring tiles, ranged and spells from the item or spell range.
3565- Hit rolls use the weapon skill (Swordfighting, Axefighting, Archery, Magic,
3566 and so on). Damage uses Strength, Dexterity or Mind according to melee,
3567 ranged or magic.
3568- Successful player-attack XP is split equally between the hit skill and the
3569 damage skill. Ordinary mobs use archetype skill levels and do not earn XP.
3570- Shop NPCs sell items at seed value adapted to the last player-market unit
3571 price, lerping over one hour, multiplied by a hidden per-shop discount.
3572- Only the latest player-market sale per item is stored (price, timestamp, and
3573 lerp origin). No historical series.
3574- Item hover shows name, description, origin (crafter or shop NPC) and the
3575 undiscounted current value, refreshed at most once per minute.
3576
3577## 0.6
3578
3579- Added a 32-slot player inventory, stackable items, carried currency as a
3580 numeric wallet, and unique-instance items for letters and filled cheques.
3581- Redefined letters as paper items with player-written text rather than a
3582 separate mail record.
3583- Redefined carrier pigeons as free couriers that carry money or one item
3584 stack to a player or to the nearest bank.
3585- Added a shared unlimited bank near the marketplace, blank cheques filled to
3586 99, vault reservations on fill, in-person redemption and pigeon-to-bank
3587 cheque transfers between vaults.
3588- Added player-dropped ground items: 10-minute lifetime, non-blocking, pickup
3589 only while standing on the tile, timestamp persistence across unload.
3590- Specified later ground-item spawners and harvesting as content that reuses
3591 this item model.
3592- Routed offline/full-inventory pigeon delivery and older-side market
3593 settlement into the recipient's shared bank vault.
3594
3595## 0.5
3596
3597- Made carrier pigeons shared world-visible entities whenever their route crosses an already-simulating chunk.
3598- Unrelated nearby players can see pigeons in their normal 3x3 chunk view; pigeons do not keep chunks loaded themselves.
3599- Added deterministic materialisation/dematerialisation between durable abstract transit and worker-owned ECS pigeon entities.
3600
3601## 0.4
3602
3603- Added FrameworkV3 as the shared player-client foundation while keeping backend ECS internal to the server.
3604- Added server-side proximity chat degradation, persistent player groups and durable carrier-pigeon letters.
3605- Added scalable courier transit that can cross dormant world space without forcing normal chunk simulation.
3606- Added the central marketplace, escrowed hidden order book, midpoint pricing and pigeon-based remote settlement.
3607- Added the player-driven item-source philosophy and restrictions on NPC shop inventories.
3608- Added classless, skill-based player progression and authoritative skill XP.
3609
3610## 0.3
3611
3612- Converted the living design document to Markdown as the canonical format.
3613- Defined `systemd` as the production process supervisor.
3614- Added a conditional, manifest-driven deployment path so crashes do not deploy pending code early.
3615- Added a concrete example systemd service shape and clarified privilege separation.
3616
3617## 0.2
3618
3619- Added unload-driven chunk persistence, authored world revisions, the admin world editor, spawner blocks, graceful scheduled restarts and future player scripting hooks.