BlueGit

timfa questward

Add the living tile MMO technical design (v0.12).

Co-authored-by: Cursor <cursoragent@cursor.com>

timfa Tim Falken · pushed by timfa

Authored 2026-08-24 · 2 months ago

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