# Multiplayer Documentation

- [Mirror Quickstart](MIRROR-QUICKSTART.md)
- [Events](EVENT-REFERENCE.md)
- [开局/重开时获取机器人信息](ROBOTS.zh-CN.md)
- [断线重连接入流程与示例](CONNECTION-RECONNECT.md)
- [进程重启后的手动重返指南](MANUAL-REENTRY.zh-CN.md)：Host 交接、EntryKind、游戏状态同步和验收。
- [KCP Idle Keepalive and RTT](KCP-HEARTBEAT-RTT-GUIDE.md)
- [Third-party Notices](THIRD-PARTY-NOTICES.md)

## Runtime Creation

RoomNode must support `arena-protobuf` and advertise `limits.maxRecordBytes`
(normally 16384). The SDK rejects a missing or invalid record limit. Reliable
P2P/custom messages may span multiple records; the SDK owns their reassembly
and local memory/time budgets. Arena-executed State/RPC operations must fit one
record. UDP does not use logical fragmentation. Upgrade Arena and Multiplayer
together when moving to this handshake contract.

All packaged samples use `.cs.txt`; assembly templates use `.asmdef.txt`.
Importing either carrier does not compile these examples. Explicitly copy and
rename only an example you choose to use; assembly templates are optional.

Core selects one Host platform runtime from the current Unity platform.
Multiplayer does not expose or repeat that selection.

```csharp
await core.InitializeAsync();

// Retry Core Host bootstrap explicitly when initial Host integration was unavailable.
bool connected = await multiplayer.TryCreateRuntimeAsync(cancellationToken);
if (!connected || !multiplayer.IsRealtimeReady)
{
    throw new InvalidOperationException("RoomNode Game data plane is unavailable.");
}
```

A caller can provide the same Core DTO directly. Here `bootstrap` is the complete
`IGPMultiplayerBootstrap` supplied by the caller, with the fields described below:

```csharp
bool connected = await multiplayer.TryCreateRuntimeAsync(
    bootstrap,
    cancellationToken);
```

There is no descriptor-only overload. `IGPMultiplayerBootstrap` contains an
immutable Gateway `Room` snapshot, immutable `CurrentPlayer` snapshot, and the
RoomNode `DataPlane` descriptor. Missing required fields or mismatched
room/player identities fail with `MULTIPLAYER_CONTEXT_INVALID` before any
socket is created.

## Runtime Context

| Property | Source | Lifetime |
| --- | --- | --- |
| `CurrentRoomSnapshot` | Gateway bootstrap | Immutable values replaced on bootstrap refresh and known player departure |
| `Robots` | Players marked `IsBot` in the same bootstrap | Read-only startup list; no RoomNode route required |
| `PlayerId` / `PlayerName` | Gateway current-player bootstrap | Read-only |
| `CurrentSceneGate` | RoomNode Game lane | Ready-time runtime state |

Peer routing is internal. Applications send to player IDs; the SDK installs
RoomNode membership snapshots and manages transport slots automatically.

Multiplayer never connects to Gateway, maintains mutable Lobby room state, or
exposes room commands. Its `RoomChanged` event reports committed business snapshots; see [EVENT-REFERENCE.md](EVENT-REFERENCE.md).

## Bootstrap Data Structures

### Robot Queries

```csharp
IReadOnlyList<IGPMultiplayerPlayerSnapshot> robots = multiplayer.Robots;
if (multiplayer.TryGetRobot(robotId, out var robot))
{
    string robotData = robot!.RobotData;
    // Interpret robotData in game code, according to the game's own format.
}
```

Both APIs read memory only. The list preserves bootstrap order and reuses its
immutable player snapshots. `RobotData` is passed through unchanged, including
non-JSON strings; no robot behavior, team rules, or routing is inferred.
`TryGetRobot` uses case-sensitive ordinal ID comparison and returns `false`
with a null result for missing, empty, or null IDs.

The list is installed before Ready, including when an in-progress connection
attempt obtains a refreshed bootstrap. It is empty before installation and
cleared on creation failure, explicit disconnect, or runtime disposal. A
temporary Reliable interruption retains the list. Installing a fresh bootstrap
replaces it; an already-Ready, same-context creation call remains a no-op.
The SDK does not subscribe to later robot changes or expose robot management
commands. Core Host bootstrap and explicit caller bootstrap use the same path;
neither requires Lobby to be installed.

### Bootstrap Types

`IGPMultiplayerBootstrap` is immutable and contains three required properties:

| Property | Type | Meaning |
| --- | --- | --- |
| `Room` | `IGPMultiplayerRoomSnapshot` | Gateway room snapshot committed before any RoomNode socket is opened. |
| `CurrentPlayer` | `IGPMultiplayerPlayerSnapshot` | The Gateway player identity for this client. |
| `DataPlane` | `IGPGameDataPlaneDescriptor` | RoomNode connection descriptor for the same room and player. |

The room snapshot fields are:

| Field | Type | Required/default and lifecycle |
| --- | --- | --- |
| `Id` | `string` | Required Gateway room identifier. |
| `Code`, `Name`, `GameId` | `string` | Gateway room values preserved for game code; Multiplayer does not require them to connect. |
| `Status` | `string` | Must be `playing` when Multiplayer creates the runtime. |
| `HostId` | `string` | Gateway host player ID for game display/state; Reliable routing is managed internally. |
| `MaxPlayers` | `int` | Gateway room capacity value preserved for game code. |
| `MapPublicId` | `string` | Gateway selected map public ID preserved for game code. |
| `MapVersionId` | `int?` | Gateway selected map version preserved for game code. |
| `Players` | `IReadOnlyList<IGPMultiplayerPlayerSnapshot>` | Immutable Gateway player snapshot. Multiplayer does not enforce membership rules. |
| `Teams` | `IReadOnlyList<IGPMultiplayerTeamSnapshot>` | Immutable Gateway team snapshot; Multiplayer does not enforce team policy. |

Each `IGPMultiplayerPlayerSnapshot` contains the following immutable fields:

| Field | Type | Meaning / default |
| --- | --- | --- |
| `Id` | `string` | Required current-player identity matching the descriptor. |
| `Name`, `Color`, `Avatar` | `string` | Display name, color and avatar; absent strings become empty. |
| `AvatarIndex` | `int` | Gateway avatar index; zero when omitted. |
| `TeamId` | `string` | Gateway team association; empty when omitted. |
| `IsReady`, `IsBot` | `bool` | Gateway ready and robot flags; false when omitted. |
| `RobotData` | `string` | Opaque robot configuration; empty when omitted. |

Each `IGPMultiplayerTeamSnapshot` contains these immutable Gateway values:

| Field | Type | Meaning / default |
| --- | --- | --- |
| `Id`, `Name`, `Color` | `string` | Team identity, display name and color; absent strings become empty. |
| `MaxPlayers` | `int` | Team capacity; zero when omitted. |
| `PlayerCount` | `int` | Gateway player count; zero when omitted. |

Both types remain unchanged for the lifetime of their snapshot. Multiplayer
preserves these values without inferring robot, team, membership or slot policy.

`IGPGameDataPlaneDescriptor` publicly exposes only `RoomId` and `PlayerId`.
They must match `Room.Id` and `CurrentPlayer.Id`. A caller that receives the
opaque JSON returned by Gateway `room.dataPlane.request` constructs it with
`IGPGameDataPlaneDescriptor.FromSdkDescriptorJson(roomId, playerId, json)`.
KCP is required; TCP and raw UDP are optional descriptor transports. Tokens,
expiry, endpoints, and negotiated limits remain internal to the SDK. The
descriptor and bootstrap redact credentials from `ToString()` and must not be
persisted, serialized, or logged by game code.

Reliable routing is managed internally and established before Ready. Game code
uses the complete room snapshots and `RoomChanged` business event described in
[Events](EVENT-REFERENCE.md); no peer-routing context is required to handle
players joining or leaving.

## Transport Lifecycle

`IsRuntimeCreated` means transport resources exist.
`IsRealtimeReady` means the selected KCP/TCP Reliable handshake completed.
An optional UDP failure does not invalidate Reliable Ready.

Established Reliable disconnect triggers one automatic recovery using retained Match credentials.
`ReconnectDataPlaneAsync()` shares that attempt, or explicitly retries after failure.
`TryCreateRuntimeAsync()` requests Host bootstrap; caller-owned bootstrap overloads
perform the same per-Match deduplication and replacement. See [recovery](CONNECTION-RECONNECT.md).

`ShutdownAsync()` releases only the Game data plane. It does not leave, finish,
or dismiss the Gateway room.

The runtime host can send `FinishGameAsync` over the Ready Reliable Game lane.
Arena validates the current Match host, ends the whole Match and sends runtime.finished.
SDK then commits Status=finished and emits RoomChanged(GameEnded) once.
FinishGameAsync completion means the finish request was sent; GameEnded confirms
Arena completed the Match. DisconnectAsync requests only the current player leave.
