# Agrarian Multiplayer And Networking Design

## Purpose

This document defines Agrarian's multiplayer and networking direction for the
MVP foundation. It focuses on authority, replication, join/spawn flow, tile
delivery interaction, latency expectations, disconnect behavior, and test gates.

The goal is to prove a small shared survival world without overbuilding the
final MMO-scale architecture too early.

## MVP Networking Goal

The first playable MVP must support at least two players joining the same
server, spawning into the Ground Zero tile, and interacting with the same
survival world.

The multiplayer proof is complete when:

- both players see the same world time and weather;
- both players can gather resources;
- inventory and survival stats replicate correctly;
- placed campfires/shelters/build pieces replicate;
- basic wildlife/resource state is shared;
- server restart can preserve core state;
- disconnect/reconnect has a defined MVP behavior;
- tile package lookup/download does not depend on clients mutating server
  state.

## Network Model

MVP model:

- Unreal server-authoritative gameplay.
- Listen server is acceptable for quick internal testing.
- Dedicated server remains the preferred closed-test target once packaging is
  stable.

Decision:

- Do not block the current MVP on a polished dedicated server deployment if a
  listen-server flow can prove gameplay.
- Do build toward dedicated server compatibility by keeping gameplay authority
  on the server and avoiding local-only critical state.

## Authority Rules

The server owns gameplay truth.

Server authoritative systems:

- player survival values;
- inventory changes;
- crafting validation and outputs;
- resource node depletion/respawn;
- wildlife state;
- world time and gameplay calendar;
- weather state applied to survival;
- placement/build validation;
- persistence writes;
- player spawn/respawn decisions;
- tile package/version selected for the active world.

Client-owned or client-local systems:

- input;
- camera;
- UI/HUD;
- local animation presentation;
- local audio/visual effects;
- local tile cache files;
- local settings.

Clients may request actions, but the server validates and applies results.

## Replication Scope

Replicate only what the client needs to render, play, or make decisions.

Already represented in current foundations:

- player survival stats;
- inventory;
- world time;
- weather;
- resource nodes;
- build pieces.

Near-term replication rules:

- replicate compact snapshots rather than large internal structures;
- replicate item IDs and stack counts, not full item definitions;
- replicate stable actor state, not transient animation-only details;
- keep weather and world time on `GameState` or equivalent global replicated
  state;
- make interactable actors responsible for their own meaningful replicated
  state;
- avoid Blueprint-only mutation of critical replicated state when C++ authority
  code exists.

## RPC Rules

RPCs should be narrow, explicit, and server validated.

Good RPC shape:

- `ServerRequestGather(TargetActor)`
- `ServerRequestCraft(RecipeId)`
- `ServerRequestPlaceBuildable(BuildableId, Transform)`
- `ServerRequestInteract(TargetActor, InteractionId)`

RPCs should validate:

- the requesting player is alive;
- the target exists and is relevant;
- distance and line-of-use are acceptable;
- required items/resources exist;
- placement rules pass;
- cooldown or action timing rules pass;
- the requested item/recipe/buildable exists in authoritative data.

Avoid broad RPCs that pass arbitrary inventory edits, raw stat values, or
client-authored world changes.

## Join Flow

MVP join flow:

1. Client loads startup/splash flow.
2. Client reaches character selection.
3. Client connects to the selected server.
4. Server validates connection and selected character choice.
5. Server assigns a player record or temporary MVP player identity.
6. Server sends current world state needed for the Ground Zero tile.
7. Client spawns at an approved spawn point.
8. Client UI initializes from replicated survival/inventory/world state.

The first MVP does not need account services, matchmaking, or full character
persistence. It does need a deterministic flow that can be tested repeatedly.

## Server Travel Flow

MVP server travel is intentionally allowlisted. The admin/dev command
`AgrarianServerTravel GroundZero` routes through the server and resolves to:

```text
/Game/Agrarian/Maps/L_GroundZeroTerrain_Test?listen
```

This gives listen-server and dedicated-server tests one repeatable travel path
without exposing arbitrary map URLs to clients. Future travel expansion should
add explicit tile/session validation before allowing any new map or region.

## Spawn And Respawn

Initial MVP spawn:

- spawn inside Ground Zero at a safe, known starting area;
- avoid spawning inside water, steep terrain, structures, or resource actors;
- provide enough immediate access to water/gatherables for a first survival
  test.

Respawn MVP behavior:

- may use a simple fixed spawn point or small spawn zone;
- does not spawn a corpse/backpack container in 0.1.J;
- should clear or penalize some carried inventory when death inventory loss is
  implemented;
- should make any future corpse/backpack actor server-owned, interaction-gated,
  persistent, and decay-aware;
- should not require full generational inheritance yet;
- should record enough information for debugging death/respawn bugs.

Future respawn design should connect to family, inheritance, settlements, and
legacy.

## Tile Delivery And Networking

The tile server is separate from the gameplay server.

Current MVP tile endpoint:

```text
http://maps.agrariangame.com:18080
```

The tile server serves static packages. It does not own gameplay state.

Server responsibilities:

- select the active tile/package version for the world;
- persist which tile/package version the world uses;
- reject or defer gameplay actions on tiles not active/loaded for that server;
- expose enough tile metadata to clients to request the correct package;
- keep gameplay authority separate from tile file delivery.

Client responsibilities:

- download tile packages from the tile endpoint;
- verify checksums;
- store packages in a local cache;
- redownload packages when missing or invalid;
- never decide authoritative tile state by itself.

Missing tile response:

- if a client lacks a required tile package, the client should show a loading
  or missing-content state and download the package;
- if the server lacks a required active tile package, the server should reject
  travel/spawn into that tile and log an operational error;
- if the tile server is unreachable, the client should retry with clear error
  messaging rather than silently failing.

## Network Relevancy

MVP relevancy can stay simple but should not replicate the entire future world.

Near-term rules:

- always relevant: player controller/pawn, player survival/inventory owner
  state, global world time/weather;
- spatially relevant: resource nodes, wildlife, build pieces, fire/shelter,
  nearby interactables;
- not replicated as gameplay actors: static terrain package files and large
  tile metadata payloads.

MVP actor cull distances:

- item pickups: 30 meters;
- resource nodes: 45 meters;
- campfires, shelters, and wildlife: 60 meters;
- water sources and weather exposure zones: 65 meters;
- wildlife spawn managers: 80 meters.

These are intentionally conservative prototype values. They prevent the first
Ground Zero multiplayer test from replicating every interactable to every
client while still keeping nearby survival objects responsive.

Future rules should align with World Partition, tile boundaries, settlement
density, and player population.

## Latency Expectations

MVP target:

- normal gathering/crafting/building should feel acceptable under LAN and
  typical residential broadband latency;
- clean LAN profile uses 0ms artificial lag and 0% packet loss;
- mild WAN profile uses 80ms lag, 20ms variance, and 1% packet loss;
- rough WAN profile uses 160ms lag, 40ms variance, and 3% packet loss;
- survival stat updates can tolerate low-frequency replication;
- inventory/crafting feedback should feel responsive enough to test the loop;
- combat and precision movement prediction are not the first MVP focus.

`Docs/Ops/MultiplayerLatencyTestPlan.md` is the 0.1.L latency gate. It uses
Unreal packet simulation commands and two packaged clients to check resource
depletion, item drops, fire/shelter replication, wildlife state, and server
travel under repeatable profiles.

Initial latency testing should cover:

- join and spawn;
- gather request/response;
- craft request/response;
- place buildable request/response;
- inventory replication;
- survival stat replication;
- disconnect/reconnect.

## Disconnect And Reconnect

MVP behavior:

- disconnect removes the player's pawn from active control and captures a
  player reconnect snapshot during `AAgrarianGameGameMode::Logout`;
- the reconnect snapshot preserves transform, survival, care history, and
  inventory through `UAgrarianPersistenceSubsystem::SavePlayerSnapshot`;
- reconnect/spawn restores the matching snapshot in
  `AAgrarianGameGameMode::RestartPlayer` through
  `UAgrarianPersistenceSubsystem::RestorePlayerSnapshot`;
- if no matching snapshot exists, the player uses the normal MVP spawn point;
- server should not crash or leak active interaction/build state when a player
  disconnects mid-action.

Closed testing should document the current reconnect rule explicitly so testers
know what behavior is expected.

## Security And Abuse Baseline

Even in MVP, the server should not trust clients with authoritative values.

Do not accept client-authored:

- health, hunger, thirst, stamina, or body temperature values;
- item grants or inventory mutations;
- resource depletion results;
- build placement success;
- weather/time changes;
- tile package versions for active gameplay;
- persistence writes.

MVP anti-cheat is not a complete system, but basic validation should prevent
accidental or obvious client-side authority mistakes.

## Dedicated Server Direction

Dedicated server should become the normal closed-test host once:

- Linux dedicated server build is repeatable;
- Ground Zero map cooks correctly for server;
- server startup can select/load the MVP map;
- server logs are easy to collect;
- persistence path is explicit;
- firewall and port requirements are documented;
- disconnect/reconnect behavior is stable enough for testers.

Until then, listen server can be used for quick internal validation, provided
code still follows server-authoritative patterns.

## Testing Gates

Minimum multiplayer smoke test:

1. Start server.
2. Connect player A.
3. Connect player B.
4. Confirm both see same world time/weather.
5. Player A gathers a resource.
6. Player B observes the changed resource state.
7. Player A crafts an item.
8. Inventory replication remains correct.
9. Player B places or observes a build piece.
10. Restart server and verify expected persisted state.

Minimum tile/network proof:

1. Client resolves `maps.agrariangame.com`.
2. Client downloads `manifest.json`.
3. Client downloads the Ground Zero tile package files.
4. Client verifies checksums.
5. Client deletes one cached file.
6. Client redownloads and revalidates it.

Minimum latency test:

- run the smoke test once on LAN;
- run it once through the intended external/public path when available;
- record ping/latency observations and obvious gameplay pain points.

## Implementation Priorities

Near-term multiplayer priorities:

- confirm MVP listen server vs dedicated server operating path;
- define player join and spawn flow in code/data;
- add network relevancy rules for resource/build/wildlife actors;
- add basic latency testing;
- define disconnect/reconnect behavior;
- keep tile package delivery separate from gameplay authority;
- prepare dedicated server as the closed-test target.

## Open Questions

- Should the first closed test require a dedicated server, or can it use a
  controlled listen-server host?
- What is the minimum acceptable reconnect behavior for the first closed test?
- Which actors need custom relevancy first: wildlife, resource nodes, build
  pieces, or fires/shelters?
- How should the server expose active tile/package version to connecting
  clients?
- What port layout should be standardized for gameplay server, tile server,
  RCON/admin, and future telemetry?
- When do we introduce client prediction for gathering/building interactions?
