> ## Documentation Index
> Fetch the complete documentation index at: https://epitech-f1becc07.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Protocols

> Documentation for TCP and UDP protocols in the R-Type project.

# Network Protocols

This page documents the network communication protocols used in the **R-Type project**, including **TCP** and **UDP**. These protocols are essential for handling reliable and efficient communication between clients and the server.

***

<AccordionGroup>
  <Accordion title="Network Functionality">
    ### Lobby

    The lobby operates exclusively using **TCP** to ensure a reliable and structured communication protocol. This guarantees that critical actions, such as joining or leaving lobbies, are securely handled.

    ### Game

    The game utilizes a hybrid approach:

    * **UDP**: For real-time game data, such as player positions or actions.
    * **TCP**: For critical information, such as game state synchronization or important updates.

    ### Network Architecture

    The server initializes a **TCP** port at startup. For every game instance, a new thread is launched with its own **TCP** and **UDP** ports to handle the game's network communication.

    All networking logic is encapsulated within a static library, which includes:

    * **Client and server interfaces**: Facilitates the implementation of additional network protocols.
    * **Unified message handling**: A wrapper for both **TCP** and **UDP**, providing a `SafeQueue` mechanism that centralizes messages from both protocols into a single queue.
  </Accordion>

  <Accordion title="Serialization and Compression">
    ### Serialization

    The **UDP protocol** is serialized into binary, stored in data structures optimized for the size of the data. All messages include the following structure:

    ```cpp theme={null}
    struct input_t {
        uint8_t cmd;            // Command type
        uint16_t payload_size;  // Size of the payload
        uint32_t sequence_id;   // Unique sequence ID
        std::vector<uint8_t> payload;   // Payload content
    };
    ```

    ### Compression

    All communications are compressed using the **LZ4** algorithm. Packets include a header with the following structure:

    ```cpp theme={null}
    struct compressed_header_t {
        uint32_t original_size;  // Original size of the data before compression
    };
    ```

    The **serialization process**:

    1. Prepare the data structure.
    2. Compress the data.
    3. Add the header with the original size.
    4. Transmit the packet.

    The **deserialization process**:

    1. Decompress the received data using the original size.
    2. Deserialize the data back into the appropriate structure.
  </Accordion>

  <Accordion title="Packet Reliability">
    ### Packet Duplication

    To mitigate packet loss, the network library implements a **message duplication mechanism**:

    * Each packet is sent **10 times**.
    * Upon receipt, the `sequence_id` is checked.
      * If the `sequence_id` already exists, the packet is ignored.
      * Otherwise, the corresponding command is executed.

    This ensures reliable communication even in environments with high packet loss.
  </Accordion>
</AccordionGroup>

***

<AccordionGroup>
  ## TCP Protocol

  <Accordion title="Error Format">
    Responses in case of errors follow this structure:

    ```json theme={null}
    {
        "description": "error description",
        "status": error_code
    }
    ```

    ### List of Errors

    * `400`: Invalid arguments
    * `401`: Maximum number of players reached
    * `402`: Room not found
    * `403`: Player already in lobby
    * `404`: Player is not in this lobby
    * `405`: Invalid password
    * `406`: Number of slots should be > 0 and \< 5
    * `407`: Lobby name already exists, please provide another
    * `408`: Only the owner has the right
    * `409`: Default lobby, you do not have the right
    * `410`: Only admin can launch the game
    * `411`: Some players are not ready
    * `412`: Some parameters must be numbers
    * `413`: Game already running
  </Accordion>

  <Accordion title="Commands and Responses">
    <Accordion title="1. GET_ALL_LOBBY">
      **Command:**

      ```text theme={null}
      GET_ALL_LOBBY<CLRF> ->
      ```

      **Response:**

      ```json theme={null}
      {
          "description": "successfully retrieved all lobbies",
          "status": 200,
          "rooms": [
              {
                  "room_name": "lobby_name",
                  "room_id": lobby_id,
                  "slot": nb_slot,
                  "running": is_game_running,
                  "players": [
                      {
                          "id": player_id,
                          "is_admin": is_player_admin,
                          "is_ready": is_player_ready,
                          "username": "player_username"
                      }
                  ]
              }
          ]
      }
      ```

      **Notify:** Clients that made the request.
    </Accordion>

    <Accordion title="2. JOIN">
      **Command:**

      ```text theme={null}
      JOIN<SP>${lobby_id}<CLRF> ->
      ```

      **Response:**

      ```json theme={null}
      {
          "description": "successfully joined lobby",
          "status": 202,
          "room_name": "joined_lobby_name",
          "room_id": joined_lobby_id,
          "slot": nb_slot,
          "running": is_game_running,
          "players": [
              {
                  "id": player_id,
                  "is_admin": is_player_admin,
                  "is_ready": is_player_ready,
                  "username": "player_username"
              }
          ]
      }
      ```

      **Notify:** All the clients in the joined lobby.
    </Accordion>

    <Accordion title="3. QUIT">
      **Command:**

      ```text theme={null}
      QUIT<SP>${lobby_id}<CLRF> ->
      ```

      **Response:**

      ```json theme={null}
      {
          "description": "successfully quit room",
          "status": 204,
          "player": {
              "player_id": player_id,
              "name": "username"
          },
          "players": [
              {
                  "id": player_id,
                  "is_admin": is_player_admin,
                  "is_ready": is_player_ready,
                  "username": "player_username"
              }
          ],
          "room_name": "quited_lobby_name",
          "room_id": quited_lobby_id,
          "slot": nb_slot,
          "running": is_game_running
      }
      ```

      **Notify:** All the clients in the client’s lobby.
    </Accordion>

    <Accordion title="4. SET_NEW_LOBBY">
      **Command:**

      ```text theme={null}
      SET_NEW_LOBBY<SP>${lobby_name}<SP>${slot}<SP>${password}<CLRF> ->
      ```

      **Response:**

      ```json theme={null}
      {
          "description": "successfully created lobby",
          "status": 205,
          "player": {
              "player_id": player_id,
              "name": "username"
          },
          "players": [
              {
                  "id": player_id,
                  "is_admin": is_player_admin,
                  "is_ready": is_player_ready,
                  "username": "player_username"
              }
          ],
          "room_name": "created_lobby_name",
          "room_id": created_lobby_id,
          "slot": nb_slot,
          "running": is_game_running
      }
      ```

      **Notify:** All connected clients.
    </Accordion>

    <Accordion title="5. DELETE_LOBBY">
      **Command:**

      ```text theme={null}
      DELETE_LOBBY<SP>${lobby_id}<CLRF> ->
      ```

      **Response:**

      ```json theme={null}
      {
          "description": "successfully deleted lobby",
          "status": 206,
          "room_id": deleted_lobby_id
      }
      ```

      **Notify:** All connected clients.
    </Accordion>

    <Accordion title="6. LAUNCH_GAME">
      **Command:**

      ```text theme={null}
      LAUNCH_GAME<SP>${lobby_id}<CLRF> ->
      ```

      **Response:**

      ```json theme={null}
      {
          "description": "launching game in lobby",
          "status": 207,
          "room_id": launched_lobby_id,
          "tcp_port": tcp_port,
          "udp_port": udp_port,
          "player_uuid": "player_code"
      }
      ```

      **Notify:** All the clients in the launched lobby.
    </Accordion>

    <Accordion title="7. SET_PLAYER_READY">
      **Command:**

      ```text theme={null}
      SET_PLAYER_READY<SP>${lobby_id}<CLRF> ->
      ```

      **Response:**

      ```json theme={null}
      {
          "description": "player is ready",
          "status": 208,
          "room_id": lobby_id,
          "player_id": ready_player_id
      }
      ```

      **Notify:** All the clients in the client’s lobby.
    </Accordion>

    <Accordion title="8. UPDATE_LOBBY">
      **Command:**

      ```text theme={null}
      UPDATE_LOBBY<SP>${lobby_id}<SP>${lobby_name}<SP>${slot}<SP>${password}<CLRF> ->
      ```

      **Response:**

      ```json theme={null}
      {
          "description": "successfully updated lobby",
          "status": 209,
          "room_name": "updated_lobby_name",
          "room_id": updated_lobby_id,
          "slot": nb_slot,
          "players": [
              {
                  "id": player_id,
                  "is_admin": is_player_admin,
                  "is_ready": is_player_ready,
                  "username": "player_username"
              }
          ],
          "running": is_game_running
      }
      ```

      **Notify:** All connected clients.
    </Accordion>

    <Accordion title="9. UPDATE_PERM">
      **Command:**

      ```text theme={null}
      UPDATE_PERM<SP>${lobby_id}<SP>${player_id}<SP>${new_perm}<CLRF> ->
      ```

      **Response:**

      ```json theme={null}
      {
          "description": "successfully updated permissions",
          "status": 210,
          "room_id": lobby_id,
          "player_id": target_player_id,
          "is_admin": new_permission
      }
      ```

      **Notify:** All the clients in the client’s lobby.
    </Accordion>

    <Accordion title="10. KICK_PLAYER">
      **Command:**

      ```text theme={null}
      KICK_PLAYER<SP>${lobby_id}<SP>${player_id}<CLRF> ->
      ```

      **Response:**

      ```json theme={null}
      {
          "description": "successfully kicked player",
          "status": 211,
          "room_id": lobby_id,
          "kicked_player": kicked_player_id
      }
      ```

      **Notify:** All the clients in the client’s lobby.
    </Accordion>

    <Accordion title="11. SEND_MSG">
      **Command:**

      ```text theme={null}
      SEND_MSG<SP>${lobby_id}<SP>${msg}<CLRF> ->
      ```

      **Response:**

      ```json theme={null}
      {
          "description": "message sent",
          "status": 212,
          "room_id": lobby_id,
          "from": sender_id,
          "msg": "message_content"
      }
      ```

      **Notify:** All the clients in the client’s lobby.
    </Accordion>
  </Accordion>
</AccordionGroup>

***

<AccordionGroup>
  ## UDP Protocol

  <Accordion title="Header Format">
    The **UDP packet header** is **7 bytes** long and structured as follows:

    | **Field**      | **Type**   | **Description**           |
    | -------------- | ---------- | ------------------------- |
    | `cmd`          | `uint8_t`  | Command type              |
    | `payload_size` | `uint16_t` | Size of the payload       |
    | `sequence_id`  | `uint32_t` | Sequence ID of the packet |
    | `payload`      | Variable   | Content of the payload    |

    **Example of Header Structure:**

    ```cpp theme={null}
    struct input_t {
        uint8_t cmd;            // Command type
        uint16_t payload_size;  // Size of the payload
        uint32_t sequence_id;   // Unique sequence ID
        std::vector<uint8_t> payload;   // Payload content
    };
    ```
  </Accordion>

  <Accordion title="Commands">
    <Accordion title="LOGIN (0)">
      **Command Code:** `0`

      **Structure:**

      ```cpp theme={null}
      struct login_t {
          char pwd[21];
      };
      ```

      **Description:** Used for user login with a password.
    </Accordion>

    <Accordion title="GET_POS (1)">
      **Command Code:** `1`

      **Structure:**

      ```cpp theme={null}
      struct pos_t {
          float x;
          float y;
      };
      ```

      **Description:** Retrieves the position of an entity.
    </Accordion>

    <Accordion title="SHOOT (2)">
      **Command Code:** `2`

      **Structure:**

      ```cpp theme={null}
      struct shoot_t {
          size_t size;
      };
      ```

      **Description:** Command for shooting.
    </Accordion>

    <Accordion title="SEND_POS (3)">
      **Command Code:** `3`

      **Structure:**

      ```cpp theme={null}
      struct sssend_pos_t {
          float x;
          float y;
          size_t rep;
      };
      ```

      **Description:** Sends the position of an entity.
    </Accordion>

    <Accordion title="SHOOT_ALLY (4)">
      **Command Code:** `4`

      **Structure:**

      ```cpp theme={null}
      struct shoot_ally_t {
          size_t size;
          size_t rep;
      };
      ```

      **Description:** Command for allies to shoot.
    </Accordion>

    <Accordion title="SPAWN_PLANE (5)">
      **Command Code:** `5`

      **Structure:**

      ```cpp theme={null}
      struct spawn_plane_t {
          size_t rep;
          float x;
          float y;
      };
      ```

      **Description:** Spawns a plane entity.
    </Accordion>

    <Accordion title="SPAWN_CRAB (6)">
      **Command Code:** `6`

      **Structure:**

      ```cpp theme={null}
      struct spawn_crab_t {
          size_t rep;
          float x;
          float y;
      };
      ```

      **Description:** Spawns a crab entity.
    </Accordion>

    <Accordion title="SPAWN_ROBOT (7)">
      **Command Code:** `7`

      **Structure:**

      ```cpp theme={null}
      struct spawn_robot_t {
          size_t rep;
          float x;
          float y;
      };
      ```

      **Description:** Spawns a robot entity.
    </Accordion>

    <Accordion title="SPAWN_BOSS (8)">
      **Command Code:** `8`

      **Structure:**

      ```cpp theme={null}
      struct spawn_boss_t {
          size_t rep;
          float x;
          float y;
      };
      ```

      **Description:** Spawns a boss entity.
    </Accordion>

    <Accordion title="KILL_MONSTER (9)">
      **Command Code:** `9`

      **Structure:**

      ```cpp theme={null}
      struct kill_monster_t {
          size_t rep;
      };
      ```

      **Description:** Kills a monster entity.
    </Accordion>

    <Accordion title="PLANE_SHOOT (10)">
      **Command Code:** `10`

      **Structure:**

      ```cpp theme={null}
      struct plane_shoot_t {
          size_t rep;
          float vx;
          float vy;
      };
      ```

      **Description:** Plane shoots with a given direction.
    </Accordion>

    <Accordion title="CRAB_NEW_DIR (11)">
      **Command Code:** `11`

      **Structure:**

      ```cpp theme={null}
      struct crab_new_dir_t {
          size_t rep;
          float vx;
          float vy;
          float x;
          float y;
      };
      ```

      **Description:** Changes the direction of a crab entity.
    </Accordion>

    <Accordion title="ROBOT_NEW_DIR (12)">
      **Command Code:** `12`

      **Structure:**

      ```cpp theme={null}
      struct robot_new_dir_t {
          size_t rep;
          float vx;
          float vy;
          float x;
          float y;
      };
      ```

      **Description:** Changes the direction of a robot entity.
    </Accordion>

    <Accordion title="ROBOT_SHOOT (13)">
      **Command Code:** `13`

      **Structure:**

      ```cpp theme={null}
      struct robot_shoot_t {
          size_t rep;
          float x;
          float y;
      };
      ```

      **Description:** Robot shoots.
    </Accordion>

    <Accordion title="BOSS_SHOOT (14)">
      **Command Code:** `14`

      **Structure:**

      ```cpp theme={null}
      struct boss_shoot_t {
          size_t rep;
      };
      ```

      **Description:** Boss shoots.
    </Accordion>

    <Accordion title="ALLY_UPDATE_HP (15)">
      **Command Code:** `15`

      **Structure:**

      ```cpp theme={null}
      struct ally_update_hp_t {
          size_t rep;
          int hp;
      };
      ```

      **Description:** Updates the health points of an ally.
    </Accordion>

    <Accordion title="UPDATE_HP (16)">
      **Command Code:** `16`

      **Structure:**

      ```cpp theme={null}
      struct update_hp_t {
          int hp;
      };
      ```

      **Description:** Updates the health points of an entity.
    </Accordion>

    <Accordion title="KILL_ALLY (17)">
      **Command Code:** `17`

      **Structure:**

      ```cpp theme={null}
      struct kill_ally_t {
          size_t rep;
      };
      ```

      **Description:** Kills an ally entity.
    </Accordion>

    <Accordion title="KILL (18)">
      **Command Code:** `18`

      **Structure:**

      ```cpp theme={null}
      struct kill_t {
          int id;
      };
      ```

      **Description:** Kills an entity by ID.
    </Accordion>
  </Accordion>
</AccordionGroup>

***

## Summary Table

### **TCP Commands**

| **Command**                 | **Description**                | **Response Codes** |
| --------------------------- | ------------------------------ | ------------------ |
| `GET_ALL_LOBBY<CLRF>`       | Retrieve all available lobbies | `200`              |
| `JOIN<SP>${Lobby_id}<CLRF>` | Join a specific lobby          | `202`              |
| `QUIT<SP>${Lobby_id}<CLRF>` | Quit a specific lobby          | `204`              |
| `SET_NEW_LOBBY<SP>...`      | Create a new lobby             | `205`              |
| `DELETE_LOBBY<SP>...`       | Delete a lobby                 | `206`              |
| `LAUNCH_GAME<SP>...`        | Launch the game in the lobby   | `207`              |
| `SET_PLAYER_READY<SP>...`   | Set a player as ready          | `208`              |
| `UPDATE_LOBBY<SP>...`       | Update the lobby               | `209`              |
| `UPDATE_PERM<SP>...`        | Update player permissions      | `210`              |
| `KICK_PLAYER<SP>...`        | Kick a player from the lobby   | `211`              |
| `SEND_MSG<SP>...`           | Send a message in the lobby    | `212`              |

### **UDP Commands**

| **Command**      | **Description**            | **Parameters**                                     |
| ---------------- | -------------------------- | -------------------------------------------------- |
| `LOGIN`          | Used for user login        | `char pwd[21]`                                     |
| `GET_POS`        | Retrieves entity position  | `float x, float y`                                 |
| `SHOOT`          | Shooting command           | `size_t size`                                      |
| `SEND_POS`       | Sends entity position      | `float x, float y, size_t rep`                     |
| `SHOOT_ALLY`     | Ally shooting command      | `size_t size, size_t rep`                          |
| `SPAWN_PLANE`    | Spawns a plane entity      | `size_t rep, float x, float y`                     |
| `SPAWN_CRAB`     | Spawns a crab entity       | `size_t rep, float x, float y`                     |
| `SPAWN_ROBOT`    | Spawns a robot entity      | `size_t rep, float x, float y`                     |
| `SPAWN_BOSS`     | Spawns a boss entity       | `size_t rep, float x, float y`                     |
| `KILL_MONSTER`   | Kills a monster entity     | `size_t rep`                                       |
| `PLANE_SHOOT`    | Plane shooting command     | `size_t rep, float vx, float vy`                   |
| `CRAB_NEW_DIR`   | Changes crab direction     | `size_t rep, float vx, float vy, float x, float y` |
| `ROBOT_NEW_DIR`  | Changes robot direction    | `size_t rep, float vx, float vy, float x, float y` |
| `ROBOT_SHOOT`    | Robot shooting command     | `size_t rep, float x, float y`                     |
| `BOSS_SHOOT`     | Boss shooting command      | `size_t rep`                                       |
| `ALLY_UPDATE_HP` | Updates ally health points | `size_t rep, int hp`                               |
| `UPDATE_HP`      | Updates entity health      | `int hp`                                           |
| `KILL_ALLY`      | Kills an ally entity       | `size_t rep`                                       |
| `KILL`           | Kills an entity by ID      | `int id`                                           |

***

## Conclusion

The **TCP Protocol** ensures reliable communication for operations such as joining lobbies, retrieving information, and launching games. The **UDP Protocol** is optimized for speed and lightweight packet delivery, making it ideal for real-time updates.

Together, these protocols provide a robust and efficient foundation for network communication in the **R-Type project**.

***
