forked from Julian-adv/OpenMMO
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
697 lines (664 loc) · 27.4 KB
/
Copy pathlib.rs
File metadata and controls
697 lines (664 loc) · 27.4 KB
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
//! Shared types and protocol between the Rust server, agent-client, and
//! the WASM web client. Definitions are split by concern across small
//! sibling modules and re-exported here so external callers can keep
//! using flat `onlinerpg_shared::Position` paths regardless of where the
//! type now lives.
pub mod ability;
pub mod bridge;
pub mod celestial;
pub mod character;
pub mod debuff;
pub mod dungeon;
pub mod entity;
pub mod estate_storage;
pub mod fence;
pub mod fishing;
pub mod fnv;
pub mod furniture;
pub mod grass_format;
pub mod housing;
pub mod hunger;
pub mod interest;
pub mod inventory;
pub mod landscaping;
pub mod mana;
pub mod meal;
pub mod messages;
pub mod monster_ai;
pub mod moon;
pub mod mount;
pub mod mount_movement;
pub mod pathfinding;
pub mod pricing;
pub mod schedule;
pub mod skills;
pub mod stall;
pub mod tales;
pub mod terrain_files;
pub mod tip_hat;
pub mod tree_format;
pub mod weather;
pub mod world;
pub mod worldgen;
pub mod xp;
/// File name of the NPC auth token inside the server's `--state-dir`
/// (default `data/`). agent-client reads `../data/<this>` as its zero-config
/// fallback; a deploy that moves `--state-dir` must hand agent-client the
/// token explicitly via `npc_token` in config.toml.
pub const NPC_TOKEN_FILENAME: &str = "npc_token";
/// Wire protocol version, sent in `ClientMessage::ClientInfo` and checked for
/// exact equality by the server. Bump it whenever a message shape or its
/// meaning changes: clients we cannot redeploy (agent-clients on other
/// machines) must be refused with an "update me" notice rather than left to
/// fail at a random later message. See `doc/REMOTE_AGENT_CLIENT.md`.
/// v6: attack-rejection ack.
/// v7: trained skills (SkillsUpdate/SkillXpGained) + fishing
/// (cast/bite/struggle messages) — see `doc/FISHING.md`.
/// v8: fishing struggle rounds replaced by continuous FishingFight beats.
/// v9: `Player.main_hand` + PlayerMainHandChanged equipment broadcast.
/// v10: party (PartyInvite/PartyRespond/PartyLeave, PartyState snapshots).
/// v11: party positions poll (RequestPartyPositions → PartyPositions) for
/// world-map member markers.
/// v12: equip slots hands/back/shirt (doc/ITEM_TIERS.md 선행 작업 #1).
/// v13: party summoning scroll (PartySummonReceived → PartySummonRespond).
/// v14: a monster's loot spawns when the killing blow lands, so
/// GroundItemSpawned no longer carries source_monster_id.
/// v15: DungeonDiscoveries snapshot for per-character world-map markers.
/// v16: hunger (HungerUpdate) + campfires (Campfire* / Grill*) — doc/HUNGER.md.
/// v17: PartyPositions pushed server-side on relocation (was a poll answer)
/// and now includes the recipient; clients filter themselves.
/// v18: party chat (PartyChat → PartyChatMessage).
/// v20: `/play_music` picks a BGM track and nearby clients play it along
/// (PlayerMusicStarted).
/// v21: PlayerMusicStarted carries `elapsed_secs` and is re-sent to players
/// entering earshot of a running performance.
/// v22: GroundItem carries `dropped_by` and GroundItemRemoved
/// `picked_up_by`, so a busker knows who left the coins at its feet —
/// and who took them.
/// v23: friends (FriendRespond/FriendRemove/RequestFriendsOnline →
/// FriendList/FriendsOnline/FriendRequestReceived); FriendList is
/// pushed at login, so older builds must not connect.
/// v24: merchant stalls (`/lay_stall`/`/pack_stall` →
/// StallPlaced/StallAppeared/StallRemoved); GameState carries `stalls`.
/// v25: declined trade offers (DeclineTrade → TradeDeclined), so an NPC
/// stops pushing trade windows at a player who waved one off.
/// v26: PartyMember carries hp/max_hp/class, PartyVitals pushes member
/// health, and PartyKick/PartyPromote (leader kick + handover).
/// v27: GroundItem carries `quantity`, so a dropped stack lands as one pile,
/// and GroundItemQuantityChanged reports a pile someone took part of.
/// v28: tip hats (the `tip_hat` item → TipHatPlaced/TipHatAppeared/
/// TipHatRemoved, ClientMessage::TipHat); GameState carries `tip_hats`.
/// v29: debuffs (DebuffUpdate) replace HungerUpdate's `poisoned_ms` —
/// doc/DEBUFF.md.
/// v30: player-to-player trading (doc/TRADE.md) — PlayerTradeRequest/
/// AtStall/Respond/SetOffer/Lock/Unlock/Confirm/Cancel and
/// PlayerTradeRequested/RequestResult/Update/Ended/Error.
/// v31: `Player.back` + PlayerBackChanged, so nearby clients render a
/// wearer's cape.
/// v32: `Character.equipment`, so character select renders each character's
/// weapon, off-hand and cape.
/// v35: DungeonReset, sent before the sunset reset puts each occupant out so
/// the client can play the roar.
/// v36: `XpGained.monster_id` names the kill the XP came from, so the client
/// can hold the gain until that monster starts going down.
/// v37: SpawnMonsterRequest/RequestSpawnMonster are gone — the server places
/// ambient monsters itself, keyed to distance walked
/// (doc/REPEAT_FARMING.md).
/// v38: RenameCharacter + CharacterRenameRequired/CharacterRenamed, so a
/// character whose name later lands on the banned list is renamed at
/// character select instead of being let in.
/// v39: level thresholds moved to the doc/LEVEL_CURVE.md table. No message
/// changed; a stale bundle would draw XP gauges on the old curve.
/// v40: `Player.wet` + PlayerWetToggled, so nearby clients can draw wet
/// footprints behind a soaked player (doc/DEBUFF.md).
/// v41: `ShopState.price_index_percent`, the merchant price index on
/// consumable buy prices (doc/PRICING.md).
/// v42: `PricingNotice` for NPC clients (price index, trend, next meeting)
/// and the `"meeting"` schedule condition.
/// v43: `FriendEntry.class`, so the friend panel can draw class icons.
/// v44: `WallVariant::WithDoubleDoor` ("double-door"); stale clients cannot
/// decode houses that use it.
/// v45: `ClientMessage::WorldReady` ends the entry grace that shields a
/// player until their scene is drawn; an older server cannot decode it.
/// v46: titles — `Player.title`, `Character.titles`/`active_title`,
/// `ClientMessage::SetActiveTitle`; an older server cannot decode it.
/// v47: `Player.object_id` rides the wire (bed occupied on respawn, for the
/// inn maid's bedside visit); the array grew, so older builds cannot
/// decode `Player`.
/// v48: `PlayerInteractionChanged.object_id` — which chair/bed was taken,
/// so the maid's table spots key on the placement id; the array grew,
/// so older builds cannot decode it.
/// v50: `ServerMessage::Recital` (`/recite` verses shown as a bubble only,
/// doc/HEROIC_TALES.md); an older client cannot decode it.
/// v51: table meals — `Meal`, `ServeMeal`/`EatMeal`/`ClearMeal`,
/// `MealPlaced/Appeared/Eaten/Removed`, `GameState.meals` (doc/HUNGER.md);
/// an older client cannot decode a served plate.
/// v52: live instrument performance (`StartInstrument`/`InstrumentNotes` and
/// the corresponding nearby-player start/note broadcasts).
/// v53: `PlayerAttacked.ammo_item_def_id` — which round a ranged shot spent,
/// so the arrow drawn in flight is the one that left the quiver.
/// v54: Land Deed preview, confirmed claims, and registration results.
/// v55: Land claim previews include the reason a plot cannot be claimed.
/// v56: Land tax account state, deposits, and withdrawals.
/// v57: persistent cell-edge fences, placement mode and inventory recovery.
/// v58: estate landscaping tools, permanent palettes and terrain updates.
/// v59: fractional landscaping radii for one-cell brush widths.
/// v60: player house-scroll placement preview and authoritative placement.
/// v61: persistent estate storage chests with atomic, weight-limited transfers.
/// v62: estate editor tabs can request an authenticated landscaping mode.
/// v63: horse mounting state and mount changes.
/// v64: mounted steering and PlayerMountTurn cancels travel at the server position.
/// v65: mounted arc movement and explicit mount steering cancellation.
/// v66: bold fishing bonus chance and second-fish outcome.
/// v67: pre-rolled trophy fights replace the second-fish bonus.
/// v68: consignment stalls replace the stall entry to player trades.
/// v69: persistent item locks and SetItemLocked.
/// v70: mounted reverse recovery and authoritative recovery progress;
/// `ServerMessage::WeatherSync` (seed, bias and sector tag for the
/// regional rain cells, doc/WEATHER_SYSTEM.md); an older client cannot
/// decode it.
/// v71: Guardian Ward ability, cooldowns, buff snapshots and VFX events.
/// v72: per-strike damage rolls and skipped dagger strikes.
/// v74: Radiance toggle and visible-player lighting state.
/// v75: targeted abilities and private True Aim mark updates.
/// v76: distinct out-of-range ability rejection.
/// v77: Double Slash cooldown snapshots on login.
/// v78: server-wide rain overrides in WeatherSync.
/// v79: owner-only ManaUpdate and Guardian Ward's MP cost.
/// v80: revisioned world subscriptions, full terrain snapshots and resync.
/// v82: Grass payloads store per-cell counts (GR04).
/// v83: terrain file manifests and direct binary downloads.
/// v84: mounts carry a kind instead of a bool.
pub const PROTOCOL_VERSION: u32 = 84;
/// Fingerprint of the dungeon layout generator this build compiled, stamped by
/// `build.rs`. Layouts never travel the wire — both sides generate them from
/// the entrance id — so a stale generator desyncs without changing any message
/// shape, which `PROTOCOL_VERSION` cannot see. See the layout fingerprint
/// section of doc/REMOTE_AGENT_CLIENT.md.
pub const LAYOUT_VERSION: &str = env!("LAYOUT_VERSION");
/// Marks the fingerprint inside a client version string. Riding the string
/// rather than a new `ClientInfo` field is deliberate: rmp_serde encodes
/// structs as positional arrays, so a 4th field makes the server fail to
/// decode an older client's `ClientInfo` at all — and that path only logs,
/// leaving the client refused in silence instead of told to update.
const LAYOUT_TAG: &str = "+layout.";
/// Client version string with this build's fingerprint appended, e.g.
/// `0.1.0+layout.1f3c...`.
pub fn stamp_layout_version(client_version: &str) -> String {
format!("{client_version}{LAYOUT_TAG}{LAYOUT_VERSION}")
}
/// The fingerprint a client stamped, or `None` from a build predating the
/// stamp — itself a mismatch worth refusing. Stops at the next `+` so the
/// suffix stays a tag list a sibling fingerprint could join.
pub fn layout_version_of(client_version: &str) -> Option<&str> {
client_version
.rsplit_once(LAYOUT_TAG)
.and_then(|(_, tail)| tail.split('+').next())
}
/// Whether a client reported this build's fingerprint. Self-reported like the
/// rest of `ClientInfo`, and that is fine: lying only buys the liar the desync
/// this gate prevents.
pub fn layout_version_matches(client_version: &str) -> bool {
layout_version_of(client_version) == Some(LAYOUT_VERSION)
}
/// WebSocket close code sent when the handshake is refused (wrong protocol
/// version, or traffic before `ClientInfo`). Lives outside the serialized
/// message shape on purpose: a client too old to understand a new message can
/// still read a close code, so this is the one signal that reaches a stale
/// build and tells it to stop reconnecting. Never renumber it.
pub const CLOSE_CODE_PROTOCOL_MISMATCH: u16 = 4001;
/// WebSocket close code sent when a source IP opens sessions faster than
/// `conn_limit` allows. Unlike a protocol refusal this is transient, so
/// clients should keep retrying on their normal backoff.
pub const CLOSE_CODE_RATE_LIMITED: u16 = 4002;
/// WebSocket close code sent when a session ends because the client's world
/// disagrees with the server's — today, grinding dungeon walls only its own
/// build generated. Unlike a protocol refusal this is found mid-session, and
/// clients should reload rather than reconnect: the same build lands in the
/// same disagreement.
pub const CLOSE_CODE_CLIENT_DESYNC: u16 = 4004;
/// WebSocket close code sent when the server drops a connection for going
/// quiet — no login inside the unauth grace period, or no heartbeat in game.
/// Transient like a rate limit, so clients retry on their normal backoff; the
/// point is that they learn the server closed them and why, instead of reading
/// a bare TCP FIN and having to guess whether the path died.
pub const CLOSE_CODE_IDLE_TIMEOUT: u16 = 4003;
#[cfg(target_arch = "wasm32")]
mod wasm_api;
pub use character::{Character, CharacterAttributes, CharacterClass, Gender, VisibleEquipment};
pub use entity::{Monster, MonsterLifecycle, MonsterState, Player, PlayerId};
pub use messages::{
deserialize_client_msg, deserialize_server_msg, serialize_client_msg, serialize_server_msg,
ActiveDeal, AttackRejectReason, ClientMessage, DealKind, InstrumentNoteEvent, ServerMessage,
INSTRUMENT_BATCH_MS, INSTRUMENT_MAX_EVENTS_PER_BATCH, INSTRUMENT_NOTE_COUNT,
};
pub use world::{
shortest_world_delta_x, wrap_world_x, GameDateTime, NoSpawnZone, Position,
EVENT_DELIVERY_RADIUS, MAX_MOVE_TARGET_DISTANCE, PLAYER_MOVE_SPEED, WORLD_MAX_X, WORLD_MIN_X,
WORLD_WIDTH_X,
};
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
#[test]
fn roundtrip_client_message() {
let msg = ClientMessage::PlayerMove {
position: Position {
x: 1.0,
y: 2.0,
z: 3.0,
},
rotation: 1.5,
floor_level: 1,
append: false,
sprinting: false,
};
let bytes = serialize_client_msg(&msg).unwrap();
let decoded = deserialize_client_msg(&bytes).unwrap();
match decoded {
ClientMessage::PlayerMove {
position,
rotation,
floor_level,
..
} => {
assert_eq!(position.x, 1.0);
assert_eq!(position.y, 2.0);
assert_eq!(position.z, 3.0);
assert_eq!(rotation, 1.5);
assert_eq!(floor_level, 1);
}
_ => panic!("Wrong variant"),
}
}
#[test]
fn roundtrip_unit_variant() {
let msg = ClientMessage::RequestRespawn;
let bytes = serialize_client_msg(&msg).unwrap();
let decoded = deserialize_client_msg(&bytes).unwrap();
assert!(matches!(decoded, ClientMessage::RequestRespawn));
}
#[test]
fn roundtrip_dagger_skill_messages() {
let request = ClientMessage::DaggerDoubleSlash {
monster_id: "m1".to_string(),
};
let bytes = serialize_client_msg(&request).unwrap();
assert!(matches!(deserialize_client_msg(&bytes).unwrap(),
ClientMessage::DaggerDoubleSlash { monster_id } if monster_id == "m1"));
for message in [
ServerMessage::AbilityCooldowns {
cooldowns: vec![crate::ability::AbilityTimer {
ability: crate::ability::AbilityId::DaggerDoubleSlash,
remaining_ms: 7000,
}],
},
ServerMessage::DaggerDoubleSlashStarted {
player_id: 1.into(),
monster_id: "m1".to_string(),
cooldown_ms: 10000,
},
ServerMessage::DaggerDoubleSlashRejected {
monster_id: "m1".to_string(),
reason: "dagger_required".to_string(),
cooldown_ms: 0,
},
ServerMessage::DaggerDoubleSlashSkipped {
player_id: 1.into(),
monster_id: "m1".to_string(),
strike: 2,
reason: "target_defeated".to_string(),
},
ServerMessage::PlayerAttacked {
player_id: 1.into(),
monster_id: "m1".to_string(),
hit: true,
roll: 20,
damage: 17,
ammo_item_def_id: None,
dagger_strike: Some(1),
},
] {
let bytes = serialize_server_msg(&message).unwrap();
let decoded = deserialize_server_msg(&bytes).unwrap();
assert_eq!(format!("{decoded:?}"), format!("{message:?}"));
}
}
#[test]
fn roundtrip_weather_sync() {
for rain_override in [None, Some(0.0), Some(0.4), Some(1.0)] {
let bytes = serialize_server_msg(&ServerMessage::WeatherSync {
seed: 42,
bias: 1.0,
sectors_tag: "0123456789abcdef".into(),
rain_override,
})
.unwrap();
match deserialize_server_msg(&bytes).unwrap() {
ServerMessage::WeatherSync {
seed,
bias,
sectors_tag,
rain_override: decoded_override,
} => {
assert_eq!(seed, 42);
assert_eq!(bias, 1.0);
assert_eq!(sectors_tag, "0123456789abcdef");
assert_eq!(decoded_override, rain_override);
}
other => panic!("Wrong variant: {other:?}"),
}
}
}
#[test]
fn roundtrip_live_instrument_messages() {
let events = vec![
InstrumentNoteEvent {
note: 0,
offset_ms: 0,
},
InstrumentNoteEvent {
note: 21,
offset_ms: 249,
},
];
let bytes = serialize_client_msg(&ClientMessage::InstrumentNotes {
events: events.clone(),
})
.unwrap();
match deserialize_client_msg(&bytes).unwrap() {
ClientMessage::InstrumentNotes { events: decoded } => assert_eq!(decoded, events),
other => panic!("Wrong variant: {other:?}"),
}
let bytes = serialize_server_msg(&ServerMessage::PlayerInstrumentNotes {
player_id: PlayerId::from(7),
position: Position {
x: 1.0,
y: 2.0,
z: 3.0,
},
floor_level: -2,
events: events.clone(),
})
.unwrap();
match deserialize_server_msg(&bytes).unwrap() {
ServerMessage::PlayerInstrumentNotes {
player_id,
position,
floor_level,
events: decoded,
} => {
assert_eq!(player_id, PlayerId::from(7));
assert_eq!((position.x, position.y, position.z), (1.0, 2.0, 3.0));
assert_eq!(floor_level, -2);
assert_eq!(decoded, events);
}
other => panic!("Wrong variant: {other:?}"),
}
}
#[test]
fn roundtrip_server_message_with_hashmap() {
let players = vec![Player {
id: 1.into(),
name: "Test".to_string(),
position: Position {
x: 0.0,
y: 0.0,
z: 0.0,
},
rotation: 0.0,
level: 1,
health: 10,
max_health: 10,
class: CharacterClass::Knight,
gender: Gender::default(),
is_official_npc: false,
torch_on: false,
radiance_on: false,
floor_level: 0,
object_type: None,
main_hand: None,
back: None,
object_id: None,
last_combat_at: 0,
client_kind: Default::default(),
mount: None,
ready_at: 0,
back_color: None,
back_texture: None,
wet: false,
title: None,
}];
// A monster with every Option None guards the wire format itself:
// rmp_serde encodes structs as positional arrays, so any field that
// fails to serialize (e.g. a future `skip_serializing_if`) shifts
// the later fields and breaks this real serialize/deserialize path.
let mut monsters = HashMap::new();
monsters.insert(
"m1".to_string(),
Monster {
id: "m1".to_string(),
monster_type: "slime".to_string(),
position: Position {
x: 1.0,
y: 0.0,
z: 1.0,
},
rotation: 0.0,
state: MonsterState::Idle,
owner_id: None,
health: 8,
max_health: 8,
floor_level: 0,
level_override: None,
aggressive: true,
lifecycle: MonsterLifecycle::Ambient,
last_attack_at: 0,
last_move_at: 0,
move_budget: 0.0,
owner_since: 0,
},
);
let msg = ServerMessage::GameState {
players,
monsters,
ground_items: Vec::new(),
campfires: Vec::new(),
stalls: Vec::new(),
tip_hats: Vec::new(),
meals: Vec::new(),
};
let bytes = serialize_server_msg(&msg).unwrap();
let decoded = deserialize_server_msg(&bytes).unwrap();
match decoded {
ServerMessage::GameState {
players, monsters, ..
} => {
assert_eq!(players.len(), 1);
assert_eq!(players[0].id, PlayerId::from(1));
let m = &monsters["m1"];
assert_eq!(m.level_override, None);
assert!(m.aggressive);
}
_ => panic!("Wrong variant"),
}
}
const ALL_CLASSES: &[CharacterClass] = &[
CharacterClass::Knight,
CharacterClass::Barbarian,
CharacterClass::Caveman,
CharacterClass::Valkyrie,
CharacterClass::Ranger,
CharacterClass::Samurai,
CharacterClass::Monk,
CharacterClass::Priest,
CharacterClass::Archaeologist,
CharacterClass::Healer,
CharacterClass::Rogue,
CharacterClass::Wizard,
CharacterClass::Tourist,
CharacterClass::Bard,
CharacterClass::Merchant,
CharacterClass::Guard,
CharacterClass::Maid,
];
#[test]
fn character_class_str_roundtrip() {
for class in ALL_CLASSES {
let s = class.as_str();
let back: CharacterClass = s.parse().expect("parse should accept as_str output");
assert_eq!(&back, class, "roundtrip failed for {s}");
}
}
#[test]
fn character_class_from_str_rejects_unknown() {
assert!("".parse::<CharacterClass>().is_err());
assert!("nonexistent".parse::<CharacterClass>().is_err());
assert!("Knight".parse::<CharacterClass>().is_err());
}
#[test]
fn only_operator_classes_are_unselectable() {
for class in ALL_CLASSES {
let expected = !matches!(
class,
CharacterClass::Merchant | CharacterClass::Guard | CharacterClass::Maid
);
assert_eq!(
class.is_player_selectable(),
expected,
"{} selectability",
class.as_str()
);
}
}
#[test]
fn character_class_hit_die_is_valid_polyhedron() {
for class in ALL_CLASSES {
let d = class.hit_die();
assert!(
matches!(d, 4 | 6 | 8 | 10 | 12 | 20),
"class {:?} has non-standard hit die d{}",
class,
d
);
}
}
#[test]
fn stat_adjustments_sum_to_zero() {
// Balanced classes: the six adjustments must net to zero so no class
// gains or loses total stat points before the 72-rebalance step.
for class in ALL_CLASSES {
for gender in [Gender::Male, Gender::Female] {
let adj = class.stat_adjustments(gender);
let sum: i32 = adj.iter().map(|v| *v as i32).sum();
assert_eq!(
sum, 0,
"class {:?} gender {:?} adjustments sum to {} (expected 0): {:?}",
class, gender, sum, adj
);
}
}
}
#[test]
fn stat_adjustments_gender_variants_differ_only_where_expected() {
// Knight, Barbarian, and Caveman have gendered splits; all others ignore gender.
let gendered = [
CharacterClass::Knight,
CharacterClass::Barbarian,
CharacterClass::Caveman,
];
for class in ALL_CLASSES {
let male = class.stat_adjustments(Gender::Male);
let female = class.stat_adjustments(Gender::Female);
if gendered.contains(class) {
assert_ne!(
male, female,
"class {:?} expected gendered adjustments",
class
);
} else {
assert_eq!(
male, female,
"class {:?} should have identical adjustments for both genders",
class
);
}
}
}
#[test]
fn no_spawn_zone_contains_inside_and_boundary() {
let zone = NoSpawnZone {
min_x: -10.0,
min_z: -5.0,
max_x: 10.0,
max_z: 5.0,
};
assert!(zone.contains(0.0, 0.0));
assert!(zone.contains(-10.0, -5.0));
assert!(zone.contains(10.0, 5.0));
assert!(zone.contains(-10.0, 5.0));
assert!(zone.contains(10.0, -5.0));
assert!(!zone.contains(-10.1, 0.0));
assert!(!zone.contains(10.1, 0.0));
assert!(!zone.contains(0.0, -5.1));
assert!(!zone.contains(0.0, 5.1));
}
#[test]
fn no_spawn_zone_degenerate_point_zone() {
// A zero-area zone still matches its single point.
let zone = NoSpawnZone {
min_x: 3.0,
min_z: 7.0,
max_x: 3.0,
max_z: 7.0,
};
assert!(zone.contains(3.0, 7.0));
assert!(!zone.contains(3.0001, 7.0));
}
#[test]
fn roundtrip_all_server_messages() {
let messages = vec![
ServerMessage::AuthError {
message: "bad".to_string(),
},
ServerMessage::PlayerLeft {
player_id: 1.into(),
},
ServerMessage::PlayerDisappeared {
player_id: 1.into(),
},
ServerMessage::MonsterDead {
monster_id: "m1".to_string(),
dropped_weapon_item_def_id: Some("goblin_sword".to_string()),
},
ServerMessage::PlayerAttacked {
player_id: 1.into(),
monster_id: "m1".to_string(),
hit: true,
roll: 18,
damage: 5,
ammo_item_def_id: None,
dagger_strike: None,
},
ServerMessage::MonsterProvoked {
player_id: 1.into(),
monster_id: "m1".to_string(),
},
ServerMessage::Kicked {
player_id: 1.into(),
reason: "test".to_string(),
},
ServerMessage::ServerNotice {
message: Some("restart soon".to_string()),
},
ServerMessage::ServerNotice { message: None },
];
for msg in messages {
let bytes = serialize_server_msg(&msg).unwrap();
let decoded = deserialize_server_msg(&bytes).unwrap();
// Just verify it roundtrips without error
assert!(!format!("{:?}", decoded).is_empty());
}
}
}