Files
gamedev-the-steward/docs/PROJECT_CONTEXT.md
T

27 KiB
Raw Blame History

The Steward — Project Context

Agent-facing context for understanding the project quickly.

Snapshot basis: repository state after commit 0900022, July 2026. Treat the code as the source of truth when this document and the implementation differ.

See the documentation map for the authority and scope of each plan.

Quick orientation

The Steward is currently a small Godot prototype for an embodied village simulation. Its larger purpose is to become a learning laboratory for a performant, large-scale NPC simulation that can later power a systemic open-world RPG.

The current village is not intended to be the final game's scale. It is a controlled environment in which to learn and validate:

  • NPC needs and decision-making;
  • professions, work, inventories, and economic dependencies;
  • actions, consequences, and world events;
  • relationships, memories, rumours, and persistent history;
  • emergent situations that can be surfaced as quests;
  • simulation level of detail for a much larger population;
  • readable world presentation and satisfying embodied play.

The desired game is not an omniscient city builder and not primarily a scripted quest RPG. The player exists physically inside the simulated society.

North-star vision

A systemic open-world RPG set around a city inspired by Jajce, Bosnia and Herzegovina, and its surrounding villages. Every important NPC participates in a simulated society, forms relationships, remembers events, and can affect history. The player can remain an ordinary citizen, pursue a profession, become a trader, criminal, warrior, or companion leader, command armies, and eventually lead a faction.

The world should generate situations. Quests should primarily communicate, frame, and track those situations rather than manufacture disconnected content.

Example:

  1. A harvest fails or a trade route becomes unsafe.
  2. Food scarcity raises pressure on households and professions.
  3. An NPC steals, migrates, changes work, joins a criminal group, or asks a relative for help.
  4. Witnesses form memories and spread partial information.
  5. Relationships, prices, safety, and faction attitudes change.
  6. The player learns about the situation through observation, conversation, rumours, employment, or authority.
  7. Any intervention changes the same world state that produced the problem.

The quest is therefore a view onto the simulation, not a parallel scripted reality.

Product pillars

1. Simulated lives

NPCs should be people rather than production modifiers. Their needs, professions, possessions, schedules, abilities, ambitions, and circumstances drive their choices.

2. Persistent history

Important actions create structured events. Events can become memories, knowledge, rumours, relationships, reputations, grudges, obligations, and political consequences.

3. Emergent narrative

Authored content should provide rules, cultures, locations, characters, archetypes, and exceptional story beats. Ordinary quests and conflicts should preferably emerge from unresolved world conditions.

4. Embodied freedom

The player walks through the same spaces, uses the same resources, and participates in the same institutions as NPCs. They can play at different social scales without being forced toward rulership.

5. Legible autonomy

Complexity is valuable only when players can understand its consequences. The game should expose why an NPC chose an action and show resources moving through the world.

6. Small stories inside a large world

The eventual map may be large, but emotional attachment comes from recognizable people and local consequences. Simulation scale must not turn everyone into an anonymous number.

7. Enjoyable action

Movement and combat should be satisfying independently of the simulation. Companions and armies should offer expressive, enjoyable control rather than only statistical resolution.

8. A recognizable setting

The core region is inspired by Jajce: dramatic elevation, a fortified urban center, rivers, a waterfall, wooded slopes, lakes, watermills, roads, farms, and surrounding villages. This is an inspiration rather than a requirement for a literal historical reconstruction.

9. Cozy presentation with real stakes

The presentation should feel warm, painterly, pastoral, and inviting while the simulation remains capable of scarcity, conflict, death, political ambition, and social change.

Build-in-public goals

Visual appeal and watchability are prototype requirements, not final polish. Each simulation feature should have a visible expression:

Simulation state Visible expression
Hunger Looking for food, checking storage, eating, asking, stealing, or weakening
Profession Recognizable tools, clothing, workplace, route, and animation
Task choice Purposeful movement plus optional task/thought icon
Production Items visibly gathered, carried, stored, processed, and consumed
Relationship Greeting, helping, arguing, avoiding, mourning, or celebrating
World event Visible consequences and a concise event/history feed
Settlement change Construction, depletion, prosperity, damage, migration, or recovery

Development clips should communicate cause and effect without requiring viewers to read console logs. A cinematic/debug toggle should eventually allow the same scenario to be shown both beautifully and analytically.

Visual direction

The target is an original stylized look characterized by:

  • painterly natural colors and soft, warm lighting;
  • readable, exaggerated terrain and building silhouettes;
  • lush vegetation with restrained environmental motion;
  • expressive, animation-friendly characters;
  • appealing water, mist, smoke, weather, and seasonal variation;
  • cozy settlements contrasted with a world capable of hardship;
  • a clear elevated third-person view that makes NPC activity readable.

Avoid generic high-fantasy spectacle and avoid treating visual style as a reason to hide the underlying simulation.

Initial environment composition

The first public-facing environment should be a compressed simulation garden, not the complete region:

  • a fortress or fortified landmark on an upper ridge;
  • a small settlement descending toward water;
  • a river, bridge, and waterfall or strong vertical water feature;
  • a mill channel and a small cluster of watermills;
  • farm terraces and a wooded work area;
  • a trade road and distant silhouettes that imply a larger world.

Terrain3D should own broad landforms, ground surfaces, distant landscape, and large-scale vegetation placement. Roads, river surfaces, waterfalls, cliffs that require overhangs, bridges, walls, buildings, and other authored landmarks should use dedicated meshes or appropriate spline/modular tooling.

Core player loop

The intended loop is:

  1. Observe people, places, stores, and local problems.
  2. Understand needs, causes, relationships, and competing priorities.
  3. Influence people through work, trade, conversation, policy, reputation, leadership, or force.
  4. Act personally through movement, interaction, production, exploration, and combat.
  5. Witness consequences in the same people and systems.
  6. Adapt to new opportunities and problems created by those consequences.

The current prototype implements a very early version of observe, autonomous task choice, physical travel, work completion, resource change, and direct player assistance. NPC gather_food and gather_wood tasks now use finite world ResourceNode instances (berry bushes and trees) rather than abstract zone markers. The zone markers remain only for player interaction and non-resource tasks. The migration is documented in the ResourceNode plan.

Current technology

  • Engine: Godot 4.7 project configuration
  • Renderer feature: Forward Plus
  • Language: GDScript (odig analysis with warnings treated as errors)
  • Main scene: res://main.tscn
  • Terrain: Terrain3D 1.0.2 is installed and enabled
  • Terrain compatibility floor: Godot 4.4 according to the bundled extension
  • Version control: Git
  • Primary branch: main
  • Commit convention: Conventional Commits

Terrain3D includes binaries, source, editor tooling, examples, and a demo/ directory. Most files under addons/terrain_3d/ and demo/ are third-party plugin content, not game architecture.

Current playable state

World and player

  • main.tscn contains a flat approximately 30×30 prototype ground.
  • The player is a CharacterBody3D represented by placeholder primitive geometry.
  • WASD movement is camera-relative.
  • The elevated third-person camera rotates with the mouse and uses smoothed follow/focus behavior.
  • Pressing E near a berry bush or tree extracts its configured yield into the village through the same ResourceNode contract used by NPCs.
  • Guard, study, and food interactions still use their temporary task zones.
  • Escape releases captured mouse input.

Village simulation

The simulation currently creates three NPCs:

  • Amina
  • Tarik
  • Jasmin

Each receives a random profession from:

  • farmer;
  • woodcutter;
  • guard;
  • scholar;
  • wanderer.

Each simulated NPC currently stores:

  • stable integer ID for the session;
  • name and profession;
  • hunger and energy;
  • strength and intelligence;
  • current task and task state;
  • task duration and progress;
  • simulated position;
  • starvation state and duration;
  • death state.

The village currently tracks:

  • food, initially 20;
  • wood, initially 10;
  • safety, initially 50;
  • knowledge, initially 0;
  • per-resource modifiers;
  • per-resource priorities.

NPC task lifecycle

Task states are:

idle -> traveling -> working -> complete -> idle
                         |
                         +-> navigation_failed -> wander -> idle

NPCs currently choose among:

  • gather food;
  • gather wood;
  • patrol;
  • study;
  • eat;
  • rest;
  • wander.

Needs override ordinary work. Otherwise a utility-like score combines:

  • village priority;
  • critical and low resource thresholds;
  • profession preference;
  • a small random contribution.

The visual NPC walks toward the task's marker. Arrival tells the simulation to start work. Work progresses on simulation ticks. The village receives the result only when the task duration completes.

Starvation can reduce productivity and eventually kill an NPC. Dead visuals stop moving, change appearance, and no longer collide.

Current task zones

The main scene contains placeholder zones for:

  • farm;
  • forest;
  • guard duty;
  • study;
  • rest;
  • food.

The farm, forest, guard, study, rest, and food locations are represented by primitive geometry and a few tree assets.

Migration status: NPC gather_food and gather_wood no longer use the farm and forest zones. They target ResourceNode instances (berry bushes and trees) instead. The zone markers remain for:

  • Non-resource NPC tasks (patrol → guard_zone, study → study_zone, rest → rest_zone, eat → food_zone)

The player also harvests food and wood directly from nearby ResourceNode instances. Extraction returns the actual amount removed, updates the village by that amount, and releases an NPC reservation if the source is depleted.

Storage, rest, study, and guard behavior should later migrate to target types that match their actual semantics rather than treating every usable object as a resource source.

Current UI

A small village panel displays:

  • food;
  • wood;
  • safety;
  • knowledge;
  • starving NPC count;
  • selected village modifiers.

Most deeper reasoning is currently visible only through verbose debug output.

Runtime architecture

simulation/SimNPC.gd

SimNPC is a RefCounted simulation model. It owns needs, task selection, task progression, profession affinity, starvation, and death.

This separation from the visual node is an important architectural seed and should be preserved.

simulation/SimVillage.gd

SimVillage is a RefCounted aggregate for shared resources, modifiers, priorities, and applying completed NPC work.

simulation/SimulationManager.gd

SimulationManager is currently a scene-tree Node that:

  • owns the village and NPC array;
  • advances a tick approximately every 1.2 seconds;
  • creates NPCs;
  • coordinates task completion;
  • emits village, task, and death signals;
  • exposes direct resource-changing methods to the player.

It currently combines clock, orchestration, event publication, population creation, and some gameplay API responsibilities.

world/world_view_manager.gd

WorldViewManager bridges simulation data to visible NPC nodes. It:

  • instantiates NpcVisual scenes;
  • resolves resource nodes, random wander targets, and remaining activity markers;
  • writes the selected ResourceNode ID onto the NPC as a transitional behavior;
  • sends targets to visuals;
  • reports arrival and navigation failure back to SimulationManager;
  • applies visual death state.

player/npc/NpcVisual.gd

NpcVisual is the active-world representation of an NPC. It currently:

  • owns a NavigationAgent3D;
  • obtains a navigation path;
  • moves and rotates toward path points;
  • reports arrival;
  • applies a simple death presentation.

player/player.gd and player/camera_rig.gd

These implement camera-relative character movement, physical interaction proximity checks, ResourceNode harvesting, mouse capture, and the elevated follow camera.

world/ui/ui.gd

The UI subscribes to village changes and formats aggregate village state.

Current runtime flow

SimulationManager tick
    |
    v
SimNPC updates needs and chooses/advances a task
    |
    v
npc_task_changed signal
    |
    v
WorldViewManager resolves target:
  gather_food/wood -> nearest available ResourceNode (interaction point)
  wander           -> random offset from current position
  other            -> task-zone marker (guard, study, rest, eat)
    |
    v
NpcVisual navigates through the active world
    |
    +-- arrived_at_target signal
    |       |
    |       v
    |   SimulationManager marks NPC as working
    |       |
    |       v
    |   Later ticks complete work
    |       |
    |       v
    |   ResourceNode.extract() -> village.apply_resource_delta()
    |       |
    |       v
    |   village_changed signal updates the UI
    |
    +-- navigation_failed signal
            |
            v
        SimulationManager releases reservation, sets last_task, sends NPC to wander

Repository map

.
├── addons/terrain_3d/       Third-party Terrain3D plugin
├── assets/foliage/          Early tree assets
├── demo/                    Terrain3D's bundled demo, not the game
├── docs/                    Project context and plans
├── player/
│   ├── camera_rig.gd
│   ├── player.gd
│   ├── PlayerInteraction.gd Currently an empty placeholder
│   └── npc/
│       ├── NpcVisual.gd
│       └── NpcVisual.tscn
├── simulation/
│   ├── SimNPC.gd
│   ├── SimVillage.gd
│   └── SimulationManager.gd
├── tests/
│   └── resource_node_player_parity_test.gd
├── world/
│   ├── resource_nodes/
│   │   ├── ResourceNode.gd
│   │   ├── ResourceNode.gd.uid
│   │   └── ResourceNode.tscn
│   ├── world_view_manager.gd
│   └── ui/ui.gd
├── main.tscn
└── project.godot

Important limitations and technical debt

These are expected prototype constraints, not necessarily isolated bugs:

  • Task names and task-to-zone mappings are duplicated strings.
  • Task zones remain for non-resource activities; NPC and player food/wood gathering use ResourceNode instances.
  • Mutable simulation state is not serializable through a defined save schema.
  • Randomness is not seeded for deterministic replay.
  • Simulation time depends on _process and a scene-tree node.
  • Automated coverage currently contains one headless player-parity and resource-contention scenario; broader simulation coverage is still missing.
  • Resources are global floating-point counters rather than items in locations and inventories.
  • NPCs do not have homes, schedules, possessions, memories, relationships, goals, or social knowledge.
  • NPC reasoning is logged but not presented through an in-game inspector.
  • Active navigation is used as if all agents are local; no simulation LOD exists.
  • There is no spatial query/index layer for large populations.
  • Simulation, orchestration, and player-facing mutation APIs are concentrated in SimulationManager.
  • Path failure and interruption emit a navigation_failed signal and send the NPC to wander; this is functional but not yet polished.
  • Terrain3D is enabled but not yet used by the main game scene.
  • Combat, companions, factions, politics, trade, rumours, quests, persistence, and regional travel do not yet exist.
  • Placeholder geometry is sufficient for debugging but not for build-in-public presentation.

Target simulation architecture

Separate definitions, state, systems, and presentation

Use four conceptual layers:

  1. Definitions — immutable data for needs, actions, professions, items, traits, event types, and locations.
  2. State — serializable runtime records for NPCs, inventories, relationships, settlements, factions, and history.
  3. Systems — clocks, scoring, action resolution, economy, relationships, events, rumours, and persistence.
  4. Presentation adapters — Godot nodes that render nearby state, accept player input, play animation, and provide UI.

Do not make the simulation core depend on Node3D, scene paths, animation, physics frames, or a currently loaded map.

The authoritative-boundary decision is recorded in ADR 0001. The current ResourceNode state and WorldViewManager target selection are transitional, not patterns to extend into inventories, schedules, or relationships.

Authority and active-world adapters

Persistent mutable state belongs in versioned, serializable simulation records. Systems mutate those records. Godot nodes:

  • present nearby records;
  • expose active-world interaction transforms and navigation results;
  • translate player input into simulation commands;
  • synchronize active position through an explicit adapter;
  • never become the only owner of a persistent amount, reservation, action, or identity.

Target selection may consume facts supplied by the active world, but the presentation bridge must not author an NPC's decision or persistent target.

Stable identity

Every persistent entity should eventually have a stable ID:

  • person;
  • household;
  • item stack or significant item;
  • building;
  • workplace;
  • settlement;
  • faction;
  • location;
  • event.

References between simulation records should use IDs rather than live node references.

Fixed and deterministic time

The simulation should advance with an explicit clock and controlled random source. Given the same starting state, seed, and player commands, a headless run should be reproducible.

This enables:

  • debugging;
  • automated scenario tests;
  • balancing;
  • replaying build-in-public demonstrations;
  • comparing performance before and after optimization.

Scheduled work rather than per-frame thinking

At scale, agents should wake for relevant decisions or scheduled updates rather than running full reasoning every frame. Examples include:

  • need threshold crossed;
  • action completed or interrupted;
  • new information received;
  • path or workplace became unavailable;
  • daily schedule boundary;
  • relationship or faction event;
  • periodic low-frequency maintenance.

Simulation fidelity levels

The eventual world needs multiple representations:

  1. Active: full node, physics, navigation, perception, animation, and combat.
  2. Local abstract: individual position and scheduled actions without continuous physics.
  3. Distant individual: data-only people resolving travel and work by time.
  4. Settlement aggregate: carefully chosen economic or demographic aggregation for populations that do not currently need individual detail.

Moving between levels must preserve identity and important state. Aggregation must not erase named relationships or unresolved history.

Action model

Actions should become data-driven definitions with:

  • preconditions;
  • candidate targets;
  • utility considerations;
  • expected duration;
  • reservations;
  • resource costs;
  • effects;
  • interruption rules;
  • visible presentation hints;
  • reason tracing.

The first implementation can remain utility-based. Do not add a complex planner until current action scoring and sequencing demonstrate a concrete need.

Events and history

Important outcomes should create structured facts rather than prose-only logs. A future event record might contain:

event_id
event_type
simulation_time
location_id
actor_ids
target_ids
witness_ids
cause_event_ids
resource_changes
relationship_changes
visibility/secrecy
tags

Memories, rumours, reputation, and quests should reference or transform these facts. Generated text is presentation; structured state remains authoritative.

Emergent quest principle

A quest candidate should normally require:

  • a real unresolved condition;
  • an NPC or institution that knows or cares about it;
  • a plausible way to communicate it;
  • one or more achievable interventions;
  • consequences that update the source simulation.

Avoid creating a duplicate quest-only bandit, item, victim, or relationship when an existing simulated entity can provide the situation.

Performance principle

Design for scale, but optimize measured bottlenecks:

  • keep headless benchmarks;
  • record agent count, simulated duration, tick cost, and allocations;
  • prefer event-driven/scheduled updates;
  • use spatial partitioning for local queries;
  • batch homogeneous work when profiling justifies it;
  • avoid premature native extensions or data-oriented rewrites before the behavior model stabilizes.

Development strategy

The project has two interleaved tracks.

Living simulation

  • deterministic clock and state;
  • data-driven needs, professions, and actions;
  • inventories and economic flow;
  • events, history, relationships, and rumours;
  • simulation LOD and performance;
  • emergent opportunities and quests.

Living presentation

  • Jajce-inspired terrain composition;
  • attractive lighting, water, foliage, and weather;
  • readable characters and professions;
  • visible work, transport, and consequences;
  • interaction UI and simulation inspection;
  • combat feel, companions, and command feedback.

Every major systems milestone should produce a shareable visual behavior. Every visual milestone should support or reveal actual simulation state.

Immediate milestone: scaffold, architecture gate, then simulation garden

Food and wood migration on the flat test map is complete. The next visual step is a deliberately minimal JajceWorld scaffold, greybox, navigation spike, and resource-placement proof. Do not proceed directly from that proof into open-ended beauty production.

After the scaffold proves terrain and navigation, complete the architecture gate:

  • deterministic clock and controlled random source;
  • fixed-seed headless scenarios with final-state checksums;
  • versioned serializable NPC, village, and resource state;
  • data-defined action and profession IDs;
  • separated action selection, execution, target resolution, and visual travel;
  • resource amount and reservation authority moved out of scene nodes;
  • explicit synchronization of active NPC position.

The coherent visual slice can then aim for:

  • one attractive valley section;
  • six named villagers;
  • three visibly distinct workplaces;
  • food and wood as location-based resources;
  • visible gathering, carrying, storing, and consuming;
  • hunger and energy;
  • one understandable shortage crisis;
  • direct player assistance and priority influence;
  • day/night presentation;
  • an in-game reason inspector;
  • deterministic replay or scenario reset;
  • save/load for the slice;
  • a stable 2030 minute session.

Safety and knowledge can remain present, but their deeper production chains should follow a complete food loop rather than grow in parallel.

Out of scope until the simulation garden works

  • full regional map;
  • large city population;
  • multiplayer;
  • procedural world generation;
  • generations and inheritance;
  • complete market simulation;
  • kingdom-scale diplomacy;
  • large battles;
  • broad crafting catalog;
  • fully generated dialogue;
  • multiple large production chains;
  • production-quality character customization.

These remain part of the vision, not the next implementation target.

Agent working guidelines

  1. Read this document, the learning roadmap, the ResourceNode migration, and the build-in-public plan before proposing a large architectural or world-production change.
  2. Inspect git status and preserve unrelated user changes.
  3. Treat addons/terrain_3d/ and demo/ as third-party code unless a task explicitly concerns the plugin.
  4. Preserve Godot .uid and asset .import sidecars. They are tracked project metadata; .godot/ is the disposable cache.
  5. Keep simulation rules independent of visuals and loaded scenes.
  6. Prefer small vertical behavior slices over broad scaffolding.
  7. When adding a decision, add a way to inspect why it occurred.
  8. When adding persistent state, define how it saves and migrates.
  9. When optimizing, include a reproducible benchmark or measurement.
  10. Keep new systems data-driven only where it improves reuse or iteration; avoid abstraction without a demonstrated consumer.
  11. Use Conventional Commits.
  12. Update these documents when a decision materially changes the vision, architecture, milestones, or current-state description.
  13. Follow the authority order in the documentation map; do not let a focused visual or migration plan silently redefine system ownership.

Definition of “reusable for the future game”

A system is reusable when:

  • it has no dependency on this prototype's scene paths or placeholder zones;
  • definitions can be supplied as data;
  • mutable state is serializable;
  • behavior can be exercised headlessly;
  • presentation communicates through an adapter or events;
  • performance characteristics are measured;
  • its public API is documented by real use, not speculative abstraction.

Reusable does not necessarily mean a separate Godot plugin. Extract a library only after the API has stabilized through use.

Glossary

  • Active NPC: A fully represented nearby character with a Godot scene node.
  • Agent: A simulated decision-making entity, usually an NPC.
  • Event: A structured fact that something happened in world time.
  • History: Persisted events and their enduring consequences.
  • Memory: An NPC's retained interpretation or knowledge of events.
  • Presentation adapter: Code that translates simulation state into scenes, animation, audio, UI, and player input.
  • Quest: A player-facing framing and tracking mechanism for an opportunity or unresolved condition.
  • Reason trace: Data explaining the inputs and scores behind a decision.
  • Simulation garden: A small, attractive, controlled world used to validate deep systems and make them watchable.
  • Simulation LOD: Changing computational fidelity based on relevance while preserving important identity and state.
  • World event: A consequential state transition that may be witnessed, remembered, communicated, and acted upon.