Skip to main content

eq_network_game/
command.rs

1//! Typed client actions and their dialect-specific packet encoding.
2
3use crate::{chat, chat::OutboundChat, GameDialect};
4use anyhow::Result;
5
6/// An action requested by an application after zone admission.
7///
8/// Future movement, zoning, inventory, group, and character actions belong
9/// here so application code never needs to carry raw opcodes or packet bytes.
10#[derive(Clone, Debug, Eq, PartialEq)]
11#[non_exhaustive]
12pub enum GameCommand {
13    /// Send one chat message.
14    SendChat(OutboundChat),
15}
16
17/// A command encoded as one game application packet.
18#[derive(Clone, Debug, Eq, PartialEq)]
19#[non_exhaustive]
20pub struct EncodedCommand {
21    /// Little-endian application opcode understood by the selected dialect.
22    pub opcode: u16,
23    /// Application body without the opcode or reliable-UDP framing.
24    pub body: Vec<u8>,
25}
26
27/// Encode a typed client action for one game dialect.
28///
29/// `character` supplies the active character name for packet layouts that
30/// repeat the sender identity.
31///
32/// # Errors
33///
34/// Returns an error when a command contains values that cannot be represented
35/// by the selected dialect.
36pub fn encode(
37    dialect: GameDialect,
38    command: &GameCommand,
39    character: &str,
40) -> Result<EncodedCommand> {
41    match command {
42        GameCommand::SendChat(message) => Ok(EncodedCommand {
43            opcode: match dialect {
44                GameDialect::TitaniumP99 => 0x1004,
45                GameDialect::EqMac => 0x0741,
46            },
47            body: chat::encode_outbound_for(dialect, message, character)?,
48        }),
49    }
50}
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55
56    #[test]
57    fn chat_command_selects_each_dialects_opcode_and_layout() {
58        let command = GameCommand::SendChat(OutboundChat::Say("ok".into()));
59        let titanium = encode(GameDialect::TitaniumP99, &command, "Example").unwrap();
60        let eqmac = encode(GameDialect::EqMac, &command, "Example").unwrap();
61
62        assert_eq!(titanium.opcode, 0x1004);
63        assert_eq!(eqmac.opcode, 0x0741);
64        assert_ne!(titanium.body, eqmac.body);
65    }
66}