harvest/game/COOP.md
Forrest 315e6890f7 Task #22: the joining player can open the store
Cause: the open path itself worked. A real two-process run with an E key event opened the
shed's menu when P2 stood at the counter. What failed in play was reach:
- The partner's game never showed the counter's "[E / X] Shop" prompt.
  CoopSession._gather_node resolved only the workbench and gather points, so P2's
  replicated focus was null at the counter. P2 couldn't tell where the 2.2 m reach around
  the counter's invisible point was.
- The host took P2's press on the first tick after the input record arrived, before its
  copy of P2 had eased to the position in that same record. It dropped the press silently
  if the lagging copy was out of reach. Walking in at 5 or 9 m/s and pressing E at 2.1 m
  (inside the reach on P2's screen) failed 3/3. The host's copy was 2.31-2.66 m out.

Fixes:
- The snapshot's focus now resolves the ShedCounter (_focus_node), so the prompt shows.
- The host keeps a partner's interact press pending for 0.3 s (Interactions.PRESS_WINDOW)
  until a counter in reach takes it.
- Interact while the partner's shop menu is open closes it on the partner's machine, and
  that press is taken back (RemoteControls.Sender.take_back), so the host never reopens it.
- When the host completes P2's "buy", it sends a "bought" event. Once P2's farm state has
  the upgrade, the partner's panel emits bought (UpgradePanel.confirm_bought). As in solo,
  the new weapon goes into P2's hand and the jingle plays. Still paid from P2's pouch,
  then the shed.
- CoopSession.PROTOCOL 4 -> 5.

Tests: test_coop _shops covers both shops opening on the client only, the prompt, interact
closing, a press taken while the host's copy is 3.8 m out still opening, an early press not
opening later, and a client weapon buy paid from P2's pouch and the shed and equipped on
both farms. coop_smoke now opens and closes the shed by day with E key events, both
standing and on arrival at a run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 13:47:52 -04:00

201 lines
13 KiB
Markdown

# Harvest Season — co-op
Two players keep the farm together: each has a scarecrow, and both play the same vacation.
Co-op runs on [GD-Sync](https://www.gd-sync.com) (`addons/GD-Sync/`, version 1.0.2), the
multiplayer plugin; its autoload is `GDSync`.
## Playing together
Main menu → **Play with a friend**. Enter your name (shown over your scarecrow), then pick how to
connect:
| Connect | What it needs | How the friend finds you |
|---|---|---|
| **Same network (LAN)** | Nothing: GD-Sync's local mode is peer to peer, with no account or keys | Join lists the games announced on the network |
| **LAN by address** | The host's address (shown in the host's status line: "or by address: 192.168.1.20") | Join → type the address → Join. Use it when the list stays empty: some firewalls drop the announcements, and VPNs like Tailscale or ZeroTier don't carry them, but connect fine by address |
| **Online** | The project's GD-Sync API keys (below) | Join lists the open games, or type the game's name ("Ana's farm") |
- **Host a game:** pick the vacation (continue your save, or a new one), and the farm opens to
your friend. You play right away; your friend can join, leave, and rejoin at any time.
- **Join a game:** pick it from the list (or type its address or name). You arrive on the host's
farm as player 2, mid-day or mid-night, wherever the host is.
### Online play: the API keys
Online lobbies go through GD-Sync's servers, which need the project's keys (a free account at
gd-sync.com gives them):
1. In the Godot editor, open **Project → Tools → GD-Sync**.
2. Paste the public and private keys.
GD-Sync saves them to `addons/GD-Sync/keys.cfg`. That file is in `.gitignore`; never commit it.
The keys can also come from the `GDSYNC_PUBLIC_KEY` and `GDSYNC_PRIVATE_KEY` environment
variables. Without keys, the menu says so and LAN still works.
Exported builds get the keys automatically: GD-Sync's export plugin writes `keys.cfg` into
every export. Anyone with a build can read them, which is how GD-Sync works for every game. If
the keys leak somewhere they shouldn't, make new ones at gd-sync.com.
### Voice chat
On by default when both are in: your microphone is sent while you talk, and your friend's voice
plays on the Voice bus. It opens on about a tenth of a second of sound over room noise (a click or
a knock alone doesn't open it) and stays open for 0.4 s after you stop. Talking costs about
10 KB/s online.
- **[M]** mutes and unmutes your microphone; Settings → Co-op does the same.
- Settings → Audio → "Voice chat (your friend)" sets their volume.
- While your friend is talking, a speaker mark shows on their panel.
- Use headphones: an open microphone picks up the game's sound from speakers.
## In the game
- **Tags and colors.** Name tags over both scarecrows: P1 (the host) in gold, P2 in blue. Player
2's scarecrow is tinted blue.
- **Partner panel** (above your own health):
- their name, health, and what they're doing (down until morning, patching, gathering, fear
ready);
- "talking" while their voice comes through, and the ping;
- your microphone's state.
- **Edge arrow:** when your friend is off screen, an arrow at the edge points to them, with the
distance.
- **Shared:** the shed, upgrades, structures, and the vacation itself. Either player can gather,
build, repair, buy upgrades, and start the day.
- **Shops open on your own screen.** By day, walk up to the Supply Shed's counter (or the work
area's bench, once you have it) until "[E / X] Shop" (or "Upgrades") shows, and press E / X.
- E / X again, Escape / B, walking off, or nightfall closes it.
- A weapon you buy goes into your hand.
- **Your pouch is your own.** The materials HUD shows yours.
- What you gather goes into your pouch.
- Only you walking into the Supply Shed banks it: your friend standing there doesn't.
- You pay for building, repairs, patching, and upgrades from your own pouch first, then the
shed, never from your friend's pouch.
- An Alien's goop goes into the pouch of the player who killed it. A pumpkin bomb's or a
turret's kill goes to the nearest scarecrow.
- Both pouches hold the same amount: one Bigger pouch makes both bigger.
- When your friend leaves, what they carried goes into the shed. So does player 2's pouch in
a co-op save that the host continues alone.
- **Health is your own.** Upgrades to max health apply to both scarecrows.
- **A scarecrow at 0 HP is out until the morning.** It lies there and the camera follows the
other one. It comes back each morning at half health. **Game Over only when both are down at
once.**
- **Enemies go for the nearer scarecrow.** Animals follow whoever picked them up.
- **The host's game is the real one and it saves** (the partner's doesn't). Retry, starting the
night early, and the end screens work from either side; only the host can restart the night
from the pause menu.
- **Menus don't pause co-op.** Your scarecrow stands still while your menu is up.
- **Leaving:**
- If the partner leaves, the host plays on alone.
- If the host leaves, the partner is back at the main menu, which says why.
- A co-op save continued alone plays by the solo rules.
## How it works
The host's farm simulates everything: both scarecrows, every enemy, the loot, the animals, and the
campaign. The partner's farm is a replica (`FarmSim.replica`). It simulates nothing and shows what
the host sends, except the partner's own scarecrow. The partner moves that scarecrow itself, so
moving never waits on the network, and sends its position, facing, and buttons to the host, where
it acts.
| Piece | File | Does |
|---|---|---|
| `CoopSession` | `game/scripts/coop_session.gd` | The protocol, on both sides: the welcome, snapshots in packed bytes 15 times a second (the clock, both scarecrows with the weapon in hand and the bomb's recharge, animals, shots, and the enemies that are due, in 16-byte records), the farm state and the loot when they change, news in order (phase changes, the end, sounds, toasts, loot news, breaches, fear bursts, attacks, pumpkin bombs thrown, gather popups), and the partner's input (with its pick of weapon) and requests. The partner's own weapons only aim and show their motion: the host attacks for it, so nothing is hit twice |
| `CoopLink`, `GDSyncLink` | `coop_link.gd`, `gdsync_link.gd` | The wire: GD-Sync remote calls, reliable or not, large messages compressed; the packing helpers; a loopback pair for tests |
| `CoopLobby` | `coop_lobby.gd` | GD-Sync's LAN and online modes, lobbies, join by address |
| `RemoteControls` | `remote_controls.gd` | The partner's buttons as the host sees them: held state, press counts (a lost packet never loses a press), aim, build mode, menus; its input record, 39 bytes |
| `Avatar` | `avatar.gd` | One scarecrow and its kit, weapons, and hands; `FarmSim.avatars` holds both |
| `CoopVoice` | `coop_voice.gd` | GD-Sync's `VoiceChat` (the microphone and the playback), one per player, owned by that player; sends speech as 4-bit ADPCM in 60 ms pieces, through its own gate |
| `CoopHud`, `CoopMenu` | `coop_hud.gd`, `coop_menu.gd` | The partner panel and arrow; the menu |
Messages that may be lost (snapshots, input) stay under 1,100 bytes. GD-Sync splits datagrams at
1,200. Nothing depends on any one of them arriving, and removals are reliable.
The partner's shops:
- **Opening.** The host's copy of the partner's scarecrow trails the partner's own by a few
ticks: the input goes out 20 times a second, and the copy eases toward it. So the partner's
press of interact waits on the host for up to 0.3 s for that copy to reach a shop's counter,
instead of being lost when it was made on arrival. The host then tells the partner's game to
open that shop's menu.
- **Closing.** Interact again closes the menu on the partner's machine, and that press is never
sent.
- **Buying.** A purchase goes to the host, which pays it from the partner's pouch and the shed.
The partner's game then counts it as bought there, as in solo: a new weapon goes into the
partner's hand.
### Data use (GD-Sync's allowance)
Online, every byte goes through GD-Sync's servers, and plans are sold by data transfer (the free
one has 200 MB a day). GD-Sync doesn't say whether the relay out to the other player counts too.
What keeps co-op small:
- **Packed snapshots.** Snapshots and the partner's input are packed bytes, not Dictionaries,
where every key's name went out with every value.
- **Few messages.** GD-Sync adds about 220 bytes to each unreliable message (its request, a
signature, the packet's envelope), so a snapshot is one message: shots and the enemies ride
in it.
- **Only what changed.** The farm state goes out when it changes (the phase clock alone doesn't
count: every snapshot has it), the loot likewise, and the partner's input when it changes or
every 0.25 s.
- **Dead reckoning for enemies.** The partner moves each enemy on at the velocity of its last
record, and the host sends a new one only when that guess is 25 cm off, or the velocity,
heading, altitude, or state changed, or it was hit, and at least every second. New and changed
records go out twice more, in case one is lost. In the test's crowd of 64, that's a tenth of
the records.
- **Compression.** Messages over 256 bytes (the welcome, the farm state, the loot, big news
batches) are compressed with zstd before GD-Sync gets them. GD-Sync compresses packets only
after encrypting them, which saves nothing.
- **Voice** goes out as 4-bit ADPCM at 12 kHz, only while you talk: about 10 KB/s, against about
60 KB/s for GD-Sync's own `VoiceChat`, which sends raw samples whenever the microphone peaks.
`game/tools/net_budget.gd` measured a whole vacation (5 nights, 32 minutes, the partner always
moving, no voice): 22 MB sent to the server, against 113 MB before (2026-10-04). That's about 12
KB/s: 6 from the host, 5.5 from the partner. Both machines must run the same version of the game:
the hello and the welcome carry `CoopSession.PROTOCOL`, and a mismatch ends the session with a
message on both sides.
## Testing
- **`game/tests/test_coop.gd`** (in the main suite) runs host and partner in one process: the
partner's farm sits in its own world, over the loopback link. It covers the join, requests,
the partner moving, gathering, and shooting (and its pick of weapon), each player's own pouch
(gathering, the shed, paying, the shared capacity, goop to the killer, leaving), the host's stabs and
pumpkin bombs drawn on the partner's farm (harmless there), enemies, loot, and shots arriving, the fall rule
and Retry, a crowd with dropped packets, message sizes, and either side leaving. It also covers
the partner's shops: the prompt, either shop's menu opening on the partner's farm only and
closing on interact, a press the host gets before its copy of the partner is at the counter,
and a weapon bought into P2's hand.
- **`game/tools/coop_smoke.gd`** plays a real GD-Sync LAN game between two processes on one
machine. The partner joins by address, since broadcasts don't loop back on every machine;
`--discover` uses the network announcements instead. `--online` plays through GD-Sync's
servers (needs the keys): the partner finds the host's lobby in the online list. Give both
sides the same `--host-name`, so an old lobby from an earlier run isn't picked by mistake. By
day the partner opens and closes the Supply Shed's menu with the E key: standing at the
counter, then pressing on arrival at a run.
- **`game/tools/net_budget.gd`** measures the traffic for the GD-Sync data allowance: it plays
whole days and nights over a loopback link that packs every message the way GD-Sync does
online, and reports what each side sends to the server, by message kind and by phase, plus
voice chat's rate while talking. `--nights=5` is a whole vacation.
```sh
godot --headless --path . --script res://game/tools/coop_smoke.gd -- --role=host &
godot --headless --path . --script res://game/tools/coop_smoke.gd -- --role=join
# online:
godot --headless --path . --script res://game/tools/coop_smoke.gd -- --role=host --online --host-name=Smoke1 &
godot --headless --path . --script res://game/tools/coop_smoke.gd -- --role=join --online --host-name=Smoke1
```
**Online, tested (2026-10-04):** both sides passed. The partner found and joined the lobby in
about 2 s, and played the day and the night with 24 enemies.
**Not tested here:** discovery between two machines (this one's firewall drops broadcasts),
online play between two machines on different networks, and voice with real microphones
(headless has none).
## Patches to GD-Sync
Four small patches, each marked `Harvest Season patch` in the code. Re-apply them after updating
the plugin.
| File | Patch | Why |
|---|---|---|
| `Scripts/ConnectionController.gd` | LAN client ids fit in 30 bits | Targeted calls carry the id in 30 bits (`RequestProcessor.encode_target_client`). A random 32-bit LAN id got cut off, and calls to that player reached nobody. |
| `Scripts/RequestProcessor.gd` | A fixed HMAC key in LAN mode | Without API keys the key is empty, and Godot logs an error for every unreliable packet |
| `Scripts/SessionController.gd`, `Scripts/Types/NodeInstantiator.gd` | Null checks for the current scene | Tests and tools run without one (`--script`) |
| `Scripts/Logger.gd` | Only talk to the debugger when one is attached | Same |