flatland-protocol 0.2.0

Flatland3 wire protocol types and codecs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
use serde::{Deserialize, Serialize};
use uuid::Uuid;

pub type EntityId = u64;
pub type Tick = u64;
pub type Seq = u32;
pub type SessionId = u64;

/// World position `(x, y, z, w, t)` — `t` reserved at 0.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct WorldCoord {
    pub x: f32,
    pub y: f32,
    pub z: f32,
    pub w: u32,
    pub t: u32,
}

impl WorldCoord {
    pub fn surface(x: f32, y: f32) -> Self {
        Self {
            x,
            y,
            z: 0.0,
            w: 0,
            t: 0,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct Velocity2D {
    pub vx: f32,
    pub vy: f32,
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct Transform {
    pub position: WorldCoord,
    pub yaw: f32,
    pub velocity: Velocity2D,
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LifeState {
    Alive,
    Dead,
}

impl Default for LifeState {
    fn default() -> Self {
        Self::Alive
    }
}

/// Player health / resources (players only; omitted on other entities).
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct PlayerVitals {
    pub health: f32,
    pub health_max: f32,
    pub mana: f32,
    pub mana_max: f32,
    pub stamina: f32,
    pub stamina_max: f32,
    #[serde(default)]
    pub coins: u32,
    #[serde(default)]
    pub deaths: u32,
    #[serde(default)]
    pub life_state: LifeState,
}

impl Default for PlayerVitals {
    fn default() -> Self {
        Self {
            health: 100.0,
            health_max: 100.0,
            mana: 50.0,
            mana_max: 50.0,
            stamina: 100.0,
            stamina_max: 100.0,
            coins: 0,
            deaths: 0,
            life_state: LifeState::Alive,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EntityState {
    pub id: EntityId,
    pub transform: Transform,
    /// Character / display name (first letter used as map glyph for other players).
    #[serde(default)]
    pub label: String,
    #[serde(default)]
    pub vitals: Option<PlayerVitals>,
    /// When inside a building interior (players only).
    #[serde(default)]
    pub inside_building: Option<String>,
}

/// Nearby voice chat vs magical long-range (requires whisper-stone item).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ChatChannel {
    Nearby,
    WhisperStone,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ChatMessage {
    pub channel: ChatChannel,
    pub from_entity: EntityId,
    pub from_name: String,
    pub text: String,
    pub tick: Tick,
}

/// Client → server gameplay input (reliable, sequenced per entity).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Intent {
    Move {
        entity_id: EntityId,
        forward: f32,
        strafe: f32,
        seq: Seq,
    },
    Stop {
        entity_id: EntityId,
        seq: Seq,
    },
    Harvest {
        entity_id: EntityId,
        node_id: String,
        seq: Seq,
    },
    Use {
        entity_id: EntityId,
        item_instance_id: Uuid,
        seq: Seq,
    },
    Say {
        entity_id: EntityId,
        channel: ChatChannel,
        text: String,
        seq: Seq,
    },
    /// Start a blueprint craft (timed, like harvest).
    Craft {
        entity_id: EntityId,
        blueprint_id: String,
        seq: Seq,
    },
    /// Door, NPC, enter/exit building.
    Interact {
        entity_id: EntityId,
        target_id: String,
        seq: Seq,
    },
    /// Dev / test: apply damage to self (co-op testing).
    TestDamage {
        entity_id: EntityId,
        amount: f32,
        seq: Seq,
    },
}

/// Server → client AOI-filtered entity updates for one sim tick.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TickDelta {
    pub tick: Tick,
    pub entities: Vec<EntityState>,
    #[serde(default)]
    pub resource_nodes: Vec<ResourceNodeView>,
    #[serde(default)]
    pub buildings: Vec<BuildingView>,
    #[serde(default)]
    pub doors: Vec<DoorView>,
    #[serde(default)]
    pub npcs: Vec<NpcView>,
    /// Observer inventory stacks (template → qty).
    #[serde(default)]
    pub inventory: Vec<ItemStack>,
    #[serde(default)]
    pub blueprints: Vec<BlueprintView>,
}

/// Full state on region enter or reconnect.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Snapshot {
    pub tick: Tick,
    pub chunk_rev: u64,
    pub entities: Vec<EntityState>,
    #[serde(default)]
    pub resource_nodes: Vec<ResourceNodeView>,
    /// Segment play area width in meters (for HUD).
    #[serde(default)]
    pub world_width_m: f32,
    #[serde(default)]
    pub world_height_m: f32,
    #[serde(default)]
    pub buildings: Vec<BuildingView>,
    #[serde(default)]
    pub doors: Vec<DoorView>,
    #[serde(default)]
    pub npcs: Vec<NpcView>,
    #[serde(default)]
    pub inventory: Vec<ItemStack>,
    #[serde(default)]
    pub blueprints: Vec<BlueprintView>,
}

/// Harvestable node visible to clients.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ResourceNodeView {
    pub id: String,
    pub label: String,
    pub x: f32,
    pub y: f32,
    pub z: f32,
    pub item_template: String,
    #[serde(default = "default_node_state")]
    pub state: ResourceNodeState,
    /// When true, players cannot walk through this node while available/harvesting.
    #[serde(default)]
    pub blocking: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ResourceNodeState {
    Available,
    Harvesting,
    Cooldown,
}

fn default_node_state() -> ResourceNodeState {
    ResourceNodeState::Available
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ItemStack {
    pub template_id: String,
    pub quantity: u32,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BlueprintIngredientView {
    pub template_id: String,
    pub quantity: u32,
    /// Always serialize — `true` is not bool::default() so postcard keeps it; explicit for clarity.
    pub consumed: bool,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolRequirementView {
    pub item: String,
    /// Always serialize — postcard omits `false` by default, which breaks roundtrip without explicit value.
    pub consumed: bool,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SkillRequirementView {
    pub skill: String,
    pub level: u32,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BlueprintView {
    pub id: String,
    pub label: String,
    pub output: String,
    pub output_qty: u32,
    pub craft_ticks: u32,
    pub inputs: Vec<BlueprintIngredientView>,
    /// Postcard always serializes optional fields (no `skip_serializing_if`) so decode stays aligned.
    #[serde(default)]
    pub station: Option<String>,
    #[serde(default)]
    pub category: Option<String>,
    #[serde(default)]
    pub required_tools: Vec<ToolRequirementView>,
    #[serde(default)]
    pub skill: Option<SkillRequirementView>,
    #[serde(default)]
    pub failure_chance: f32,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BuildingView {
    pub id: String,
    pub label: String,
    pub x: f32,
    pub y: f32,
    pub width_m: f32,
    pub depth_m: f32,
    /// Interior map origin (for wall rendering when player is inside).
    #[serde(default)]
    pub interior_origin_x: f32,
    #[serde(default)]
    pub interior_origin_y: f32,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DoorView {
    pub id: String,
    pub building_id: String,
    pub x: f32,
    pub y: f32,
    pub open: bool,
    #[serde(default)]
    pub is_exit: bool,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NpcView {
    pub id: String,
    pub label: String,
    pub role: String,
    pub x: f32,
    pub y: f32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub building_id: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CraftResult {
    pub blueprint_id: String,
    pub outputs: Vec<ItemStack>,
    pub consumed: Vec<ItemStack>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DeathNotice {
    pub entity_id: EntityId,
    pub respawn_x: f32,
    pub respawn_y: f32,
    pub message: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct InteractionNotice {
    pub target_id: String,
    pub message: String,
    #[serde(default)]
    pub coins_delta: i32,
    #[serde(default)]
    pub inventory_delta: Vec<ItemStack>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct HarvestResult {
    pub node_id: String,
    /// Stack quantity granted (not one-node-one-instance).
    pub quantity: u32,
    pub item_template: String,
    /// Optional DB row id when persisted to control plane.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub item_instance_id: Option<Uuid>,
}

/// Every on-wire payload is wrapped for versioning and codec uniformity.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Envelope<T> {
    pub protocol_version: u16,
    pub payload: T,
}

impl<T> Envelope<T> {
    pub fn new(payload: T) -> Self {
        Self {
            protocol_version: crate::PROTOCOL_VERSION,
            payload,
        }
    }
}

/// Session handshake after transport connect.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Hello {
    pub client_name: String,
    pub protocol_version: u16,
    #[serde(default)]
    pub auth: AuthCredential,
    /// Required for session auth; embedded in `ApiToken` variant otherwise.
    #[serde(default)]
    pub character_id: Option<Uuid>,
}

/// How the client authenticates to the game gateway.
/// Uses default serde enum encoding (postcard-compatible; not internally tagged).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AuthCredential {
    DevLocal,
    Session { token: String },
    ApiToken { token: String, character_id: Uuid },
}

impl Default for AuthCredential {
    fn default() -> Self {
        Self::DevLocal
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Welcome {
    pub session_id: SessionId,
    pub entity_id: EntityId,
    pub snapshot: Snapshot,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ServerMessage {
    Welcome(Welcome),
    Tick(TickDelta),
    IntentAck {
        entity_id: EntityId,
        seq: Seq,
        tick: Tick,
    },
    Chat(ChatMessage),
    HarvestResult(HarvestResult),
    CraftResult(CraftResult),
    Death(DeathNotice),
    Interaction(InteractionNotice),
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ClientMessage {
    Hello(Hello),
    Intent(Intent),
    Disconnect,
}