1 Commits

Author SHA1 Message Date
98fcb30f68 update color interface
All checks were successful
Linux arm64 / Build (push) Successful in 24m2s
2024-04-09 19:19:51 +02:00
72 changed files with 182 additions and 2156 deletions

View File

@@ -10,7 +10,7 @@ jobs:
- name: Install deps - name: Install deps
run : | run : |
apt update apt update
apt install -y libsdl2-dev libassimp-dev libglew-dev apt install -y libsdl2-dev libassimp-dev libglew-dev
- name: Check out repository code - name: Check out repository code
uses: actions/checkout@v3 uses: actions/checkout@v3
@@ -22,19 +22,11 @@ jobs:
actions-cache-folder: '.xmake-cache' actions-cache-folder: '.xmake-cache'
actions-cache-key: 'ubuntu' actions-cache-key: 'ubuntu'
- name: Calc deps hash
uses: seepine/hash-files@v1
id: get-hash
with:
patterns: |
**/xmake.lua
**/xmake/*.lua
- name: Packages cache - name: Packages cache
uses: actions/cache@v4 uses: actions/cache@v4
with: with:
path: ~/.xmake path: ~/.xmake
key: ${{ runner.os }}-${{ steps.get-hash.outputs.hash }} key: 'ubuntu-packages'
- name: XMake config - name: XMake config
run: xmake f -p linux -y --root run: xmake f -p linux -y --root
@@ -43,4 +35,4 @@ jobs:
run: xmake --root run: xmake --root
- name: Test - name: Test
run: xmake test --root run: xmake test --root

Binary file not shown.

View File

@@ -7,10 +7,10 @@
#include <algorithm> #include <algorithm>
#include <cassert> #include <cassert>
#include <cstdint>
#include <cstring> #include <cstring>
#include <string> #include <string>
#include <vector> #include <vector>
#include <cstdint>
namespace blitz { namespace blitz {
@@ -40,31 +40,21 @@ class DataBuffer {
DataBuffer& operator=(const DataBuffer& other); DataBuffer& operator=(const DataBuffer& other);
DataBuffer& operator=(DataBuffer&& other); DataBuffer& operator=(DataBuffer&& other);
/**
* \brief Append data to the buffer
*/
template <typename T> template <typename T>
void Append(const T& data) { void Append(const T& data) {
std::size_t size = sizeof(data); std::size_t size = sizeof(data);
std::size_t end_pos = m_Buffer.size(); std::size_t end_pos = m_Buffer.size();
m_Buffer.resize(m_Buffer.size() + size); m_Buffer.resize(m_Buffer.size() + size);
std::memcpy(&m_Buffer[end_pos], &data, size); memcpy(&m_Buffer[end_pos], &data, size);
} }
/**
* \brief Append data to the buffer
*/
template <typename T> template <typename T>
DataBuffer& operator<<(const T& data) { DataBuffer& operator<<(const T& data) {
Append(data); Append(data);
return *this; return *this;
} }
/** // don't use it for binary data !
* \brief Append a string to the buffer
* \warning Don't use it for binary data !
* \param str The string to append
*/
DataBuffer& operator<<(const std::string& str) { DataBuffer& operator<<(const std::string& str) {
std::size_t strlen = str.length() + 1; // including null character std::size_t strlen = str.length() + 1; // including null character
Resize(GetSize() + strlen); Resize(GetSize() + strlen);
@@ -72,18 +62,16 @@ class DataBuffer {
return *this; return *this;
} }
/** DataBuffer& operator<<(DataBuffer& data) {
* \brief Append data to the buffer from another const buffer m_Buffer.insert(m_Buffer.end(), data.begin(), data.end());
* \param data The buffer to append return *this;
*/ }
DataBuffer& operator<<(const DataBuffer& data) { DataBuffer& operator<<(const DataBuffer& data) {
m_Buffer.insert(m_Buffer.end(), data.begin(), data.end()); m_Buffer.insert(m_Buffer.end(), data.begin(), data.end());
return *this; return *this;
} }
/**
* \brief Read some data from the buffer and assign to desired variable
*/
template <typename T> template <typename T>
DataBuffer& operator>>(T& data) { DataBuffer& operator>>(T& data) {
assert(m_ReadOffset + sizeof(T) <= GetSize()); assert(m_ReadOffset + sizeof(T) <= GetSize());
@@ -92,10 +80,6 @@ class DataBuffer {
return *this; return *this;
} }
/**
* \brief Read some data from the buffer and assign to the new buffer
* \param data The buffer to assign
*/
DataBuffer& operator>>(DataBuffer& data) { DataBuffer& operator>>(DataBuffer& data) {
data.Resize(GetSize() - m_ReadOffset); data.Resize(GetSize() - m_ReadOffset);
std::copy(m_Buffer.begin() + static_cast<difference_type>(m_ReadOffset), m_Buffer.end(), data.begin()); std::copy(m_Buffer.begin() + static_cast<difference_type>(m_ReadOffset), m_Buffer.end(), data.begin());
@@ -103,11 +87,7 @@ class DataBuffer {
return *this; return *this;
} }
/** // Don't use it for binary data !
* \brief Read a string from the buffer
* \param str The string to assign in the new buffer
* \warning Don't use it for binary data !
*/
DataBuffer& operator>>(std::string& str) { DataBuffer& operator>>(std::string& str) {
std::size_t stringSize = std::size_t stringSize =
strlen(reinterpret_cast<const char*>(m_Buffer.data()) + m_ReadOffset) + 1; // including null character strlen(reinterpret_cast<const char*>(m_Buffer.data()) + m_ReadOffset) + 1; // including null character
@@ -118,55 +98,30 @@ class DataBuffer {
return *this; return *this;
} }
/**
* \brief Write some data to the buffer
* \param buffer The buffer to write
* \param amount The amount of data to write
*/
void WriteSome(const char* buffer, std::size_t amount) { void WriteSome(const char* buffer, std::size_t amount) {
std::size_t end_pos = m_Buffer.size(); std::size_t end_pos = m_Buffer.size();
m_Buffer.resize(m_Buffer.size() + amount); m_Buffer.resize(m_Buffer.size() + amount);
std::memcpy(m_Buffer.data() + end_pos, buffer, amount); memcpy(m_Buffer.data() + end_pos, buffer, amount);
} }
/**
* \brief Write some data to the buffer
* \param buffer The buffer to write
* \param amount The amount of data to write
*/
void WriteSome(const std::uint8_t* buffer, std::size_t amount) { void WriteSome(const std::uint8_t* buffer, std::size_t amount) {
std::size_t end_pos = m_Buffer.size(); std::size_t end_pos = m_Buffer.size();
m_Buffer.resize(m_Buffer.size() + amount); m_Buffer.resize(m_Buffer.size() + amount);
std::memcpy(m_Buffer.data() + end_pos, buffer, amount); memcpy(m_Buffer.data() + end_pos, buffer, amount);
} }
/**
* \brief Read some data from the buffer
* \param buffer The buffer to Read
* \param amount The amount of data from the buffer
*/
void ReadSome(char* buffer, std::size_t amount) { void ReadSome(char* buffer, std::size_t amount) {
assert(m_ReadOffset + amount <= GetSize()); assert(m_ReadOffset + amount <= GetSize());
std::copy_n(m_Buffer.begin() + static_cast<difference_type>(m_ReadOffset), amount, buffer); std::copy_n(m_Buffer.begin() + static_cast<difference_type>(m_ReadOffset), amount, buffer);
m_ReadOffset += amount; m_ReadOffset += amount;
} }
/**
* \brief Read some data from the buffer
* \param buffer The buffer to Read
* \param amount The amount of data from the buffer
*/
void ReadSome(std::uint8_t* buffer, std::size_t amount) { void ReadSome(std::uint8_t* buffer, std::size_t amount) {
assert(m_ReadOffset + amount <= GetSize()); assert(m_ReadOffset + amount <= GetSize());
std::copy_n(m_Buffer.begin() + static_cast<difference_type>(m_ReadOffset), amount, buffer); std::copy_n(m_Buffer.begin() + static_cast<difference_type>(m_ReadOffset), amount, buffer);
m_ReadOffset += amount; m_ReadOffset += amount;
} }
/**
* \brief Read some data from the buffer
* \param buffer The buffer to Read
* \param amount The amount of data from the buffer
*/
void ReadSome(DataBuffer& buffer, std::size_t amount) { void ReadSome(DataBuffer& buffer, std::size_t amount) {
assert(m_ReadOffset + amount <= GetSize()); assert(m_ReadOffset + amount <= GetSize());
buffer.Resize(amount); buffer.Resize(amount);
@@ -174,113 +129,64 @@ class DataBuffer {
m_ReadOffset += amount; m_ReadOffset += amount;
} }
/**
* \brief Resize the buffer
* \param size The new size of the buffer
*/
void Resize(std::size_t size) { void Resize(std::size_t size) {
m_Buffer.resize(size); m_Buffer.resize(size);
} }
/**
* \brief Reserve some space in the buffer
* \param amount The amount of space to reserve
*/
void Reserve(std::size_t amount) { void Reserve(std::size_t amount) {
m_Buffer.reserve(amount); m_Buffer.reserve(amount);
} }
void erase(iterator it) {
m_Buffer.erase(it);
}
/**
* \brief Clear the buffer
*/
void Clear() { void Clear() {
m_Buffer.clear(); m_Buffer.clear();
m_ReadOffset = 0; m_ReadOffset = 0;
} }
/**
* \brief When the buffer has been read entirely
*/
bool IsFinished() const { bool IsFinished() const {
return m_ReadOffset >= m_Buffer.size(); return m_ReadOffset >= m_Buffer.size();
} }
/**
* \brief Get the buffer data
*/
std::uint8_t* data() { std::uint8_t* data() {
return m_Buffer.data(); return m_Buffer.data();
} }
/**
* \brief Get the buffer data
*/
const std::uint8_t* data() const { const std::uint8_t* data() const {
return m_Buffer.data(); return m_Buffer.data();
} }
/**
* \brief Get the read offset
*/
std::size_t GetReadOffset() const { std::size_t GetReadOffset() const {
return m_ReadOffset; return m_ReadOffset;
} }
/**
* \brief Set the read offset
* \param pos The new read offset
*/
void SetReadOffset(std::size_t pos); void SetReadOffset(std::size_t pos);
/**
* \brief Get the size of the buffer
*/
std::size_t GetSize() const; std::size_t GetSize() const;
/**
* \brief Get the remaining size of the buffer
*/
std::size_t GetRemaining() const; std::size_t GetRemaining() const;
/** iterator begin();
* \brief Read a file into the buffer iterator end();
* \param fileName The name of the file to read const_iterator begin() const;
*/ const_iterator end() const;
bool ReadFile(const std::string& fileName);
/** bool ReadFile(const std::string& fileName);
* \brief Write a file into the buffer
* \param fileName The name of the file to write to
*/
bool WriteFile(const std::string& fileName); bool WriteFile(const std::string& fileName);
/** // Don't forget to free the data !
* \brief Allocate the buffer on the heap
* \warning Don't forget to free the data !
*/
std::uint8_t* HeapAllocatedData() const { std::uint8_t* HeapAllocatedData() const {
std::uint8_t* newBuffer = new std::uint8_t[GetSize()]; std::uint8_t* newBuffer = new std::uint8_t[GetSize()];
std::memcpy(newBuffer, data(), GetSize()); std::memcpy(newBuffer, data(), GetSize());
return newBuffer; return newBuffer;
} }
/** bool operator==(const DataBuffer& other) const{
* \brief Operator == to compare two DataBuffer
*/
bool operator==(const DataBuffer& other) const {
return m_Buffer == other.m_Buffer; return m_Buffer == other.m_Buffer;
} }
iterator begin();
iterator end();
const_iterator begin() const;
const_iterator end() const;
}; };
/**
* \brief Operator << to write a DataBuffer to an ostream
*/
std::ostream& operator<<(std::ostream& os, const DataBuffer& buffer); std::ostream& operator<<(std::ostream& os, const DataBuffer& buffer);
} // namespace blitz } // namespace blitz

View File

@@ -1,17 +1,7 @@
#pragma once #pragma once
/**
* \file NonCopyable.h
* \brief File containing the blitz::NonCopyable class
*/
namespace blitz { namespace blitz {
/**
* \class NonCopyable
* \brief Class used to make a class non copyable
* \note Inherit from this class privately to make a class non copyable
*/
class NonCopyable { class NonCopyable {
public: public:
NonCopyable(const NonCopyable&) = delete; NonCopyable(const NonCopyable&) = delete;

View File

@@ -1,10 +1,5 @@
#pragma once #pragma once
/**
* \file VarInt.h
* \brief File containing the blitz::VarInt class
*/
#include <cstddef> #include <cstddef>
#include <cstdint> #include <cstdint>
@@ -12,46 +7,21 @@ namespace blitz {
class DataBuffer; class DataBuffer;
/**
* \class VarInt
* \brief Variable-length format such that smaller numbers use fewer bytes.
*/
class VarInt { class VarInt {
private: private:
std::uint64_t m_Value; std::uint64_t m_Value;
public: public:
VarInt() : m_Value(0) {} VarInt() : m_Value(0) {}
/**
* \brief Construct a variable integer from a value
* \param value The value of the variable integer
*/
VarInt(std::uint64_t value) : m_Value(value) {} VarInt(std::uint64_t value) : m_Value(value) {}
/**
* \brief Get the value of the variable integer
*/
std::uint64_t GetValue() const { std::uint64_t GetValue() const {
return m_Value; return m_Value;
} }
/**
* \brief Get the length of the serialized variable integer
*/
std::size_t GetSerializedLength() const; std::size_t GetSerializedLength() const;
/**
* \brief Serialize the variable integer
* \param out The buffer to write the serialized variable integer to
* \param var The variable integer to serialize
*/
friend DataBuffer& operator<<(DataBuffer& out, const VarInt& var); friend DataBuffer& operator<<(DataBuffer& out, const VarInt& var);
/**
* \brief Deserialize the variable integer
* \param in The buffer to read the serialized variable integer from
* \param var The variable integer to deserialize
*/
friend DataBuffer& operator>>(DataBuffer& in, VarInt& var); friend DataBuffer& operator>>(DataBuffer& in, VarInt& var);
}; };

View File

@@ -1,10 +1,5 @@
#pragma once #pragma once
/**
* \file Game.h
* \brief File containing the blitz::game::Game class
*/
#include "Player.h" #include "Player.h"
#include "blitz/misc/Time.h" #include "blitz/misc/Time.h"
#include <map> #include <map>
@@ -12,43 +7,21 @@
namespace blitz { namespace blitz {
namespace game { namespace game {
/**
* \typedef PlayerMap
* \brief A map of players
*/
typedef std::map<PlayerID, Player> PlayerMap; typedef std::map<PlayerID, Player> PlayerMap;
/**
* \enum GameState
* \brief The states of the game
*/
enum GameState : std::uint8_t { enum GameState : std::uint8_t {
gsNone = 0, /**< Default state */ gsNone = 0,
gsWaiting, /**< Waiting state if the number of players is less than 2 */ gsWaiting,
gsPreparing, /**< Preparing state until the game start */ gsPreparing,
gsGame, /**< Game state during the players can shoot and kill ... */ gsGame,
gsEnd, /**< End state of the game : show the winner of the game and the leaderboard*/ gsEnd,
}; };
/**
* \brief The game configuration
* \struct GameConfig
*/
struct GameConfig { struct GameConfig {
/**
* \brief The gravity applied to players
*/
float Gravity; float Gravity;
/**
* \brief The firing rate of the shoot in RPM (round per minute)
*/
int FiringRate; int FiringRate;
}; };
/**
* \class Game
* \brief Class representing a game
*/
class Game { class Game {
protected: protected:
PlayerMap m_Players; PlayerMap m_Players;
@@ -57,85 +30,36 @@ class Game {
GameConfig m_Config; GameConfig m_Config;
public: public:
/** \brief Default constructor */
Game() : m_GameState(gsNone) {} Game() : m_GameState(gsNone) {}
/**
* \brief Update the game with a delta time
* \param delta The time elapsed since the last update in milliseconds
*/
virtual void Tick(std::uint64_t delta) = 0; virtual void Tick(std::uint64_t delta) = 0;
/**
* \brief Get a player by its identifier
* \param id The identifier of the player
* \return The player if found, nullptr otherwise
*/
Player* GetPlayerById(PlayerID id); Player* GetPlayerById(PlayerID id);
/**
* \brief Get a player by its identifier (const version)
* \param id The identifier of the player
* \return The player if found, nullptr otherwise
*/
const Player* GetPlayerById(PlayerID id) const; const Player* GetPlayerById(PlayerID id) const;
/**
* \brief Get the players
* \return The map of players
*/
PlayerMap& GetPlayers() { PlayerMap& GetPlayers() {
return m_Players; return m_Players;
} }
/**
* \brief Get the players (const version)
* \return The map of players
*/
const PlayerMap& GetPlayers() const { const PlayerMap& GetPlayers() const {
return m_Players; return m_Players;
} }
/**
* \brief Get the game state
* \return The game state
*/
GameState GetGameState() const { GameState GetGameState() const {
return m_GameState; return m_GameState;
} }
/**
* \brief Load the game configuration
* \param config The game configuration to load
*/
void LoadConfig(const GameConfig& config) { void LoadConfig(const GameConfig& config) {
m_Config = config; m_Config = config;
} }
/**
* \brief Get the game configuration
* \return The game configuration
*/
const game::GameConfig& GetGameConfig() const { const game::GameConfig& GetGameConfig() const {
return m_Config; return m_Config;
} }
/**
* \brief Add a player to the game
* \param player The identifier of the player
* \param name The name of the player
*/
virtual void AddPlayer(PlayerID player, const std::string& name); virtual void AddPlayer(PlayerID player, const std::string& name);
/**
* \brief Remove a player from the game
* \param player The identifier of the player
*/
virtual void RemovePlayer(PlayerID player); virtual void RemovePlayer(PlayerID player);
/**
* \brief Get the remaining time of the game
* \return The remaining time of the game in milliseconds
*/
std::uint64_t GetGameStateRemainingTime() const { std::uint64_t GetGameStateRemainingTime() const {
return m_GameTimer.GetTimeRemaining(); return m_GameTimer.GetTimeRemaining();
} }

View File

@@ -1,45 +1,21 @@
#pragma once #pragma once
/**
* \file LeaderBoard.h
* \brief File containing the blitz::game::LeaderBoard class
*/
#include "blitz/game/Player.h" #include "blitz/game/Player.h"
#include <vector> #include <vector>
namespace blitz { namespace blitz {
namespace game { namespace game {
/**
* \class LeaderBoard
* \brief The leaderboard of the game
*/
class LeaderBoard { class LeaderBoard {
private: private:
std::vector<Player*> m_Players; std::vector<Player*> m_Players;
public: public:
/**
* \brief Add a player to the leaderboard
* \param player The player to add
*/
void AddPlayer(Player* player); void AddPlayer(Player* player);
/**
* \brief Remove a player from the leaderboard
* \param player The player to remove
*/
void RemovePlayer(PlayerID player); void RemovePlayer(PlayerID player);
/**
* \brief Update the leaderboard
*/
void Update(); void Update();
/**
* \brief Get the players in the leaderboard ordered by kills
* \return The players
*/
const std::vector<Player*>& GetPlayers() const { const std::vector<Player*>& GetPlayers() const {
return m_Players; return m_Players;
} }

View File

@@ -13,6 +13,7 @@ typedef std::vector<ColoredPart> ColoredText;
} // namespace protocol } // namespace protocol
namespace game { namespace game {
class PlayerInputListener { class PlayerInputListener {
@@ -27,8 +28,6 @@ class ClientListener {
virtual void OnSpectatorChange(game::PlayerID player) {} virtual void OnSpectatorChange(game::PlayerID player) {}
virtual void OnPlayerShoot(PlayerID player, const Vec3f& position, float yaw, float pitch) {} virtual void OnPlayerShoot(PlayerID player, const Vec3f& position, float yaw, float pitch) {}
virtual void OnGameConfigUpdate() {} virtual void OnGameConfigUpdate() {}
virtual void OnGameJoin() {}
virtual void OnGameLeave() {}
}; };
} // namespace game } // namespace game

View File

@@ -1,10 +1,5 @@
#pragma once #pragma once
/**
* \file Player.h
* \brief File containing the blitz::game::Player class
*/
#include "blitz/common/Defines.h" #include "blitz/common/Defines.h"
#include "blitz/maths/Vector.h" #include "blitz/maths/Vector.h"
#include <cstdint> #include <cstdint>
@@ -13,33 +8,13 @@
namespace blitz { namespace blitz {
namespace game { namespace game {
/**
* \struct PlayerStats
* \brief The statistics of a player
*/
struct PlayerStats { struct PlayerStats {
/**
* \brief The number of deaths
*/
std::uint16_t m_Deaths; std::uint16_t m_Deaths;
/**
* \brief The number of kills
*/
std::uint16_t m_Kills; std::uint16_t m_Kills;
/**
* \brief The number of shots
*/
std::uint32_t m_ShootCount; std::uint32_t m_ShootCount;
/**
* \brief The number of successful shots
*/
std::uint32_t m_ShootSuccessCount; std::uint32_t m_ShootSuccessCount;
}; };
/**
* \class Player
* \brief The player of the game
*/
class Player { class Player {
private: private:
PlayerID m_ID; PlayerID m_ID;
@@ -50,173 +25,94 @@ class Player {
float m_Pitch; float m_Pitch;
float m_HP; float m_HP;
bool m_IsBot; bool m_IsBot;
PlayerStats m_Stats{};
public: public:
/**
* \brief Default constructor
* \param id The ID of the player
*/
Player(PlayerID id) : m_ID(id), m_Yaw(0), m_Pitch(0), m_HP(100), m_IsBot(false) {} Player(PlayerID id) : m_ID(id), m_Yaw(0), m_Pitch(0), m_HP(100), m_IsBot(false) {}
PlayerStats m_Stats{};
/**
* \brief Get the ID of the player
* \return The ID of the player
*/
PlayerID GetID() const { PlayerID GetID() const {
return m_ID; return m_ID;
} }
/**
* \brief Get the name of the player
* \return The name of the player
*/
const std::string& GetName() const { const std::string& GetName() const {
return m_Name; return m_Name;
} }
/**
* \brief Set the name of the player
* \param name The name of the player
*/
void SetName(const std::string& name) { void SetName(const std::string& name) {
m_Name = name; m_Name = name;
} }
/**
* \brief Get the position of the player
* \return The position of the player
*/
const Vec3f& GetPosition() const { const Vec3f& GetPosition() const {
return m_Position; return m_Position;
} }
/**
* \brief Set the position of the player
* \param newPos The new position of the player
*/
void SetPosition(const Vec3f& newPos) { void SetPosition(const Vec3f& newPos) {
m_Position = newPos; m_Position = newPos;
} }
/**
* \brief Add a position to the player
* \param dPos The position to add
*/
void AddPosition(const Vec3f& dPos) { void AddPosition(const Vec3f& dPos) {
m_Position += dPos; m_Position += dPos;
} }
/**
* \brief Get the velocity of the player
* \return The velocity of the player
*/
const Vec3f& GetVelocity() const { const Vec3f& GetVelocity() const {
return m_Velocity; return m_Velocity;
} }
/**
* \brief Set the velocity of the player
* \param newVelocity The new velocity of the player
*/
void SetVelocity(const Vec3f& newVelocity) { void SetVelocity(const Vec3f& newVelocity) {
m_Velocity = newVelocity; m_Velocity = newVelocity;
} }
/**
* \brief Get the yaw of the player
* \return The yaw of the player in radians
*/
float GetYaw() const { float GetYaw() const {
return m_Yaw; return m_Yaw;
} }
/**
* \brief Set the yaw of the player
* \param yaw The yaw of the player in radians
*/
void SetYaw(float yaw) { void SetYaw(float yaw) {
m_Yaw = yaw; m_Yaw = yaw;
} }
/**
* \brief Add a yaw to the player
* \param dYaw The yaw to add in radians
*/
void AddYaw(float dYaw) { void AddYaw(float dYaw) {
m_Yaw += dYaw; m_Yaw += dYaw;
} }
/**
* \brief Get the pitch of the player
* \return The pitch of the player in radians
*/
float GetPitch() const { float GetPitch() const {
return m_Pitch; return m_Pitch;
} }
/**
* \brief Set the pitch of the player
* \param pitch The pitch of the player in radians
*/
void SetPitch(float pitch) { void SetPitch(float pitch) {
m_Pitch = pitch; m_Pitch = pitch;
} }
/**
* \brief Add a pitch to the player
* \param dPitch The pitch to add in radians
*/
void AddPitch(float dPitch) { void AddPitch(float dPitch) {
m_Pitch += dPitch; m_Pitch += dPitch;
} }
/**
* \brief Get the HP of the player
* \return The HP of the player
*/
float GetHP() const { float GetHP() const {
return m_HP; return m_HP;
} }
/**
* \brief Set the HP of the player
* \param hp The HP of the player
*/
void SetHP(float hp) { void SetHP(float hp) {
m_HP = hp; m_HP = hp;
} }
/**
* \brief When the player is a bot
* \return True if the player is a bot
*/
bool IsBot() const { bool IsBot() const {
return m_IsBot; return m_IsBot;
} }
/**
* \brief Set the player as a bot
*/
void SetBot() { void SetBot() {
m_IsBot = true; m_IsBot = true;
} }
/**
* \brief Get the statistics of the player (const version)
* \return The statistics of the player
*/
const PlayerStats& GetStats() const { const PlayerStats& GetStats() const {
return m_Stats; return m_Stats;
} }
/**
* \brief Get the statistics of the player
* \return The statistics of the player
*/
PlayerStats& GetStats() { PlayerStats& GetStats() {
return m_Stats; return m_Stats;
} }
void SetStats(const PlayerStats& stats) {
m_Stats = stats;
}
}; };

View File

@@ -1,10 +1,5 @@
#pragma once #pragma once
/**
* \file Maths.h
* \brief File containing mathematical functions and constants
*/
#include "blitz/maths/Vector.h" #include "blitz/maths/Vector.h"
#include <cmath> #include <cmath>
@@ -13,19 +8,18 @@ namespace maths {
static constexpr float PI = 3.141592653f; static constexpr float PI = 3.141592653f;
/**
* \return the amount of overlap between the ranges [a1 ; b1] and [a2 ; b2]
*/
template <typename T> template <typename T>
/**
* @brief returns the amount of overlap between the ranges [a1 ; b1] and [a2 ; b2]
*/
T RangesOverlap(T& a1, T& b1, T& a2, T& b2) { T RangesOverlap(T& a1, T& b1, T& a2, T& b2) {
return std::min(std::max(a1, b1), std::max(a2, b2)) - std::max(std::min(a1, b1), std::min(a2, b2)); return std::min(std::max(a1, b1), std::max(a2, b2)) - std::max(std::min(a1, b1), std::min(a2, b2));
} }
/**
* \return whether the ranges [a1 ; b1] and [a2 ; b2] overlap
*/
template <typename T> template <typename T>
/**
* @brief returns whether the ranges [a1 ; b1] and [a2 ; b2] overlap
*/
bool RangesOverlapping(T& a1, T& b1, T& a2, T& b2) { bool RangesOverlapping(T& a1, T& b1, T& a2, T& b2) {
return RangesOverlap(a1, a2, b1, b2) >= 0; return RangesOverlap(a1, a2, b1, b2) >= 0;
} }
@@ -34,19 +28,11 @@ bool RangesOverlapping(T& a1, T& b1, T& a2, T& b2) {
// Vectors // // Vectors //
////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////
/**
* \brief Returns the length of the vector
* \return the length of the vector
*/
template <typename T> template <typename T>
T Length(const Vec3<T>& vect) { T Length(const Vec3<T>& vect) {
return std::sqrt(vect.x * vect.x + vect.y * vect.y + vect.z * vect.z); return std::sqrt(vect.x * vect.x + vect.y * vect.y + vect.z * vect.z);
} }
/**
* \brief Normalizes the vector
* \return the normalized vector
*/
template <typename T> template <typename T>
Vec3<T> Normalize(const Vec3<T>& vect) { Vec3<T> Normalize(const Vec3<T>& vect) {
T length = Length(vect); T length = Length(vect);
@@ -54,10 +40,6 @@ Vec3<T> Normalize(const Vec3<T>& vect) {
return {vect.x / length, vect.y / length, vect.z / length}; return {vect.x / length, vect.y / length, vect.z / length};
} }
/**
* \brief Normalizes the vector
* \return the normalized vector
*/
template <typename T> template <typename T>
Vec4<T> Normalize(const Vec4<T>& vect) { Vec4<T> Normalize(const Vec4<T>& vect) {
T length = std::sqrt(vect.x * vect.x + vect.y * vect.y + vect.z * vect.z + vect.w * vect.w); T length = std::sqrt(vect.x * vect.x + vect.y * vect.y + vect.z * vect.z + vect.w * vect.w);
@@ -65,19 +47,11 @@ Vec4<T> Normalize(const Vec4<T>& vect) {
return {vect.x / length, vect.y / length, vect.z / length, vect.w / length}; return {vect.x / length, vect.y / length, vect.z / length, vect.w / length};
} }
/**
* \brief Returns the dot product of the two vectors
* \return the dot product of the two vectors
*/
template <typename T> template <typename T>
T Dot(const Vec3<T>& vect, const Vec3<T>& other) { T Dot(const Vec3<T>& vect, const Vec3<T>& other) {
return vect.x * other.x + vect.y * other.y + vect.z * other.z; return vect.x * other.x + vect.y * other.y + vect.z * other.z;
} }
/**
* \brief Returns the cross product of the two vectors
* \return the cross product of the two vectors
*/
template <typename T> template <typename T>
Vec3<T> Cross(const Vec3<T>& vect, const Vec3<T>& other) { Vec3<T> Cross(const Vec3<T>& vect, const Vec3<T>& other) {
return { return {
@@ -87,46 +61,35 @@ Vec3<T> Cross(const Vec3<T>& vect, const Vec3<T>& other) {
}; };
} }
/**
* \brief Returns the dot product of the two vectors
* \return the dot product of the two vectors
*/
template <typename T> template <typename T>
T Dot(const Vec4<T>& vect, const Vec4<T>& other) { T Dot(const Vec4<T>& vect, const Vec4<T>& other) {
return vect.x * other.x + vect.y * other.y + vect.z * other.z + vect.w * other.w; return vect.x * other.x + vect.y * other.y + vect.z * other.z + vect.w * other.w;
} }
/**
* \brief Returns the distance between the two vectors
* \return the distance between the two vectors
*/
template <typename T> template <typename T>
T Distance(const Vec3<T>& vect, const Vec3<T>& other) { T Distance(const Vec3<T>& vect, const Vec3<T>& other) {
return Length(vect - other); return Length(vect - other);
} }
/** // it seems that `std::{min, max}`'s behavior conflicts with that of `cmath`'s `f{min, max}[f]`
* \brief Returns the minimum of the three coordinates of the vector // Why? Like I fucking know dude
* \return the minimum between the three coordinates of the vector
*/
template <typename T> template <typename T>
T ReduceMin(const Vec3<T>& vect) { T ReduceMin(const Vec3<T>& vect) {
return std::min(std::min(vect.x, vect.y), vect.z); return std::min(std::min(vect.x, vect.y), vect.z);
} }
/**
* \brief Returns the maximum of the three coordinates of the vector
* \return the maximum between the three coordinates of the vector
*/
template <typename T> template <typename T>
T ReduceMax(const Vec3<T>& vect) { T ReduceMax(const Vec3<T>& vect) {
return std::max(std::max(vect.x, vect.y), vect.z); return std::max(std::max(vect.x, vect.y), vect.z);
} }
/** /**
* \brief Returns the (signed) minimal coordinate of the vector * @brief returns the (signed) minimal coordinate of the vector
* \param v a vector *
* \return the (signed) minimal coordinate of the vector * @param v
* @return constexpr T
*/ */
template <> template <>
inline float ReduceMin<float>(const Vec3f& v) { inline float ReduceMin<float>(const Vec3f& v) {
@@ -134,9 +97,10 @@ inline float ReduceMin<float>(const Vec3f& v) {
} }
/** /**
* \brief Returns the (signed) maximal coordinate of the vector * @brief returns the (signed) maximal coordinate of the vector
* \param v a vector *
* \return the (signed) maximal coordinate of the vector * @param v
* @return constexpr T
*/ */
template <> template <>
inline float ReduceMax<float>(const Vec3f& v) { inline float ReduceMax<float>(const Vec3f& v) {
@@ -144,9 +108,10 @@ inline float ReduceMax<float>(const Vec3f& v) {
} }
/** /**
* \brief returns the (signed) minimal coordinate of the vector * @brief returns the (signed) minimal coordinate of the vector
* \param v a vector *
* \return the (signed) minimal coordinate of the vector * @param v
* @return constexpr T
*/ */
template <> template <>
inline double ReduceMin<double>(const Vec3d& v) { inline double ReduceMin<double>(const Vec3d& v) {
@@ -154,9 +119,10 @@ inline double ReduceMin<double>(const Vec3d& v) {
} }
/** /**
* \brief returns the (signed) maximal coordinate of the vector * @brief returns the (signed) maximal coordinate of the vector
* \param v a vector *
* \return the (signed) maximal coordinate of the vector * @param v
* @return constexpr T
*/ */
template <> template <>
inline double ReduceMax<double>(const Vec3d& v) { inline double ReduceMax<double>(const Vec3d& v) {
@@ -164,13 +130,13 @@ inline double ReduceMax<double>(const Vec3d& v) {
} }
/** /**
* \brief returns the coordinate-wise minimum of the given vectors, where a coordinate in the returned vector is NAN iff any of the two * @brief returns the coordinate-wise minimum of the given vectors,
* compared ones are NAN * where a coordinate in the returned vector is NAN iff any of the two compared ones are NAN
* \tparam T *
* \param self a vector * @tparam T
* \param other an other vector * @param self
* \return the coordinate-wise minimum of the given vectors, where a coordinate in the returned vector is NAN iff any of the two * @param other
* compared ones are NAN * @return constexpr Vec3f
*/ */
template <typename T> template <typename T>
constexpr Vec3<T> Min(const Vec3<T>& self, const Vec3<T>& other) { constexpr Vec3<T> Min(const Vec3<T>& self, const Vec3<T>& other) {
@@ -182,13 +148,13 @@ constexpr Vec3<T> Min(const Vec3<T>& self, const Vec3<T>& other) {
} }
/** /**
* \brief returns the coordinate-wise maximum of the given vectors, * @brief returns the coordinate-wise maximum of the given vectors,
* where a coordinate in the returned vector is NAN iff any of the two compared ones are NAN
* \tparam T
* \param self a vector
* \param other an other vector
* \return returns the coordinate-wise maximum of the given vectors,
* where a coordinate in the returned vector is NAN iff any of the two compared ones are NAN * where a coordinate in the returned vector is NAN iff any of the two compared ones are NAN
*
* @tparam T
* @param self
* @param other
* @return constexpr Vec3f
*/ */
template <typename T> template <typename T>
constexpr Vec3<T> Max(const Vec3<T>& self, const Vec3<T>& other) { constexpr Vec3<T> Max(const Vec3<T>& self, const Vec3<T>& other) {
@@ -203,10 +169,6 @@ constexpr Vec3<T> Max(const Vec3<T>& self, const Vec3<T>& other) {
// Matricies // // Matricies //
////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////
/**
* \brief Returns the dot product of the matrix and the vector
* \return the dot product of the matrix and the vector
*/
template <typename T> template <typename T>
Vec4<T> Dot(const Mat4<T>& mat, const Vec4<T>& vect) { Vec4<T> Dot(const Mat4<T>& mat, const Vec4<T>& vect) {
return {mat.x0 * vect.x + mat.x1 * vect.y + mat.x2 * vect.z + mat.x3 * vect.w, return {mat.x0 * vect.x + mat.x1 * vect.y + mat.x2 * vect.z + mat.x3 * vect.w,
@@ -215,10 +177,6 @@ Vec4<T> Dot(const Mat4<T>& mat, const Vec4<T>& vect) {
mat.w0 * vect.x + mat.w1 * vect.y + mat.w2 * vect.z + mat.w3 * vect.w}; mat.w0 * vect.x + mat.w1 * vect.y + mat.w2 * vect.z + mat.w3 * vect.w};
} }
/**
* \brief Returns the dot product of the matrix and an other matrix
* \return the dot product of the matrix and the other matrix
*/
template <typename T> template <typename T>
Mat4<T> Dot(const Mat4<T>& mat, const Mat4<T>& other) { Mat4<T> Dot(const Mat4<T>& mat, const Mat4<T>& other) {
Mat4<T> result{}; Mat4<T> result{};
@@ -234,10 +192,6 @@ Mat4<T> Dot(const Mat4<T>& mat, const Mat4<T>& other) {
return result; return result;
} }
/**
* \brief Returns the identity matrix
* \return the identity matrix
*/
template <typename T> template <typename T>
Mat4<T> Identity() { Mat4<T> Identity() {
Mat4<T> result{}; Mat4<T> result{};
@@ -250,10 +204,6 @@ Mat4<T> Identity() {
return result; return result;
} }
/**
* \brief Returns the transposed matrix
* \return the transposed matrix
*/
template <typename T> template <typename T>
Mat4<T> Transpose(const Mat4<T>& mat) { Mat4<T> Transpose(const Mat4<T>& mat) {
Mat4<T> result; Mat4<T> result;
@@ -278,76 +228,21 @@ Mat4<T> Transpose(const Mat4<T>& mat) {
return result; return result;
} }
/**
* \brief Returns the perspective matrix
* \param fovY The field of view in the y direction
* \param aspectRatio The aspect ratio of the screen
* \param zNear The near clipping plane
* \param zFar The far clipping plane
* \return the perspective matrix
*/
Mat4f Perspective(float fovY, float aspectRatio, float zNear, float zFar); Mat4f Perspective(float fovY, float aspectRatio, float zNear, float zFar);
/**
* \brief Returns the look matrix
* \param eyePos The position of the camera
* \param front The front vector of the camera
* \param up The up vector of the camera
* \return the look matrix
*/
Mat4f Look(const Vec3f& eyePos, const Vec3f& front, const Vec3f& up); Mat4f Look(const Vec3f& eyePos, const Vec3f& front, const Vec3f& up);
/**
* \brief Returns the inverse of the matrix
* \return the inverse of the matrix
*/
Mat4f Inverse(const Mat4f& mat); Mat4f Inverse(const Mat4f& mat);
/**
* \brief Returns the translation matrix
* \param translation The translation vector
* \return the translation matrix
*/
Mat4f Translate(const Vec3f& translation); Mat4f Translate(const Vec3f& translation);
/**
* \brief Returns the scale matrix
* \param axisFactor The scaling factor for each axis
* \return the scale matrix
*/
Mat4f Scale(const Vec3f& axisFactor); Mat4f Scale(const Vec3f& axisFactor);
/**
* \brief Returns the rotation matrix around the x axis
* \param angle The angle of rotation
* \return the rotation matrix
*/
Mat4f RotateX(float angle); Mat4f RotateX(float angle);
/**
* \brief Returns the rotation matrix around the y axis
* \param angle The angle of rotation
* \return the rotation matrix
*/
Mat4f RotateY(float angle); Mat4f RotateY(float angle);
/**
* \brief Returns the rotation matrix around the z axis
* \param angle The angle of rotation
* \return the rotation matrix
*/
Mat4f RotateZ(float angle); Mat4f RotateZ(float angle);
/**
* \brief Returns the rotation matrix
* \param angles The angles of rotation
* \return the rotation matrix
*/
Mat4f Rotate(const Vec3f& angles); Mat4f Rotate(const Vec3f& angles);
/**
* \brief Returns the rotation matrix
* \param angle The angle of rotation
* \param axis The axis of rotation
* \return the rotation matrix
*/
Mat4f Rotate(float angle, Vec3f axis); Mat4f Rotate(float angle, Vec3f axis);
} // namespace maths } // namespace maths

View File

@@ -1,10 +1,5 @@
#pragma once #pragma once
/**
* \file Vector.h
* \brief File containing the Vector structs and 4x4 matrix
*/
#include <algorithm> #include <algorithm>
#include <cmath> #include <cmath>
#include <cstddef> #include <cstddef>

View File

@@ -1,88 +1,63 @@
#pragma once #pragma once
/**
* \file Easing.h
* \brief File containing mathematical functions and constants
*/
namespace blitz { namespace blitz {
namespace utils { namespace utils {
/** /* Sine functions */
* \brief Sine functions
*/
float EaseInSine(float x); float EaseInSine(float x);
float EaseOutSine(float x); float EaseOutSine(float x);
float EaseInOutSine(float x); float EaseInOutSine(float x);
/** /* Cubic functions */
* \brief Cubic functions
*/
float EaseInCubic(float x); float EaseInCubic(float x);
float EaseOutCubic(float x); float EaseOutCubic(float x);
float EaseInOutCubic(float x); float EaseInOutCubic(float x);
/** /* Quint functions */
* \brief Quint functions
*/
float EaseInQuint(float x); float EaseInQuint(float x);
float EaseOutQuint(float x); float EaseOutQuint(float x);
float EaseInOutQuint(float x); float EaseInOutQuint(float x);
/** /* Circ functions */
* \brief Circ functions
*/
float EaseInCirc(float x); float EaseInCirc(float x);
float EaseOutCirc(float x); float EaseOutCirc(float x);
float EaseInOutCirc(float x); float EaseInOutCirc(float x);
/** /* Elastic functions */
* \brief Elastic functions
*/
float EaseInElastic(float x); float EaseInElastic(float x);
float EaseOutElastic(float x); float EaseOutElastic(float x);
float EaseInOutElastic(float x); float EaseInOutElastic(float x);
/** /* Quad functions */
* \brief Quad functions
*/
float EaseInQuad(float x); float EaseInQuad(float x);
float EaseOutQuad(float x); float EaseOutQuad(float x);
float EaseInOutQuad(float x); float EaseInOutQuad(float x);
/** /* Quart functions */
* \brief Quart functions
*/
float EaseInQuart(float x); float EaseInQuart(float x);
float EaseOutQuart(float x); float EaseOutQuart(float x);
float EaseInOutQuart(float x); float EaseInOutQuart(float x);
/** /* Expo functions */
* \brief Expo functions
*/
float EaseInExpo(float x); float EaseInExpo(float x);
float EaseOutExpo(float x); float EaseOutExpo(float x);
float EaseInOutExpo(float x); float EaseInOutExpo(float x);
/** /* Back functions */
* \brief Back functions
*/
float EaseInBack(float x); float EaseInBack(float x);
float EaseOutBack(float x); float EaseOutBack(float x);
float EaseInOutBack(float x); float EaseInOutBack(float x);
/** /* Bounce functions */
* \brief Bounce functions
*/
float EaseInBounce(float x); float EaseInBounce(float x);
float EaseOutBounce(float x); float EaseOutBounce(float x);

View File

@@ -1,10 +1,5 @@
#pragma once #pragma once
/**
* \file Format.h
* \brief This file contains the definition of the `Format` function.
*/
#include <memory> #include <memory>
#include <stdexcept> #include <stdexcept>
#include <string> #include <string>
@@ -12,17 +7,6 @@
namespace blitz { namespace blitz {
namespace utils { namespace utils {
/**
* \brief Formats a string using a format string and variadic arguments.
*
* This function takes a format string and a variable number of arguments and returns a formatted string.
* The format string can contain placeholders that will be replaced by the corresponding arguments.
*
* \param format The format string.
* \param args The variadic arguments to be formatted.
* \return The formatted string.
* \throws std::runtime_error if an error occurs during formatting.
*/
template <typename... Args> template <typename... Args>
std::string Format(const std::string& format, Args... args) { std::string Format(const std::string& format, Args... args) {
int size = snprintf(nullptr, 0, format.c_str(), args...) + 1; // Extra space for '\0' int size = snprintf(nullptr, 0, format.c_str(), args...) + 1; // Extra space for '\0'

View File

@@ -1,32 +1,13 @@
#pragma once #pragma once
/**
* \file Log.h
* \brief File defining log functions
*/
#include <string> #include <string>
namespace blitz { namespace blitz {
namespace utils { namespace utils {
/** void LOG(const std::string& msg); // Normal
* \brief Logs a normal message. void LOGD(const std::string& msg); // Normal en mode debug
* \param msg The message to be logged. void LOGE(const std::string& err); // Normal erreur
*/
void LOG(const std::string& msg);
/**
* \brief Logs a normal message in debug mode.
* \param msg The message to be logged.
*/
void LOGD(const std::string& msg);
/**
* \brief Logs an error message.
* \param err The error message to be logged.
*/
void LOGE(const std::string& err);
} // namespace utils } // namespace utils
} // namespace blitz } // namespace blitz

View File

@@ -1,10 +1,5 @@
#pragma once #pragma once
/**
* \file ObjectNotifier.h
* \brief File containing the blitz::ObjectNotifier class
*/
#include <algorithm> #include <algorithm>
#include <functional> #include <functional>
#include <vector> #include <vector>
@@ -12,26 +7,16 @@
namespace blitz { namespace blitz {
namespace utils { namespace utils {
/**
* \class ObjectNotifier
* \brief Class used to notify listeners
*/
template <typename Listener> template <typename Listener>
class ObjectNotifier { class ObjectNotifier {
protected: protected:
std::vector<Listener*> m_Listeners; std::vector<Listener*> m_Listeners;
public: public:
/**
* \brief Binds a listener to notify later
*/
void BindListener(Listener* listener) { void BindListener(Listener* listener) {
m_Listeners.push_back(listener); m_Listeners.push_back(listener);
} }
/**
* \brief Unbinds a listener (in case the listener is destroyed for example)
*/
void UnbindListener(Listener* listener) { void UnbindListener(Listener* listener) {
auto iter = std::find(m_Listeners.begin(), m_Listeners.end(), listener); auto iter = std::find(m_Listeners.begin(), m_Listeners.end(), listener);
@@ -41,9 +26,6 @@ class ObjectNotifier {
m_Listeners.erase(iter); m_Listeners.erase(iter);
} }
/**
* \brief Notify listeners that were bound
*/
template <typename Func, typename... Args> template <typename Func, typename... Args>
void NotifyListeners(Func function, Args... args) { void NotifyListeners(Func function, Args... args) {
for (Listener* listener : m_Listeners) for (Listener* listener : m_Listeners)

View File

@@ -1,10 +1,5 @@
#pragma once #pragma once
/**
* \file PrettyLog.h
* \brief File defining log functions with colors
*/
#include "blitz/maths/Vector.h" #include "blitz/maths/Vector.h"
#include <string> #include <string>
@@ -23,13 +18,7 @@ const static Vec3uc YELLOW = {255, 255, 0};
} // namespace TextColor } // namespace TextColor
/**
* \brief Returns the color code for a given color.
*/
std::string GetTextColor(Vec3uc color); std::string GetTextColor(Vec3uc color);
/**
* \brief Returns the color code for the reset color.
*/
std::string GetTextColorReset(); std::string GetTextColorReset();
} // namespace utils } // namespace utils

View File

@@ -1,21 +1,10 @@
#pragma once #pragma once
/**
* \file Random.h
* \brief Defines functions for generating random numbers.
*/
#include <random> #include <random>
namespace blitz { namespace blitz {
namespace utils { namespace utils {
/**
* \brief Returns a random integer between min and max.
* \param min The minimum value.
* \param max The maximum value.
* \return A random integer between min and max.
*/
template <typename NumberType> template <typename NumberType>
NumberType GetRandomInt(NumberType min, NumberType max) { NumberType GetRandomInt(NumberType min, NumberType max) {
std::random_device randomDevice; std::random_device randomDevice;
@@ -24,12 +13,6 @@ NumberType GetRandomInt(NumberType min, NumberType max) {
return distrib(generator); return distrib(generator);
} }
/**
* \brief Returns a random real number between min and max.
* \param min The minimum value.
* \param max The maximum value.
* \return A random real number between min and max.
*/
template <typename NumberType> template <typename NumberType>
NumberType GetRandomReal(NumberType min, NumberType max) { NumberType GetRandomReal(NumberType min, NumberType max) {
std::random_device randomDevice; std::random_device randomDevice;

View File

@@ -10,16 +10,7 @@
namespace blitz { namespace blitz {
namespace utils { namespace utils {
/**
* \def BLITZ_TEST_SUCCESSFUL
* \brief Used in tests to indicate that a test was successful
*/
#define BLITZ_TEST_SUCCESSFUL 0 #define BLITZ_TEST_SUCCESSFUL 0
/**
* \def BLITZ_TEST_FAILED
* \brief Used in tests to indicate that a test failed
*/
#define BLITZ_TEST_FAILED 1 #define BLITZ_TEST_FAILED 1
#ifndef __FUNCTION_NAME__ #ifndef __FUNCTION_NAME__
@@ -33,8 +24,7 @@ namespace utils {
/** /**
* \def blitz_test_assert * \def blitz_test_assert
* \param ... The expression to evaluate * \param ... The expression to evaluate
* \brief Evaluates the expression and exits the program if not valid. * \brief Evaluates the expression and exits the program if not valid
* \note It works like a basic assert() but also in release mode
*/ */
#define blitz_test_assert(...) \ #define blitz_test_assert(...) \
if (!static_cast<bool>(__VA_ARGS__)) { \ if (!static_cast<bool>(__VA_ARGS__)) { \
@@ -47,7 +37,6 @@ namespace utils {
* \def blitz_debug_assert * \def blitz_debug_assert
* \param ... The expression to execute * \param ... The expression to execute
* \brief Assertion without checks in release mode * \brief Assertion without checks in release mode
* \note The expression is always executed. However, in release, no checks are made !
*/ */
#ifdef NDEBUG #ifdef NDEBUG
#define blitz_debug_assert(...) __VA_ARGS__ #define blitz_debug_assert(...) __VA_ARGS__

View File

@@ -1,19 +1,10 @@
#pragma once #pragma once
/**
* \file TickCounter.h
* \brief File containing the blitz::utils::TickCounter class
*/
#include <cstdint> #include <cstdint>
namespace blitz { namespace blitz {
namespace utils { namespace utils {
/**
* \class TickCounter
* \brief Class used to count ticks
*/
class TickCounter { class TickCounter {
private: private:
float m_TPS; float m_TPS;
@@ -23,42 +14,19 @@ class TickCounter {
int m_TargetTPS; int m_TargetTPS;
public: public:
/**
* \brief Constructor
* \param tps The target ticks per second
*/
TickCounter(int tps) : m_TargetTPS(tps) {} TickCounter(int tps) : m_TargetTPS(tps) {}
/**
* \brief Reset the tick counter
*/
void Reset(); void Reset();
/** bool Update(); // return true when tps is updated
* \brief Update the tick counter
* \return True if the tick counter has been updated
*/
bool Update();
/**
* \brief Get the ticks per second
* \return The ticks per second
*/
float GetTPS() const { float GetTPS() const {
return m_TPS; return m_TPS;
} }
/**
* \brief Get the milliseconds per tick
* \return The milliseconds per tick
*/
float GetMSPT() const { float GetMSPT() const {
return m_MSPT; return m_MSPT;
} }
/**
* \brief Set the ticks per second
* \param mspt The ticks per second
*/
void SetMSPT(float mspt) { void SetMSPT(float mspt) {
m_MSPT = mspt; m_MSPT = mspt;
} }

View File

@@ -1,11 +1,5 @@
#pragma once #pragma once
/**
* \file Time.h
* \brief File containing the blitz::utils::AutoTimer, blitz::utils::Timer, blitz::utils::CooldownTimer and blitz::utils::DelayTimer
* classes
*/
#include <algorithm> #include <algorithm>
#include <cstdint> #include <cstdint>
#include <functional> #include <functional>
@@ -13,18 +7,11 @@
namespace blitz { namespace blitz {
namespace utils { namespace utils {
/**
* \brief Get current time
* \return Time elapsed since epoch in milliseconds
*/
std::uint64_t GetTime(); std::uint64_t GetTime();
typedef std::function<void()> TimerExecFunction; typedef std::function<void()> TimerExecFunction;
/** // utililty class to call a function at regular period of time
* \class AutoTimer
* \brief Calls a function at regular period of time
*/
class AutoTimer { class AutoTimer {
private: private:
std::uint64_t m_Interval; std::uint64_t m_Interval;
@@ -34,136 +21,65 @@ class AutoTimer {
std::uint64_t m_InternalTime = 0; std::uint64_t m_InternalTime = 0;
public: public:
/**
* \brief Default constructor
*/
AutoTimer() : m_Interval(0), m_Function(nullptr) {} AutoTimer() : m_Interval(0), m_Function(nullptr) {}
/**
* \param interval Time between each function call in milliseconds
*/
AutoTimer(std::uint64_t interval) : m_Interval(interval), m_Function(nullptr) {} AutoTimer(std::uint64_t interval) : m_Interval(interval), m_Function(nullptr) {}
/**
* \param interval Time between each function call in milliseconds
* \param callback The function to call peridocally
*/
AutoTimer(std::uint64_t interval, TimerExecFunction callback) : m_Interval(interval), m_Function(callback) {} AutoTimer(std::uint64_t interval, TimerExecFunction callback) : m_Interval(interval), m_Function(callback) {}
/**
* \brief Updates the timer
*/
void Update(); void Update();
/**
* \brief Updates the timer with the desired time step
* \param delta The time step in milliseconds
*/
void Update(std::uint64_t delta); void Update(std::uint64_t delta);
/**
* \brief Resets the internal cooldown
*/
void Reset(); void Reset();
/**
* \brief Sets a new interval
* \param newInterval the new interval in milliseconds
*/
void SetInterval(std::uint64_t newInterval) { void SetInterval(std::uint64_t newInterval) {
m_Interval = newInterval; m_Interval = newInterval;
} }
/**
* \return The interval between each callback in milliseconds
*/
std::uint64_t GetInterval() const { std::uint64_t GetInterval() const {
return m_Interval; return m_Interval;
} }
/**
* \brief Set a new callback function
* \param newCallback The function to call
*/
void SetCallbackFunction(TimerExecFunction newCallback) { void SetCallbackFunction(TimerExecFunction newCallback) {
m_Function = newCallback; m_Function = newCallback;
} }
/**
* \return The callback function
*/
TimerExecFunction GetCallbackFunction() const { TimerExecFunction GetCallbackFunction() const {
return m_Function; return m_Function;
} }
}; };
/** // utililty class to trigger update at regular period of time
* \class Timer
* \brief Utililty class to trigger update at regular period of time
*/
class Timer { class Timer {
private: private:
std::uint64_t m_Interval; // in millis std::uint64_t m_Interval; // in millis
std::uint64_t m_InternalTime = 0; std::uint64_t m_InternalTime = 0;
public: public:
/**
* \brief Default constructor
*/
Timer() : m_Interval(0) {} Timer() : m_Interval(0) {}
/**
* \brief Construct a Timer with the desired interval
* \param interval The interval between each update in milliseconds
*/
Timer(std::uint64_t interval) : m_Interval(interval) {} Timer(std::uint64_t interval) : m_Interval(interval) {}
/**
* \brief Updates the timer
* \param delta The time step in milliseconds
* \return true every interval milliseconds
*/
bool Update(std::uint64_t delta); bool Update(std::uint64_t delta);
/**
* \brief Resets the timer to its original state
*/
void Reset(); void Reset();
// void ResetSoft(); // don't trigger the timer
/**
* \return The time remaing before the next Update() call will return true (in milliseconds)
*/
std::uint64_t GetTimeRemaining() const { std::uint64_t GetTimeRemaining() const {
return m_Interval - m_InternalTime; return m_Interval - m_InternalTime;
} }
/**
* \return The time elapsed since the previous Update() call returned true (in milliseconds)
*/
std::uint64_t GetTimeElapsed() const { std::uint64_t GetTimeElapsed() const {
return m_InternalTime; return m_InternalTime;
} }
/**
* \brief Set a new value for the interval
* \param newInterval the new interval to set
*/
void SetInterval(std::uint64_t newInterval) { void SetInterval(std::uint64_t newInterval) {
m_Interval = newInterval; m_Interval = newInterval;
} }
/**
* \return The interval between each successful Update()
*/
std::uint64_t GetInterval() const { std::uint64_t GetInterval() const {
return m_Interval; return m_Interval;
} }
}; };
/** // utililty class to trigger update at regular period of time with a cooldown
* \class CooldownTimer
* \brief Class to trigger update at regular period of time with a cooldown
*/
template <typename T> template <typename T>
class CooldownTimer { class CooldownTimer {
private: private:
@@ -171,20 +87,9 @@ class CooldownTimer {
T m_CooldownTime; T m_CooldownTime;
public: public:
/**
* \brief Default constructor
*/
CooldownTimer() : m_Cooldown(0), m_CooldownTime(0) {} CooldownTimer() : m_Cooldown(0), m_CooldownTime(0) {}
/**
* \param cooldown The cooldown before Update() returns true again
*/
CooldownTimer(T cooldown) : m_Cooldown(0), m_CooldownTime(cooldown) {} CooldownTimer(T cooldown) : m_Cooldown(0), m_CooldownTime(cooldown) {}
/**
* \brief Update the timer
* \param delta the time step
*/
bool Update(T delta) { bool Update(T delta) {
if (m_Cooldown > 0) { if (m_Cooldown > 0) {
m_Cooldown = std::max<T>(static_cast<T>(0), static_cast<T>(m_Cooldown - delta)); m_Cooldown = std::max<T>(static_cast<T>(0), static_cast<T>(m_Cooldown - delta));
@@ -192,40 +97,24 @@ class CooldownTimer {
return m_Cooldown == 0; return m_Cooldown == 0;
} }
/**
* \brief Apply a cooldown for the timer
*/
void ApplyCooldown() { void ApplyCooldown() {
m_Cooldown = m_CooldownTime; m_Cooldown = m_CooldownTime;
} }
/**
* \brief Reset the cooldown. Update() will return true immediatly afterward.
*/
void Reset() { void Reset() {
m_Cooldown = 0; m_Cooldown = 0;
} }
/**
* \brief Change the timer cooldown
* \param newCooldown the new cooldown
*/
void SetCooldown(T newCooldown) { void SetCooldown(T newCooldown) {
m_CooldownTime = newCooldown; m_CooldownTime = newCooldown;
} }
/**
* \return The cooldown of the timer
*/
T GetCooldown() const { T GetCooldown() const {
return m_CooldownTime; return m_CooldownTime;
} }
}; };
/** // utililty class to trigger update at regular period of time with a cooldown
* \class DelayTimer
* \brief class to trigger an update after a period of time
*/
template <typename T> template <typename T>
class DelayTimer { class DelayTimer {
private: private:
@@ -233,14 +122,7 @@ class DelayTimer {
T m_InternalTime; T m_InternalTime;
public: public:
/**
* \brief Default constructor
*/
DelayTimer() : m_DelayTime(0), m_InternalTime(0) {} DelayTimer() : m_DelayTime(0), m_InternalTime(0) {}
/**
* \param delay The delay to set
*/
DelayTimer(T delay) : m_DelayTime(delay), m_InternalTime(delay) {} DelayTimer(T delay) : m_DelayTime(delay), m_InternalTime(delay) {}
/** /**
@@ -252,23 +134,16 @@ class DelayTimer {
} }
/** /**
* \brief Resets the timer. Update() will immediatly return true * \brief Resets the timer
*/ */
void Reset() { void Reset() {
m_InternalTime = m_DelayTime; m_InternalTime = m_DelayTime;
} }
/**
* \brief Changes the delay of the timer
* \param newDelay the new delay
*/
void SetDelay(T newDelay) { void SetDelay(T newDelay) {
m_DelayTime = newDelay; m_DelayTime = newDelay;
} }
/**
* \return the delay of the timer
*/
T GetDelay() const { T GetDelay() const {
return m_DelayTime; return m_DelayTime;
} }

View File

@@ -56,7 +56,7 @@ class Connexion : public protocol::PacketHandler, private NonCopyable {
/** /**
* \brief Tries to connect the socket at the specified address and port * \brief Tries to connect the socket at the specified address and port
* \return Whether this action was succesfull * \return Wether this action was succesfull
*/ */
bool Connect(const std::string& address, std::uint16_t port); bool Connect(const std::string& address, std::uint16_t port);

View File

@@ -35,7 +35,7 @@ class TCPListener : private NonCopyable {
* \param port The port to listen to * \param port The port to listen to
* \param maxConnexions The maximum amount of connexion that can happen at the same time. \n * \param maxConnexions The maximum amount of connexion that can happen at the same time. \n
* Every other guests will be kicked if this amount is reached. * Every other guests will be kicked if this amount is reached.
* \return Whether this action was succesfull * \return Wether this action was succesfull
*/ */
bool Listen(std::uint16_t port, int maxConnexions); bool Listen(std::uint16_t port, int maxConnexions);

View File

@@ -1,11 +1,5 @@
#pragma once #pragma once
/**
* \file PacketDispatcher.h
* \brief File containing the blitz::protocol::PacketDispatcher class
*/
#include "blitz/common/NonCopyable.h"
#include "blitz/protocol/Protocol.h" #include "blitz/protocol/Protocol.h"
#include <map> #include <map>
@@ -15,42 +9,22 @@ namespace protocol {
class PacketHandler; class PacketHandler;
/** class PacketDispatcher {
* \class PacketDispatcher
* \brief Class used to dispatch packets
*/
class PacketDispatcher : private NonCopyable {
private: private:
std::map<PacketType, std::vector<PacketHandler*>> m_Handlers; std::map<PacketType, std::vector<PacketHandler*>> m_Handlers;
public: public:
/** PacketDispatcher() = default;
* \brief Constructor
*/ PacketDispatcher(const PacketDispatcher& rhs) = delete;
PacketDispatcher() {} PacketDispatcher& operator=(const PacketDispatcher& rhs) = delete;
PacketDispatcher(PacketDispatcher&& rhs) = delete;
PacketDispatcher& operator=(PacketDispatcher&& rhs) = delete;
/**
* \brief Dispatch a packet
* \param packet The packet to dispatch
*/
void Dispatch(const Packet* packet); void Dispatch(const Packet* packet);
/**
* \brief Register a packet handler
* \param type The packet type
* \param handler The packet handler
*/
void RegisterHandler(PacketType type, PacketHandler* handler); void RegisterHandler(PacketType type, PacketHandler* handler);
/**
* \brief Unregister a packet handler
* \param type The packet type
* \param handler The packet handler
*/
void UnregisterHandler(PacketType type, PacketHandler* handler); void UnregisterHandler(PacketType type, PacketHandler* handler);
/**
* \brief Unregister a packet handler
* \param handler The packet handler
*/
void UnregisterHandler(PacketHandler* handler); void UnregisterHandler(PacketHandler* handler);
}; };

View File

@@ -1,22 +1,13 @@
#pragma once #pragma once
/**
* \file PacketFactory.h
*/
#include "blitz/protocol/Protocol.h" #include "blitz/protocol/Protocol.h"
namespace blitz { namespace blitz {
namespace protocol { namespace protocol {
namespace PacketFactory { namespace PacketFactory {
/**
* \brief Creates a packet from a buffer.
* \param buffer The buffer containing the packet data.
* \return The created packet.
*/
const Packet* CreatePacket(PacketType type, DataBuffer& buffer); const Packet* CreatePacket(PacketType type, DataBuffer& buffer);
} // namespace PacketFactory }
} // namespace protocol } // namespace protocol
} // namespace blitz } // namespace blitz

View File

@@ -1,10 +1,5 @@
#pragma once #pragma once
/**
* \file PacketHandler.h
* \brief File containing the blitz::protocol::PacketHandler class
*/
#include "blitz/protocol/PacketsForward.h" #include "blitz/protocol/PacketsForward.h"
#include "blitz/protocol/Protocol.h" #include "blitz/protocol/Protocol.h"
@@ -13,26 +8,14 @@ namespace protocol {
class PacketDispatcher; class PacketDispatcher;
/**
* \class PacketHandler
* \brief Class used to handle packets
*/
class PacketHandler { class PacketHandler {
private: private:
PacketDispatcher* m_Dispatcher; PacketDispatcher* m_Dispatcher;
public: public:
/**
* \brief Constructor
* \param dispatcher The packet dispatcher
*/
PacketHandler(PacketDispatcher* dispatcher) : m_Dispatcher(dispatcher) {} PacketHandler(PacketDispatcher* dispatcher) : m_Dispatcher(dispatcher) {}
virtual ~PacketHandler() {} virtual ~PacketHandler() {}
/**
* \brief Get the packet dispatcher
* \return The packet dispatcher
*/
PacketDispatcher* GetDispatcher() { PacketDispatcher* GetDispatcher() {
return m_Dispatcher; return m_Dispatcher;
} }

View File

@@ -2,7 +2,7 @@
/** /**
* \file Protocol.h * \file Protocol.h
* \brief File containing the blitz::protocol::Protocol class * \brief File describing protocol
*/ */
#include "blitz/common/DataBuffer.h" #include "blitz/common/DataBuffer.h"

View File

@@ -1,10 +1,5 @@
#pragma once #pragma once
/**
* \file ChatPacket.h
* \brief File containing the blitz::protocol::ChatPacket class
*/
#include "blitz/maths/Vector.h" #include "blitz/maths/Vector.h"
#include "blitz/protocol/Protocol.h" #include "blitz/protocol/Protocol.h"
#include <vector> #include <vector>
@@ -12,53 +7,20 @@
namespace blitz { namespace blitz {
namespace protocol { namespace protocol {
/**
* \struct ColoredPart
* \brief Represents a part of a chat message with a specific color.
*/
struct ColoredPart { struct ColoredPart {
/**
* \brief The color of the part.
*/
Vec4f color; Vec4f color;
/**
* \brief The text of the part.
*/
std::string text; std::string text;
}; };
typedef std::vector<ColoredPart> ColoredText; typedef std::vector<ColoredPart> ColoredText;
/**
* \class ChatPacket
* \brief Packet for sending chat messages.
* %Packet structure :
* | PacketType |
* |------------------------|
* | PacketType::Chat |
*
* | Field Name | Field Type | Notes |
* |--------------------|-------------------|-------------------------------|
* | m_Message | ColoredText | The message sent in the chat |
*/
class ChatPacket : public Packet { class ChatPacket : public Packet {
private: private:
ColoredText m_Message; ColoredText m_Message;
public: public:
/**
* \brief Default constructor.
*/
ChatPacket() {} ChatPacket() {}
/**
* \brief Constructor.
* \param msg The message to send.
*/
ChatPacket(const std::string& msg) : m_Message(ColorizeText(msg)) {} ChatPacket(const std::string& msg) : m_Message(ColorizeText(msg)) {}
/**
* \brief Constructor.
* \param msg The message to send.
*/
ChatPacket(const ColoredText& msg) : m_Message(msg) {} ChatPacket(const ColoredText& msg) : m_Message(msg) {}
virtual ~ChatPacket() {} virtual ~ChatPacket() {}
@@ -66,10 +28,6 @@ class ChatPacket : public Packet {
virtual void Deserialize(DataBuffer& data); virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const; virtual void Dispatch(PacketHandler* handler) const;
/**
* \brief Get the message.
* \return The message.
*/
const ColoredText& GetMessage() const { const ColoredText& GetMessage() const {
return m_Message; return m_Message;
} }
@@ -78,17 +36,8 @@ class ChatPacket : public Packet {
return PacketType::Chat; return PacketType::Chat;
} }
/**
* \brief Get the text color.
*/
static std::string GetTextColor(Vec3uc color); static std::string GetTextColor(Vec3uc color);
/**
* \brief Colorize a text.
*/
static ColoredText ColorizeText(const std::string& text); static ColoredText ColorizeText(const std::string& text);
/**
* \brief Get the colored text string.
*/
static std::string GetColoredTextString(const ColoredText& text); static std::string GetColoredTextString(const ColoredText& text);
}; };

View File

@@ -1,40 +1,16 @@
#pragma once #pragma once
/**
* \file ConnexionInfoPacket.h
* \brief File containing the blitz::protocol::ConnexionInfoPacket class
*/
#include "blitz/protocol/Protocol.h" #include "blitz/protocol/Protocol.h"
namespace blitz { namespace blitz {
namespace protocol { namespace protocol {
/**
* \class ConnexionInfoPacket
* \brief Packet for sending connection information.
* %Packet structure :
* | PacketType |
* |------------------------|
* | PacketType::ConnexionInfo |
*
* | Field Name | Field Type | Notes |
* |--------------------|-------------------|-------------------------------|
* | m_ConnectionID | std::uint8_t | The connection ID |
*/
class ConnexionInfoPacket : public Packet { class ConnexionInfoPacket : public Packet {
private: private:
std::uint8_t m_ConnectionID; std::uint8_t m_ConnectionID;
public: public:
/**
* \brief Default constructor.
*/
ConnexionInfoPacket() {} ConnexionInfoPacket() {}
/**
* \brief Constructor.
* \param connectionID The ID of the connection.
*/
ConnexionInfoPacket(std::uint8_t connectionID) : m_ConnectionID(connectionID) {} ConnexionInfoPacket(std::uint8_t connectionID) : m_ConnectionID(connectionID) {}
virtual ~ConnexionInfoPacket() {} virtual ~ConnexionInfoPacket() {}
@@ -42,10 +18,6 @@ class ConnexionInfoPacket : public Packet {
virtual void Deserialize(DataBuffer& data); virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const; virtual void Dispatch(PacketHandler* handler) const;
/**
* \brief Get the connection ID.
* \return The connection ID.
*/
std::uint8_t GetConnectionID() const { std::uint8_t GetConnectionID() const {
return m_ConnectionID; return m_ConnectionID;
} }

View File

@@ -1,39 +1,15 @@
#pragma once #pragma once
/**
* \file DisconnectPacket.h
* \brief File containing the blitz::protocol::DisconnectPacket class
*/
#include "blitz/protocol/Protocol.h" #include "blitz/protocol/Protocol.h"
namespace blitz { namespace blitz {
namespace protocol { namespace protocol {
/**
* \class DisconnectPacket
* \brief Packet for disconnecting from the server.
* %Packet structure :
* | PacketType |
* |------------------------|
* | PacketType::Disconnect |
*
* | Field Name | Field Type | Notes |
* |--------------------|-------------------|-------------------------------|
* | m_Reason | std::string | The reason for disconnection |
*/
class DisconnectPacket : public Packet { class DisconnectPacket : public Packet {
private: private:
std::string m_Reason; // only when sent from server std::string m_Reason; // only when sent from server
public: public:
/**
* \brief Default constructor.
*/
DisconnectPacket() {} DisconnectPacket() {}
/**
* \brief Constructor.
* \param reason The reason for disconnection.
*/
DisconnectPacket(std::string reason) : m_Reason(reason) {} DisconnectPacket(std::string reason) : m_Reason(reason) {}
virtual ~DisconnectPacket() {} virtual ~DisconnectPacket() {}
@@ -41,10 +17,6 @@ class DisconnectPacket : public Packet {
virtual void Deserialize(DataBuffer& data); virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const; virtual void Dispatch(PacketHandler* handler) const;
/**
* \brief Get the reason for disconnection.
* \return The reason for disconnection.
*/
const std::string& GetReason() const { const std::string& GetReason() const {
return m_Reason; return m_Reason;
} }

View File

@@ -13,14 +13,14 @@ namespace protocol {
/** /**
* \class KeepAlivePacket * \class KeepAlivePacket
* \brief Packet sent to measure the health of a connexion. \n * \brief %Packet sent to measure the health of a connexion. \n
* The client must respond with the same alive ID. Else, the connexion will be closed. \n * The client must respond with the same alive ID. Else, the connexion will be closed. \n
* %Packet structure : * %Packet structure :
* | PacketType | * | PacketType |
* |------------------------| * |------------------------|
* | PacketType::KeepAlive | * | PacketType::KeepAlive |
* *
* | Field Name | Field Type | Notes | * | Field Name | Field Type | Notes |
* |--------------------|---------------|---------------------------------------------------------------------------| * |--------------------|---------------|---------------------------------------------------------------------------|
* | Keep Alive ID | VarInt | The server generates a random ID, the client must respond with the same | * | Keep Alive ID | VarInt | The server generates a random ID, the client must respond with the same |
* *

View File

@@ -13,7 +13,7 @@ namespace protocol {
/** /**
* \class PlayerJoinPacket * \class PlayerJoinPacket
* \brief Packet sent when a new player joins the game * \brief %Packet sent when a new player joins the game \n
* %Packet structure : * %Packet structure :
* | PacketType | * | PacketType |
* |------------------------| * |------------------------|

View File

@@ -1,53 +1,24 @@
#pragma once #pragma once
/**
* \file PlayerLeavePacket.h
* \brief File containing the blitz::protocol::PlayerLeavePacket class
*/
#include "blitz/common/Defines.h"
#include "blitz/protocol/Protocol.h" #include "blitz/protocol/Protocol.h"
namespace blitz { namespace blitz {
namespace protocol { namespace protocol {
/**
* \class PlayerLeavePacket
* \brief Packet for when a player leaves the game.
* %Packet structure :
* | PacketType |
* |------------------------|
* | PacketType::PlayerLeave|
*
* | Field Name | Field Type | Notes |
* |--------------------|-------------------|-------------------------------|
* | m_PlayerID | PlayerID |The ID of the player that left |
*/
class PlayerLeavePacket : public Packet { class PlayerLeavePacket : public Packet {
private: private:
game::PlayerID m_PlayerID; std::uint8_t m_PlayerID;
public: public:
/**
* \brief Default constructor.
*/
PlayerLeavePacket() {} PlayerLeavePacket() {}
/** PlayerLeavePacket(std::uint8_t playerID) : m_PlayerID(playerID) {}
* \brief Constructor.
* \param playerID The ID of the player that left.
*/
PlayerLeavePacket(game::PlayerID playerID) : m_PlayerID(playerID) {}
virtual ~PlayerLeavePacket() {} virtual ~PlayerLeavePacket() {}
virtual DataBuffer Serialize(bool packetID = true) const; virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data); virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const; virtual void Dispatch(PacketHandler* handler) const;
/** std::uint8_t GetPlayerID() const {
* \brief Get the ID of the player that left.
* \return The ID of the player that left.
*/
game::PlayerID GetPlayerID() const {
return m_PlayerID; return m_PlayerID;
} }

View File

@@ -1,10 +1,5 @@
#pragma once #pragma once
/**
* \file PlayerListPacket.h
* \brief File containing the blitz::protocol::PlayerListPacket class
*/
#include <map> #include <map>
#include "blitz/protocol/Protocol.h" #include "blitz/protocol/Protocol.h"
@@ -12,34 +7,18 @@
namespace blitz { namespace blitz {
namespace protocol { namespace protocol {
/**
* \struct PlayerInfo
* \brief Represents information about a player.
*/
struct PlayerInfo { struct PlayerInfo {
std::string name; std::string name;
}; };
typedef std::map<std::uint8_t, PlayerInfo> PlayerList; typedef std::map<std::uint8_t, PlayerInfo> PlayerList;
/**
* \class PlayerListPacket
* \brief Packet for sending the list of players.
* \todo PACKET STRUCTURE
*/
class PlayerListPacket : public Packet { class PlayerListPacket : public Packet {
private: private:
PlayerList m_Players; PlayerList m_Players;
public: public:
/**
* \brief Default constructor.
*/
PlayerListPacket() {} PlayerListPacket() {}
/**
* \brief Constructor.
* \param players The list of players.
*/
PlayerListPacket(const PlayerList& players) : m_Players(players) {} PlayerListPacket(const PlayerList& players) : m_Players(players) {}
virtual ~PlayerListPacket() {} virtual ~PlayerListPacket() {}
@@ -47,11 +26,6 @@ class PlayerListPacket : public Packet {
virtual void Deserialize(DataBuffer& data); virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const; virtual void Dispatch(PacketHandler* handler) const;
/**
* \brief Get the list of players.
* \return The list of players.
*/
const PlayerList& GetPlayers() const { const PlayerList& GetPlayers() const {
return m_Players; return m_Players;
} }

View File

@@ -1,40 +1,16 @@
#pragma once #pragma once
/**
* \file PlayerLoginPacket.h
* \brief File containing the blitz::protocol::PlayerLoginPacket class
*/
#include "blitz/protocol/Protocol.h" #include "blitz/protocol/Protocol.h"
namespace blitz { namespace blitz {
namespace protocol { namespace protocol {
/**
* \class PlayerLoginPacket
* \brief Packet for when a player logs in.
* %Packet structure :
* | PacketType |
* |------------------------|
* | PacketType::PlayerLogin|
*
* | Field Name | Field Type | Notes |
* |--------------------|-------------------|----------------------------------|
* | Player Name | std::string | Name of the player that logged in|
*/
class PlayerLoginPacket : public Packet { class PlayerLoginPacket : public Packet {
private: private:
std::string m_PlayerName; std::string m_PlayerName;
public: public:
/**
* \brief Default constructor.
*/
PlayerLoginPacket() {} PlayerLoginPacket() {}
/**
* \brief Constructor.
* \param playerName The name of the player that logged in.
*/
PlayerLoginPacket(std::string playerName) : m_PlayerName(playerName) {} PlayerLoginPacket(std::string playerName) : m_PlayerName(playerName) {}
virtual ~PlayerLoginPacket() {} virtual ~PlayerLoginPacket() {}
@@ -42,17 +18,13 @@ class PlayerLoginPacket : public Packet {
virtual void Deserialize(DataBuffer& data); virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const; virtual void Dispatch(PacketHandler* handler) const;
/**
* \brief Get the name of the player that logged in.
* \return The name of the player that logged in.
*/
const std::string& GetPlayerName() const {
return m_PlayerName;
}
virtual PacketType GetType() const { virtual PacketType GetType() const {
return PacketType::PlayerLogin; return PacketType::PlayerLogin;
} }
const std::string& GetPlayerName() const {
return m_PlayerName;
}
}; };
} // namespace protocol } // namespace protocol

View File

@@ -1,10 +1,5 @@
#pragma once #pragma once
/**
* \file PlayerPositionAndRotationPacket.h
* \brief File containing the blitz::protocol::PlayerPositionAndRotationPacket class
*/
#include "blitz/common/Defines.h" #include "blitz/common/Defines.h"
#include "blitz/maths/Vector.h" #include "blitz/maths/Vector.h"
#include "blitz/protocol/Protocol.h" #include "blitz/protocol/Protocol.h"
@@ -12,21 +7,6 @@
namespace blitz { namespace blitz {
namespace protocol { namespace protocol {
/**
* \class PlayerPositionAndRotationPacket
* \brief Packet for sending a player's position and rotation.
* %Packet structure :
* | PacketType |
* |--------------------------------|
* | PacketType::PlayerPositionAndRotation |
*
* | Field Name | Field Type | Notes |
* |--------------------|-------------------|----------------------------------|
* | Player ID | PlayerID | Id of the player who moved |
* | Position | Vec3f | Position of the player |
* | Yaw | float | Yaw of the player |
* | Pitch | float | Pitch of the player |
*/
class PlayerPositionAndRotationPacket : public Packet { class PlayerPositionAndRotationPacket : public Packet {
private: private:
game::PlayerID m_Player; // only used when sent to client game::PlayerID m_Player; // only used when sent to client
@@ -34,53 +14,28 @@ class PlayerPositionAndRotationPacket : public Packet {
float m_Yaw, m_Pitch; float m_Yaw, m_Pitch;
public: public:
/**
* \brief Default constructor.
*/
PlayerPositionAndRotationPacket() {} PlayerPositionAndRotationPacket() {}
/**
* \brief Constructor.
* \param position The position of the player.
* \param yaw The yaw of the player.
* \param pitch The pitch of the player.
* \param player The ID of the player.
*/
PlayerPositionAndRotationPacket(const Vec3f& position, float yaw, float pitch, game::PlayerID player = 0) : PlayerPositionAndRotationPacket(const Vec3f& position, float yaw, float pitch, game::PlayerID player = 0) :
m_Player(player), m_Position(position), m_Yaw(yaw), m_Pitch(pitch) {} m_Player(player), m_Position(position), m_Yaw(yaw), m_Pitch(pitch) {}
virtual ~PlayerPositionAndRotationPacket() {} virtual ~PlayerPositionAndRotationPacket() {}
virtual DataBuffer Serialize(bool packetID = true) const; virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data); virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const; virtual void Dispatch(PacketHandler* handler) const;
/**
* \brief Get the position of the player.
* \return The position of the player.
*/
const Vec3f& GetPosition() const { const Vec3f& GetPosition() const {
return m_Position; return m_Position;
} }
/**
* \brief Get the yaw of the player.
* \return The yaw of the player.
*/
float GetYaw() const { float GetYaw() const {
return m_Yaw; return m_Yaw;
} }
/**
* \brief Get the pitch of the player.
* \return The pitch of the player.
*/
float GetPitch() const { float GetPitch() const {
return m_Pitch; return m_Pitch;
} }
/**
* \brief Get the ID of the player.
* \return The ID of the player.
*/
game::PlayerID GetPlayer() const { game::PlayerID GetPlayer() const {
return m_Player; return m_Player;
} }

View File

@@ -1,31 +1,11 @@
#pragma once #pragma once
/**
* \file PlayerShootPacket.h
* \brief File containing the blitz::protocol::PlayerShootPacket class
*/
#include "blitz/game/Player.h" #include "blitz/game/Player.h"
#include "blitz/protocol/Protocol.h" #include "blitz/protocol/Protocol.h"
namespace blitz { namespace blitz {
namespace protocol { namespace protocol {
/**
* \class PlayerShootPacket
* \brief Packet for when a player shoots.
* %Packet structure :
* | PacketType |
* |------------------------|
* | PacketType::PlayerShoot|
*
* | Field Name | Field Type | Notes |
* |--------------------|-------------------|----------------------------------|
* | Player ID | PlayerID | The ID of the player that shot |
* | Position | Vec3f | Position of the player |
* | Yaw | float | Yaw of the player |
* | Pitch | float | Pitch of the player |
*/
class PlayerShootPacket : public Packet { class PlayerShootPacket : public Packet {
private: private:
game::PlayerID m_Player; // only used when sent to client game::PlayerID m_Player; // only used when sent to client
@@ -33,17 +13,7 @@ class PlayerShootPacket : public Packet {
float m_Yaw, m_Pitch; float m_Yaw, m_Pitch;
public: public:
/**
* \brief Default constructor.
*/
PlayerShootPacket() {} PlayerShootPacket() {}
/**
* \brief Constructor.
* \param position The position of the player.
* \param yaw The yaw of the player.
* \param pitch The pitch of the player.
* \param player The ID of the player.
*/
PlayerShootPacket(Vec3f position, float yaw, float pitch, game::PlayerID player = 0) : PlayerShootPacket(Vec3f position, float yaw, float pitch, game::PlayerID player = 0) :
m_Player(player), m_Position(position), m_Yaw(yaw), m_Pitch(pitch) {} m_Player(player), m_Position(position), m_Yaw(yaw), m_Pitch(pitch) {}
virtual ~PlayerShootPacket() {} virtual ~PlayerShootPacket() {}
@@ -52,34 +22,18 @@ class PlayerShootPacket : public Packet {
virtual void Deserialize(DataBuffer& data); virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const; virtual void Dispatch(PacketHandler* handler) const;
/**
* \brief Get the position of the player.
* \return The position of the player.
*/
const Vec3f& GetPosition() const { const Vec3f& GetPosition() const {
return m_Position; return m_Position;
} }
/**
* \brief Get the yaw of the player.
* \return The yaw of the player.
*/
float GetYaw() const { float GetYaw() const {
return m_Yaw; return m_Yaw;
} }
/**
* \brief Get the pitch of the player.
* \return The pitch of the player.
*/
float GetPitch() const { float GetPitch() const {
return m_Pitch; return m_Pitch;
} }
/**
* \brief Get the ID of the player.
* \return The ID of the player.
*/
game::PlayerID GetPlayer() const { game::PlayerID GetPlayer() const {
return m_Player; return m_Player;
} }

View File

@@ -1,10 +1,5 @@
#pragma once #pragma once
/**
* \file PlayerStatsPacket.h
* \brief File containing the blitz::protocol::PlayerStatsPacket class
*/
#include "blitz/common/Defines.h" #include "blitz/common/Defines.h"
#include "blitz/game/Player.h" #include "blitz/game/Player.h"
#include "blitz/protocol/Protocol.h" #include "blitz/protocol/Protocol.h"
@@ -12,34 +7,13 @@
namespace blitz { namespace blitz {
namespace protocol { namespace protocol {
/**
* \class PlayerStatsPacket
* \brief Packet for sending player stats.
* %Packet structure :
* | PacketType |
* |------------------------|
* | PacketType::PlayerStats|
*
* | Field Name | Field Type | Notes |
* |--------------------|-------------------|-------------------------------|
* | Player ID | PlayerID | Id of the player |
* | Player Stats | PlayerStats | Stats of the player |
*/
class PlayerStatsPacket : public Packet { class PlayerStatsPacket : public Packet {
private: private:
game::PlayerID m_PlayerID; game::PlayerID m_PlayerID;
game::PlayerStats m_PlayerStats; game::PlayerStats m_PlayerStats;
public: public:
/**
* \brief Default constructor.
*/
PlayerStatsPacket() {} PlayerStatsPacket() {}
/**
* \brief Constructor.
* \param playerID The ID of the player.
* \param stats The stats of the player.
*/
PlayerStatsPacket(game::PlayerID playerID, const game::PlayerStats& stats) : m_PlayerID(playerID), m_PlayerStats(stats) {} PlayerStatsPacket(game::PlayerID playerID, const game::PlayerStats& stats) : m_PlayerID(playerID), m_PlayerStats(stats) {}
virtual ~PlayerStatsPacket() {} virtual ~PlayerStatsPacket() {}

View File

@@ -1,41 +1,17 @@
#pragma once #pragma once
/**
* \file ServerConfigPacket.h
* \brief File containing the blitz::protocol::ServerConfigPacket class
*/
#include "blitz/game/Game.h" #include "blitz/game/Game.h"
#include "blitz/protocol/Protocol.h" #include "blitz/protocol/Protocol.h"
namespace blitz { namespace blitz {
namespace protocol { namespace protocol {
/**
* \class ServerConfigPacket
* \brief Packet for sending the server configuration.
* %Packet structure :
* | PacketType |
* |-------------------------|
* | PacketType::ServerConfig|
*
* | Field Name | Field Type | Notes |
* |--------------------|-------------------|-------------------------------|
* | Game Config | GameConfig | The game configuration |
*/
class ServerConfigPacket : public Packet { class ServerConfigPacket : public Packet {
private: private:
game::GameConfig m_GameConfig; game::GameConfig m_GameConfig;
public: public:
/**
* \brief Default constructor.
*/
ServerConfigPacket() {} ServerConfigPacket() {}
/**
* \brief Constructor.
* \param GameConfig The game configuration.
*/
ServerConfigPacket(const game::GameConfig& GameConfig) : m_GameConfig(GameConfig) {} ServerConfigPacket(const game::GameConfig& GameConfig) : m_GameConfig(GameConfig) {}
virtual ~ServerConfigPacket() {} virtual ~ServerConfigPacket() {}
@@ -43,10 +19,6 @@ class ServerConfigPacket : public Packet {
virtual void Deserialize(DataBuffer& data); virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const; virtual void Dispatch(PacketHandler* handler) const;
/**
* \brief Getter of the game configuration
* \return The game configuration
*/
game::GameConfig GetGameConfig() const { game::GameConfig GetGameConfig() const {
return m_GameConfig; return m_GameConfig;
} }

View File

@@ -1,45 +1,17 @@
#pragma once #pragma once
/**
* \file ServerTpsPacket.h
* \brief File containing the blitz::protocol::ServerTpsPacket class
*/
#include "blitz/protocol/Protocol.h" #include "blitz/protocol/Protocol.h"
namespace blitz { namespace blitz {
namespace protocol { namespace protocol {
/**
* \class ServerTpsPacket
* \brief Packet for sending server TPS (Tick per second) and MSPT (Milliseconds per tick).
* %Packet structure :
* | PacketType |
* |------------------------|
* | PacketType::ServerTps |
*
* | Field Name | Field Type | Notes |
* |--------------------|-------------------|-------------------------------|
* | Tps | float | Server TPS |
* | Mspt | float | Server MSPT |
* | PacketSendTime | uint64_t | Time the packet was sent |
*/
class ServerTpsPacket : public Packet { class ServerTpsPacket : public Packet {
private: private:
float m_TPS; float m_TPS;
float m_MSPT; float m_MSPT;
std::uint64_t m_PacketSendTime; // used to calculate ping std::uint64_t m_PacketSendTime; // used to calculate ping
public: public:
/**
* \brief Default constructor.
*/
ServerTpsPacket() {} ServerTpsPacket() {}
/**
* \brief Constructor.
* \param tps The server TPS.
* \param mspt The server MSPT.
* \param sendTime The time the packet was sent.
*/
ServerTpsPacket(float tps, float mspt, std::uint64_t sendTime) : m_TPS(tps), m_MSPT(mspt), m_PacketSendTime(sendTime) {} ServerTpsPacket(float tps, float mspt, std::uint64_t sendTime) : m_TPS(tps), m_MSPT(mspt), m_PacketSendTime(sendTime) {}
virtual ~ServerTpsPacket() {} virtual ~ServerTpsPacket() {}
@@ -47,27 +19,14 @@ class ServerTpsPacket : public Packet {
virtual void Deserialize(DataBuffer& data); virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const; virtual void Dispatch(PacketHandler* handler) const;
/**
* \brief Get the server TPS.
* \return The server TPS.
*/
float GetTPS() const { float GetTPS() const {
return m_TPS; return m_TPS;
} }
/**
* \brief Get the server MSPT.
* \return The server MSPT.
*/
float GetMSPT() const { float GetMSPT() const {
return m_MSPT; return m_MSPT;
} }
/**
* \brief Get the time the packet was sent.
* \return The time the packet was sent.
* \todo Calculate ping.
*/
std::uint64_t GetPacketSendTime() const { std::uint64_t GetPacketSendTime() const {
return m_PacketSendTime; return m_PacketSendTime;
} }

View File

@@ -1,44 +1,18 @@
#pragma once #pragma once
/**
* \file UpdateGameStatePacket.h
* \brief File containing the blitz::protocol::UpdateGameStatePacket class
*/
#include "blitz/game/Game.h" #include "blitz/game/Game.h"
#include "blitz/protocol/Protocol.h" #include "blitz/protocol/Protocol.h"
namespace blitz { namespace blitz {
namespace protocol { namespace protocol {
/**
* \class UpdateGameStatePacket
* \brief Packet for updating the game state.
* %Packet structure :
* | PacketType |
* |-----------------------------|
* | PacketType::UpdateGameState |
*
* | Field Name | Field Type | Notes |
* |--------------------|-------------------|----------------------------------------------|
* | Game State | GameState | The new game state |
* | Time Remaining | std::uint64_t | The time remaining in the current game state |
*/
class UpdateGameStatePacket : public Packet { class UpdateGameStatePacket : public Packet {
private: private:
game::GameState m_GameState; game::GameState m_GameState;
std::uint64_t m_TimeRemaining; std::uint64_t m_TimeRemaining;
public: public:
/**
* \brief Default constructor.
*/
UpdateGameStatePacket() {} UpdateGameStatePacket() {}
/**
* \brief Constructor.
* \param a_GameState The new game state.
* \param a_TimeRemaining The time remaining in the current game state.
*/
UpdateGameStatePacket(game::GameState a_GameState, std::uint64_t a_TimeRemaining = 0) : UpdateGameStatePacket(game::GameState a_GameState, std::uint64_t a_TimeRemaining = 0) :
m_GameState(a_GameState), m_TimeRemaining(a_TimeRemaining) {} m_GameState(a_GameState), m_TimeRemaining(a_TimeRemaining) {}
virtual ~UpdateGameStatePacket() {} virtual ~UpdateGameStatePacket() {}
@@ -47,18 +21,10 @@ class UpdateGameStatePacket : public Packet {
virtual void Deserialize(DataBuffer& data); virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const; virtual void Dispatch(PacketHandler* handler) const;
/**
* \brief Get the new game state.
* \return The new game state.
*/
game::GameState GetGameState() const { game::GameState GetGameState() const {
return m_GameState; return m_GameState;
} }
/**
* \brief Get the time remaining in the current game state.
* \return The time remaining in the current game state.
*/
std::uint64_t GetTimeRemaining() const { std::uint64_t GetTimeRemaining() const {
return m_TimeRemaining; return m_TimeRemaining;
} }

View File

@@ -1,40 +1,16 @@
#pragma once #pragma once
/**
* \file UpdateHealthPacket.h
* \brief File containing the blitz::protocol::UpdateHealthPacket class
*/
#include "blitz/protocol/Protocol.h" #include "blitz/protocol/Protocol.h"
namespace blitz { namespace blitz {
namespace protocol { namespace protocol {
/**
* \class UpdateHealthPacket
* \brief Packet for updating the health of a player.
* %Packet structure :
* | PacketType |
* |--------------------------|
* | PacketType::UpdateHealth |
*
* | Field Name | Field Type | Notes |
* |--------------------|-------------------|-------------------------------|
* | m_NewHealth | float | The new health value |
*/
class UpdateHealthPacket : public Packet { class UpdateHealthPacket : public Packet {
private: private:
float m_NewHealth; float m_NewHealth;
public: public:
/**
* \brief Default constructor.
*/
UpdateHealthPacket() {} UpdateHealthPacket() {}
/**
* \brief Constructor.
* \param newHealth The new health value.
*/
UpdateHealthPacket(float newHealth) : m_NewHealth(newHealth) {} UpdateHealthPacket(float newHealth) : m_NewHealth(newHealth) {}
virtual ~UpdateHealthPacket() {} virtual ~UpdateHealthPacket() {}
@@ -42,10 +18,6 @@ class UpdateHealthPacket : public Packet {
virtual void Deserialize(DataBuffer& data); virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const; virtual void Dispatch(PacketHandler* handler) const;
/**
* \brief Get the new health value.
* \return The new health value.
*/
float GetNewHealth() const { float GetNewHealth() const {
return m_NewHealth; return m_NewHealth;
} }

View File

@@ -1,25 +0,0 @@
#pragma once
#include "blitz/common/DataBuffer.h"
#include "blitz/common/NonCopyable.h"
#include "blitz/maths/Vector.h"
#include "client/audio/AudioLoader.h"
namespace blitz {
namespace audio {
class AudioBuffer : private NonCopyable {
private:
unsigned int m_ID;
public:
AudioBuffer(AudioData&& audioData);
~AudioBuffer();
unsigned int GetID() const {
return m_ID;
}
};
} // namespace audio
} // namespace blitz

View File

@@ -1,21 +0,0 @@
#pragma once
#include "blitz/common/NonCopyable.h"
#include "blitz/maths/Vector.h"
namespace blitz {
namespace audio {
class AudioListener : private NonCopyable {
public:
AudioListener();
~AudioListener();
void SetGain(float a_Gain);
void SetPosition(const Vec3f& a_Position);
void SetVelocity(const Vec3f& a_Velocity);
void SetOrientation(const Vec3f& a_Orientation, const Vec3f& a_Up);
};
} // namespace audio
} // namespace blitz

View File

@@ -1,24 +0,0 @@
#pragma once
#include "blitz/common/DataBuffer.h"
namespace blitz {
namespace audio {
enum AudioFormat { afMono8 = 0, afMono16, afStereo8, afStereo16 };
struct AudioData {
DataBuffer m_Buffer;
AudioFormat m_Format;
std::uint32_t m_Frequency;
};
namespace AudioLoader {
// files should be 8 or 16 bits wav
AudioData LoadAudioFile(const std::string& filePath);
}; // namespace AudioLoader
} // namespace audio
} // namespace blitz

View File

@@ -1,33 +0,0 @@
#pragma once
#include "blitz/game/Listeners.h"
#include "client/audio/AudioListener.h"
#include "client/audio/AudioSource.h"
namespace blitz {
class Client;
namespace audio {
class AudioManager : public game::ClientListener {
private:
Client* m_Client;
AudioListener m_Listener;
AudioSourcePtr m_MenuMusic;
std::vector<AudioSourcePtr> m_Sources;
public:
AudioManager(Client* client);
~AudioManager();
virtual void OnGameJoin() override;
virtual void OnGameLeave() override;
private:
void InitMainMenuMusic();
};
} // namespace audio
} // namespace blitz

View File

@@ -1,42 +0,0 @@
#pragma once
#include "blitz/common/NonCopyable.h"
#include "blitz/maths/Vector.h"
#include "client/audio/AudioBuffer.h"
#include <memory>
namespace blitz {
namespace audio {
typedef std::unique_ptr<AudioBuffer> AudioBufferPtr;
class AudioSource : NonCopyable {
private:
unsigned int m_ID;
AudioBufferPtr m_Buffer;
public:
enum SourceState { ssInitial = 0, ssPlaying, ssPaused, ssStopped };
AudioSource();
~AudioSource();
void SetGain(float a_Gain);
void SetPitch(float a_Pitch);
void SetPosition(const Vec3f& a_Position);
void SetDirection(const Vec3f& a_Direction);
void SetVelocity(const Vec3f& a_Velocity);
void SetLooping(bool a_Looping);
void SetBuffer(AudioBufferPtr&& a_Buffer);
SourceState GetSourceState() const;
void Play();
void Pause();
void Stop();
};
typedef std::unique_ptr<AudioSource> AudioSourcePtr;
} // namespace audio
} // namespace blitz

View File

@@ -1,20 +1,11 @@
#pragma once #pragma once
/**
* \file BlitzConfig.h
* \brief File containing the blitz::BlitzConfig class
*/
#include "blitz/game/Game.h" #include "blitz/game/Game.h"
#include <array> #include <array>
#include <string> #include <string>
namespace blitz { namespace blitz {
/**
* \enum KeyAction
* \brief Enum containing the key actions
*/
enum KeyAction { enum KeyAction {
kaAvancer = 0, kaAvancer = 0,
kaReculer, kaReculer,
@@ -26,13 +17,9 @@ enum KeyAction {
typedef std::array<int, kaMax> Keybinds; typedef std::array<int, kaMax> Keybinds;
/**
* \class BlitzConfig
* \brief Class used to manage the Blitz configuration
*/
class BlitzConfig { class BlitzConfig {
private: private:
std::array<char, 20> m_Pseudo; std::array<char, 256> m_Pseudo;
game::GameConfig m_ServerConfig; game::GameConfig m_ServerConfig;
bool m_VSync; bool m_VSync;
bool m_DisplayFps; bool m_DisplayFps;
@@ -40,71 +27,41 @@ class BlitzConfig {
float m_MouseSpeed; float m_MouseSpeed;
public: public:
/**
* \brief Default constructor
*/
BlitzConfig(); BlitzConfig();
~BlitzConfig(); ~BlitzConfig();
std::array<char, 20>& GetPseudo() { std::array<char, 256>& GetPseudo() {
return m_Pseudo; return m_Pseudo;
} }
/**
* \brief Return whether VSync is enabled
*/
bool IsVSyncEnabled() const { bool IsVSyncEnabled() const {
return m_VSync; return m_VSync;
} }
/**
* \brief Set whether VSync is enabled
*/
void SetVSync(bool vsync) { void SetVSync(bool vsync) {
m_VSync = vsync; m_VSync = vsync;
} }
/**
* \brief Return whether the FPS display is enabled
*/
bool IsFPSDisplayEnabled() const { bool IsFPSDisplayEnabled() const {
return m_DisplayFps; return m_DisplayFps;
} }
/**
* \brief Set whether the FPS display is enabled
*/
void SetFPSDisplay(bool display) { void SetFPSDisplay(bool display) {
m_DisplayFps = display; m_DisplayFps = display;
} }
/**
* \brief Get the keybinds
* \return The keybinds
*/
Keybinds& GetKeys() { Keybinds& GetKeys() {
return m_Keybinds; return m_Keybinds;
} }
/**
* \brief Get the mouse speed
* \return The mouse speed
*/
float GetMouseSpeed() const { float GetMouseSpeed() const {
return m_MouseSpeed; return m_MouseSpeed;
} }
/**
* \brief Set the mouse speed
*/
void SetMouseSpeed(float MouseSpeed) { void SetMouseSpeed(float MouseSpeed) {
m_MouseSpeed = MouseSpeed; m_MouseSpeed = MouseSpeed;
} }
/**
* \brief Get the server configuration
* \return The server configuration
*/
game::GameConfig& GetServerConfig() { game::GameConfig& GetServerConfig() {
return m_ServerConfig; return m_ServerConfig;
} }

View File

@@ -1,10 +1,5 @@
#pragma once #pragma once
/**
* \file Display.h
* \brief File containing the blitz::Display class
*/
#include <memory> #include <memory>
#include <string> #include <string>
@@ -18,10 +13,7 @@ namespace gui {
class BlitzGui; class BlitzGui;
} // namespace gui } // namespace gui
/**
* \class Display
* \brief Class used to manage the display
*/
class Display { class Display {
private: private:
SDL_Window* m_Window; SDL_Window* m_Window;
@@ -39,55 +31,19 @@ class Display {
std::unique_ptr<gui::BlitzGui> m_BlitzGui; std::unique_ptr<gui::BlitzGui> m_BlitzGui;
public: public:
/**
* \brief Constructor
* \param width The width of the window
* \param height The height of the window
* \param windowName The name of the window
* \param client The client
*/
Display(int width, int height, const std::string& windowName, Client* client); Display(int width, int height, const std::string& windowName, Client* client);
~Display(); ~Display();
/**
* \brief Return whether the display has been created
*/
bool Create(); bool Create();
/**
* \brief Poll the events
* \note This function should be called at the beginning of the main loop
*/
void PollEvents(); void PollEvents();
/**
* \brief Update the display
* \note Swap the buffers
*/
void Update(); void Update();
/**
* \brief Render the display (ImGui)
*/
void Render(); void Render();
/**
* \brief Destroy the display (Not your mother's display)
*/
void Destroy(); void Destroy();
/**
* \brief Return whether the display should be closed
*/
bool IsCloseRequested(); bool IsCloseRequested();
/**
* \brief Return widht/height ratio
*/
float GetAspectRatio(); float GetAspectRatio();
/**
* \brief Return the window width
*/
int GetWindowWidth(); int GetWindowWidth();
/**
* \brief Return the window height
*/
int GetWindowHeight(); int GetWindowHeight();
private: private:

View File

@@ -1,10 +1,5 @@
#pragma once #pragma once
/**
* \file PlayerController.h
* \brief File containing the blitz::input::PlayerController class.
*/
#include "blitz/common/Smoothing.h" #include "blitz/common/Smoothing.h"
#include "blitz/game/Listeners.h" #include "blitz/game/Listeners.h"
#include "blitz/misc/ObjectNotifier.h" #include "blitz/misc/ObjectNotifier.h"
@@ -22,11 +17,6 @@ class Player;
namespace input { namespace input {
/**
* \brief Class that handles player input and sends it to the client.
* \details This class is responsible for handling player input and sending it to the server.
* It also handles the player's velocity and position.
*/
class PlayerController : public utils::ObjectNotifier<game::PlayerInputListener>, game::ClientListener { class PlayerController : public utils::ObjectNotifier<game::PlayerInputListener>, game::ClientListener {
private: private:
game::Player* m_Player; game::Player* m_Player;
@@ -42,30 +32,16 @@ class PlayerController : public utils::ObjectNotifier<game::PlayerInputListener>
bool m_OnGround; bool m_OnGround;
public: public:
/**
* \brief Default constructor
*/
PlayerController(Client* client); PlayerController(Client* client);
/**
* \brief Update things like player position and velocity.
*/
void Update(float delta); void Update(float delta);
virtual void OnGameConfigUpdate() override; virtual void OnGameConfigUpdate() override;
/**
* \brief Set the player that this controller is attached to.
* \param a_Player The player to attach to.
*/
void SetAttachedPlayer(game::Player* a_Player) { void SetAttachedPlayer(game::Player* a_Player) {
m_Player = a_Player; m_Player = a_Player;
} }
/**
* \brief Get the player that this controller is attached to.
* \return The player that this controller is attached to.
*/
game::Player* GetAttachedPlayer() { game::Player* GetAttachedPlayer() {
return m_Player; return m_Player;
} }

View File

@@ -9,7 +9,7 @@ class Client;
namespace game { namespace game {
class Player; class Player;
} // namespace game } // namespace game
namespace gui { namespace gui {
class Hud : public GuiWidget { class Hud : public GuiWidget {

View File

@@ -1,6 +1,7 @@
#pragma once #pragma once
#include "blitz/game/Player.h" #include "blitz/game/Player.h"
#include "blitz/maths/Vector.h"
#include <cstdint> #include <cstdint>
namespace blitz { namespace blitz {

View File

@@ -1,10 +1,5 @@
#pragma once #pragma once
/**
* \file Server.h
* \brief File containing the blitz::server::Server class
*/
#include <map> #include <map>
#include <thread> #include <thread>
@@ -13,15 +8,7 @@
#include "server/ServerConnexion.h" #include "server/ServerConnexion.h"
#include "server/game/ServerGame.h" #include "server/game/ServerGame.h"
/**
* \def SERVER_TPS
* \brief The server ticks per second
*/
#define SERVER_TPS 20 #define SERVER_TPS 20
/**
* \def SERVER_TICK
* \brief The server tick duration
*/
#define SERVER_TICK 1000 / SERVER_TPS #define SERVER_TICK 1000 / SERVER_TPS
namespace blitz { namespace blitz {
@@ -29,10 +16,6 @@ namespace server {
typedef std::map<std::uint8_t, std::unique_ptr<ServerConnexion>> ConnexionMap; typedef std::map<std::uint8_t, std::unique_ptr<ServerConnexion>> ConnexionMap;
/**
* \class Server
* \brief Class used to manage the server
*/
class Server { class Server {
private: private:
network::TCPListener m_Listener; network::TCPListener m_Listener;
@@ -45,114 +28,47 @@ class Server {
bool m_ServerRunning; bool m_ServerRunning;
public: public:
/**
* \brief Constructor
*/
Server(); Server();
virtual ~Server(); virtual ~Server();
/**
* \brief Start the server
* \param port The port
* \param blocking If the server is blocking
* \return If the server has started
*/
bool Start(std::uint16_t port, bool blocking); bool Start(std::uint16_t port, bool blocking);
/** void Stop(); // force the server to stop
* \brief Force the server to stop
*/
void Stop();
/**
* \brief Restart the server
*/
void Restart(); void Restart();
/**
* \brief Add a bot
*/
void AddBot(); void AddBot();
/**
* \brief Forcefully remove a player from the game
* \param player the id of the player to remove
*/
void KickPlayer(game::PlayerID player);
/**
* \brief Remove a connexion
* \param connexionID The connexion ID
*/
void RemoveConnexion(std::uint8_t connexionID); void RemoveConnexion(std::uint8_t connexionID);
/**
* \brief Broadcast a packet to all connexions
* \param packet The packet
*/
void BroadcastPacket(const protocol::Packet* packet); void BroadcastPacket(const protocol::Packet* packet);
/**
* \brief Broadcast a chat message
* \param msg The message
*/
void BroadcastChatMessage(const std::string& msg); void BroadcastChatMessage(const std::string& msg);
/**
* \brief Get the milliseconds per tick
* \return The milliseconds per tick
*/
float GetMSPT() const { float GetMSPT() const {
return m_TickCounter.GetMSPT(); return m_TickCounter.GetMSPT();
} }
/**
* \brief Get the ticks per second
* \return The ticks per second
*/
float GetTPS() const { float GetTPS() const {
return m_TickCounter.GetTPS(); return m_TickCounter.GetTPS();
} }
/**
* \brief Return whether the server is running
*/
bool IsRunning() { bool IsRunning() {
return m_ServerRunning; return m_ServerRunning;
} }
/**
* \brief Get the connexions (const version)
* \return The connexions
*/
const ConnexionMap& GetConnexions() const { const ConnexionMap& GetConnexions() const {
return m_Connections; return m_Connections;
} }
/**
* \brief Get the connexions
* \return The connexions
*/
ConnexionMap& GetConnexions() { ConnexionMap& GetConnexions() {
return m_Connections; return m_Connections;
} }
/**
* \brief Get the game
* \return The game
*/
ServerGame& GetGame() { ServerGame& GetGame() {
return m_Game; return m_Game;
} }
/**
* \brief Get the listening port
* \return The listening port
*/
std::uint16_t GetListeningPort(); std::uint16_t GetListeningPort();
/**
* \brief Get a new player ID
* \return The new player ID
*/
game::PlayerID GetNewPlayerID(); game::PlayerID GetNewPlayerID();
private: private:

View File

@@ -1,10 +1,5 @@
#pragma once #pragma once
/**
* \file ServerConnexion.h
* \brief File containing the blitz::server::ServerConnexion class
*/
#include "blitz/network/Connexion.h" #include "blitz/network/Connexion.h"
namespace blitz { namespace blitz {
@@ -20,23 +15,13 @@ namespace server {
class Server; class Server;
/**
* \struct KeepAlive
* \brief Structure containing the keep alive informations
* \var KeepAlive::KeepAliveID The keep alive ID
* \var KeepAlive::SendTime The time when the keep alive was sent
* \var KeepAlive::RecievedResponse If the keep alive has recieved a response
*/
struct KeepAlive { struct KeepAlive {
std::uint64_t KeepAliveID = 0; std::uint64_t keepAliveID = 0;
std::uint64_t SendTime; std::uint64_t sendTime;
bool RecievedResponse = false; bool recievedResponse = false;
}; };
/**
* \class ServerConnexion
* \brief Class used to manage the server connexion
*/
class ServerConnexion : public network::Connexion { class ServerConnexion : public network::Connexion {
private: private:
Server* m_Server; Server* m_Server;
@@ -46,31 +31,11 @@ class ServerConnexion : public network::Connexion {
std::string m_ChatColor; std::string m_ChatColor;
public: public:
/**
* \brief Constructor
* \param server The server
* \param socket The socket
* \param id The ID of the connexion
*/
ServerConnexion(Server* server, network::TCPSocket& socket, std::uint8_t id); ServerConnexion(Server* server, network::TCPSocket& socket, std::uint8_t id);
/**
* \brief Move constructor
*/
ServerConnexion(ServerConnexion&& move); ServerConnexion(ServerConnexion&& move);
virtual ~ServerConnexion(); virtual ~ServerConnexion();
/** void Start();
* \brief Start the connexion
*/
void Init();
/**
* \brief Get the ID of the connexion
* \return The ID of the connexion
*/
std::uint8_t GetID() const {
return m_ID;
}
virtual void HandlePacket(const protocol::PlayerLoginPacket* packet) override; virtual void HandlePacket(const protocol::PlayerLoginPacket* packet) override;
virtual void HandlePacket(const protocol::KeepAlivePacket* packet) override; virtual void HandlePacket(const protocol::KeepAlivePacket* packet) override;
@@ -79,6 +44,10 @@ class ServerConnexion : public network::Connexion {
virtual void HandlePacket(const protocol::PlayerPositionAndRotationPacket* packet) override; virtual void HandlePacket(const protocol::PlayerPositionAndRotationPacket* packet) override;
virtual void HandlePacket(const protocol::PlayerShootPacket* packet) override; virtual void HandlePacket(const protocol::PlayerShootPacket* packet) override;
std::uint8_t GetID() const {
return m_ID;
}
virtual bool UpdateSocket() override; virtual bool UpdateSocket() override;
private: private:

View File

@@ -1,22 +1,10 @@
#pragma once #pragma once
/**
* \file ServerGame.h
* \brief File containing the blitz::server::ServerGame class
*/
#include "blitz/game/Game.h" #include "blitz/game/Game.h"
namespace blitz { namespace blitz {
namespace server { namespace server {
/**
* \struct ServerDuration
* \brief Structure containing the server game durations
* \var ServerDuration::m_GameDuration The game duration
* \var ServerDuration::m_PrepDuration The preparation duration
* \var ServerDuration::m_EndDuration The end duration
*/
struct ServerDuration { struct ServerDuration {
std::uint64_t m_GameDuration = 1000 * 3 * 60; std::uint64_t m_GameDuration = 1000 * 3 * 60;
std::uint64_t m_PrepDuration = 1000 * 10; std::uint64_t m_PrepDuration = 1000 * 10;
@@ -25,10 +13,6 @@ struct ServerDuration {
class Server; class Server;
/**
* \class ServerGame
* \brief Class used to manage the server game
*/
class ServerGame : public game::Game { class ServerGame : public game::Game {
private: private:
Server* m_Server; Server* m_Server;
@@ -36,57 +20,22 @@ class ServerGame : public game::Game {
ServerDuration m_ServerDuration; ServerDuration m_ServerDuration;
public: public:
/**
* \brief Constructor
* \param server The server
*/
ServerGame(Server* server); ServerGame(Server* server);
virtual ~ServerGame(); virtual ~ServerGame();
/** void CheckShoot(game::PlayerID player, Vec3f position, float yaw, float pitch);
* \brief Process a player shoot
* \param player The player
* \param position The position of the player
* \param yaw The yaw
* \param pitch The pitch
*/
void ProcessShoot(game::PlayerID player, Vec3f position, float yaw, float pitch);
/**
* \brief Process a player login
* \param player The player
* \param name The name of the player
*/
void AddPlayer(game::PlayerID player, const std::string& name) override; void AddPlayer(game::PlayerID player, const std::string& name) override;
/**
* \brief Remove a player from the game if he disconnected
*/
void RemovePlayer(game::PlayerID player) override; void RemovePlayer(game::PlayerID player) override;
/**
* \brief Update the game
* \param delta The delta time in milliseconds
*/
void Tick(std::uint64_t delta) override; void Tick(std::uint64_t delta) override;
/**
* \brief Set the game state
* \param gameState The game state
* \param duration The duration in milliseconds
*/
void SetGameState(game::GameState gameState, std::uint64_t duration); void SetGameState(game::GameState gameState, std::uint64_t duration);
/**
* \brief Get the server duration
* \return The server duration in milliseconds
*/
ServerDuration& GetServerDuration() { ServerDuration& GetServerDuration() {
return m_ServerDuration; return m_ServerDuration;
} }
/**
* \brief Send the player positions
*/
void SendServerConfig(); void SendServerConfig();
private: private:

View File

@@ -1,6 +1,5 @@
#include "blitz/network/Network.h" #include "blitz/network/Network.h"
#include "client/Client.h" #include "client/Client.h"
#include "client/audio/AudioManager.h"
#include "client/display/Display.h" #include "client/display/Display.h"
#include "client/render/MainRenderer.h" #include "client/render/MainRenderer.h"
@@ -13,7 +12,6 @@ int main(int argc, char** argv) {
return EXIT_FAILURE; return EXIT_FAILURE;
blitz::render::MainRenderer renderer(&client); blitz::render::MainRenderer renderer(&client);
blitz::audio::AudioManager audioManager(&client);
blitz::network::NetworkInitializer network; blitz::network::NetworkInitializer network;
while (!display.IsCloseRequested()) { while (!display.IsCloseRequested()) {

View File

@@ -1,17 +1,10 @@
#include "blitz/network/Network.h" #include "blitz/network/Network.h"
#include "blitz/misc/Log.h" #include "blitz/misc/Log.h"
#include <signal.h>
namespace blitz { namespace blitz {
namespace network { namespace network {
/* Catch Signal Handler function */
void signal_callback_handler(int signum) {
utils::LOGD("[Network] Caught a SIGPIPE !");
}
#ifdef _WIN32 #ifdef _WIN32
NetworkInitializer::NetworkInitializer() { NetworkInitializer::NetworkInitializer() {
WSADATA wsaData; WSADATA wsaData;
@@ -25,10 +18,7 @@ NetworkInitializer::~NetworkInitializer() {
WSACleanup(); WSACleanup();
} }
#else #else
NetworkInitializer::NetworkInitializer() { NetworkInitializer::NetworkInitializer() {}
/* Prevents the game for crashing when socket closes on the other side */
signal(SIGPIPE, signal_callback_handler);
}
NetworkInitializer::~NetworkInitializer() {} NetworkInitializer::~NetworkInitializer() {}
#endif #endif

View File

@@ -89,6 +89,8 @@ bool TCPSocket::Connect(const std::string& host, unsigned short port) {
return false; return false;
} }
SetBlocking(m_Blocking);
struct addrinfo* ptr = nullptr; struct addrinfo* ptr = nullptr;
for (ptr = result; ptr != nullptr; ptr = ptr->ai_next) { for (ptr = result; ptr != nullptr; ptr = ptr->ai_next) {
struct sockaddr* sockaddr = ptr->ai_addr; struct sockaddr* sockaddr = ptr->ai_addr;
@@ -121,15 +123,14 @@ size_t TCPSocket::Send(const unsigned char* data, size_t size) {
while (sent < size) { while (sent < size) {
int cur = send(m_Handle, reinterpret_cast<const char*>(data + sent), static_cast<int>(size - sent), 0); int cur = send(m_Handle, reinterpret_cast<const char*>(data + sent), static_cast<int>(size - sent), 0);
if (cur <= 0) { if (cur <= 0) {
m_Status = Status::Error;
Disconnect(); Disconnect();
m_Status = Status::Error; m_Status = Status::Error;
return 0; return 0;
} }
sent += static_cast<std::size_t>(cur); sent += static_cast<std::size_t>(cur);
} }
return sent; return sent;
} }

View File

@@ -13,7 +13,7 @@ DataBuffer GetAsset(const std::string& fileName) {
SDL_RWops* io = SDL_RWFromFile(fileName.c_str(), "rb"); SDL_RWops* io = SDL_RWFromFile(fileName.c_str(), "rb");
assert(io != nullptr && "Can't find the requested file !"); assert(io != nullptr);
std::int64_t bufferSize = SDL_RWsize(io); std::int64_t bufferSize = SDL_RWsize(io);

View File

@@ -1,6 +1,5 @@
#include "client/Client.h" #include "client/Client.h"
#include "blitz/misc/Log.h"
#include "blitz/protocol/packets/ChatPacket.h" #include "blitz/protocol/packets/ChatPacket.h"
#include "blitz/protocol/packets/DisconnectPacket.h" #include "blitz/protocol/packets/DisconnectPacket.h"
#include "blitz/protocol/packets/PlayerPositionAndRotationPacket.h" #include "blitz/protocol/packets/PlayerPositionAndRotationPacket.h"
@@ -18,13 +17,11 @@ Client::Client() :
m_Game(std::make_unique<client::ClientGame>(this, m_Connexion->GetDispatcher())) {} m_Game(std::make_unique<client::ClientGame>(this, m_Connexion->GetDispatcher())) {}
Client::~Client() { Client::~Client() {
Disconnect(); protocol::DisconnectPacket packet("Client");
m_Connexion->SendPacket(&packet);
} }
void Client::Update() { void Client::Update() {
if (m_Connexion->GetSocketStatus() != network::TCPSocket::Status::Connected)
return;
if (m_Connexion->UpdateSocket()) { if (m_Connexion->UpdateSocket()) {
static std::uint64_t lastTime = utils::GetTime(); static std::uint64_t lastTime = utils::GetTime();
@@ -32,8 +29,6 @@ void Client::Update() {
m_Game->Tick(utils::GetTime() - lastTime); m_Game->Tick(utils::GetTime() - lastTime);
lastTime = utils::GetTime(); lastTime = utils::GetTime();
} else {
Disconnect();
} }
} }
@@ -62,21 +57,11 @@ bool Client::CreateGame(std::uint16_t port, const std::string& pseudo) {
} }
void Client::Disconnect() { void Client::Disconnect() {
if (m_Connexion->GetSocketStatus() != network::TCPSocket::Status::Connected)
return;
protocol::DisconnectPacket packet("Client wants to leave !");
m_Connexion->SendPacket(&packet);
utils::LOGD("[Client] Disconnected !");
if (m_Server) { if (m_Server) {
m_Server->Stop(); m_Server->Stop();
} }
m_Connexion->CloseConnection(); m_Connexion->CloseConnection();
Reset(); Reset();
NotifyListeners(&game::ClientListener::OnGameLeave);
} }
void Client::Reset() { void Client::Reset() {

View File

@@ -5,7 +5,6 @@
#include "blitz/misc/PrettyLog.h" #include "blitz/misc/PrettyLog.h"
#include "blitz/protocol/packets/ChatPacket.h" #include "blitz/protocol/packets/ChatPacket.h"
#include "blitz/protocol/packets/ConnexionInfoPacket.h" #include "blitz/protocol/packets/ConnexionInfoPacket.h"
#include "blitz/protocol/packets/DisconnectPacket.h"
#include "blitz/protocol/packets/KeepAlivePacket.h" #include "blitz/protocol/packets/KeepAlivePacket.h"
#include "blitz/protocol/packets/PlayerLoginPacket.h" #include "blitz/protocol/packets/PlayerLoginPacket.h"
#include "client/Client.h" #include "client/Client.h"
@@ -53,8 +52,7 @@ void ClientConnexion::HandlePacket(const protocol::ChatPacket* packet) {
} }
void ClientConnexion::HandlePacket(const protocol::DisconnectPacket* packet) { void ClientConnexion::HandlePacket(const protocol::DisconnectPacket* packet) {
utils::LOG("[ClientConnexion] Disconnected ! Reason : " + packet->GetReason()); utils::LOG("Disconnected !");
m_Client->NotifyListeners(&game::ClientListener::OnGameLeave);
} }
void ClientConnexion::HandlePacket(const protocol::KeepAlivePacket* packet) { void ClientConnexion::HandlePacket(const protocol::KeepAlivePacket* packet) {
@@ -64,7 +62,6 @@ void ClientConnexion::HandlePacket(const protocol::KeepAlivePacket* packet) {
void ClientConnexion::HandlePacket(const protocol::ConnexionInfoPacket* packet) { void ClientConnexion::HandlePacket(const protocol::ConnexionInfoPacket* packet) {
m_PlayerID = packet->GetConnectionID(); m_PlayerID = packet->GetConnectionID();
utils::LOGD("[ClientConnexion] Logging in with pseudo " + m_PlayerName + " ...");
Login(m_PlayerName); Login(m_PlayerName);
} }

View File

@@ -1,27 +0,0 @@
#include "client/audio/AudioBuffer.h"
#include <AL/al.h>
namespace blitz {
namespace audio {
static const std::vector<unsigned int> AudioFormats = {
AL_FORMAT_MONO8,
AL_FORMAT_MONO16,
AL_FORMAT_STEREO8,
AL_FORMAT_STEREO16,
};
AudioBuffer::AudioBuffer(AudioData&& audioData) {
alGenBuffers(1, &m_ID);
alBufferData(m_ID, AudioFormats[audioData.m_Format], audioData.m_Buffer.data() + audioData.m_Buffer.GetReadOffset(),
audioData.m_Buffer.GetSize() - audioData.m_Buffer.GetReadOffset(), static_cast<ALsizei>(audioData.m_Frequency));
}
AudioBuffer::~AudioBuffer() {
alDeleteBuffers(1, &m_ID);
m_ID = 0;
}
} // namespace audio
} // namespace blitz

View File

@@ -1,47 +0,0 @@
#include "client/audio/AudioListener.h"
#include "blitz/misc/Log.h"
#include <AL/al.h>
#include <AL/alc.h>
namespace blitz {
namespace audio {
AudioListener::AudioListener() {
ALCdevice* device = alcOpenDevice(nullptr);
if (device) {
ALCcontext* context = alcCreateContext(device, nullptr);
alcMakeContextCurrent(context);
} else {
utils::LOGE("[AudioListener] Can't initialize sound !");
}
}
AudioListener::~AudioListener() {
ALCcontext* context = alcGetCurrentContext();
ALCdevice* device = alcGetContextsDevice(context);
alcMakeContextCurrent(NULL);
alcDestroyContext(context);
alcCloseDevice(device);
}
void AudioListener::SetGain(float a_Gain) {
alListenerf(AL_GAIN, a_Gain);
}
void AudioListener::SetPosition(const Vec3f& a_Position) {
alListener3f(AL_POSITION, a_Position.x, a_Position.y, a_Position.z);
}
void AudioListener::SetVelocity(const Vec3f& a_Velocity) {
alListener3f(AL_VELOCITY, a_Velocity.x, a_Velocity.y, a_Velocity.z);
}
void AudioListener::SetOrientation(const Vec3f& a_Orientation, const Vec3f& a_Up) {
Vec3f data[] = {a_Orientation, a_Up};
alListenerfv(AL_ORIENTATION, reinterpret_cast<float*>(data));
}
} // namespace audio
} // namespace blitz

View File

@@ -1,51 +0,0 @@
#include "client/audio/AudioLoader.h"
#include "blitz/misc/Log.h"
#include "client/AssetsManager.h"
namespace blitz {
namespace audio {
namespace AudioLoader {
struct WavHeader {
/* RIFF Chunk Descriptor */
uint8_t RIFF[4]; // RIFF Header Magic header
uint32_t ChunkSize; // RIFF Chunk Size
uint8_t WAVE[4]; // WAVE Header
/* "fmt" sub-chunk */
uint8_t FMT[4]; // FMT header
uint32_t Subchunk1Size; // Size of the fmt chunk
uint16_t AudioFormat; // Audio format 1=PCM,6=mulaw,7=alaw, 257=IBM Mu-Law, 258=IBM A-Law, 259=ADPCM
uint16_t NumOfChan; // Number of channels 1=Mono 2=Sterio
uint32_t SamplesPerSec; // Sampling Frequency in Hz
uint32_t BytesPerSec; // bytes per second
uint16_t BlockAlign; // 2=16-bit mono, 4=16-bit stereo
uint16_t BitsPerSample; // Number of bits per sample
/* "data" sub-chunk */
uint8_t Subchunk2ID[4]; // "data" string
uint32_t Subchunk2Size; // Sampled data length
};
AudioData LoadAudioFile(const std::string& filePath) {
DataBuffer fileBuffer = utils::AssetsManager::GetAsset(filePath);
WavHeader wavHeader;
fileBuffer >> wavHeader;
if (wavHeader.Subchunk2Size == 0) {
utils::LOGE("[AudioLoader] Failed to load sound " + filePath + " !");
}
fileBuffer.Resize(fileBuffer.GetReadOffset() + wavHeader.Subchunk2Size);
int audioFormat = (wavHeader.NumOfChan - 1) * 2 + (wavHeader.BitsPerSample / 8) - 1;
return {fileBuffer, AudioFormat(audioFormat), wavHeader.SamplesPerSec};
}
}; // namespace AudioLoader
} // namespace audio
} // namespace blitz

View File

@@ -1,43 +0,0 @@
#include "client/audio/AudioManager.h"
#include "client/Client.h"
#include "client/audio/AudioBuffer.h"
namespace blitz {
namespace audio {
AudioManager::AudioManager(Client* client) : m_Client(client) {
m_Listener.SetPosition({});
m_Listener.SetVelocity({});
m_Listener.SetGain(1.0f);
m_Listener.SetOrientation(blitz::Vec3f{0.0, 0.0, 0.0}, blitz::Vec3f{0.0, 1.0, 0.0});
InitMainMenuMusic();
m_MenuMusic->Play();
m_Client->BindListener(this);
}
void AudioManager::InitMainMenuMusic() {
AudioData audioData = AudioLoader::LoadAudioFile("sessionD.wav");
AudioBufferPtr audioBuffer = std::make_unique<AudioBuffer>(std::move(audioData));
m_MenuMusic = std::make_unique<AudioSource>();
m_MenuMusic->SetBuffer(std::move(audioBuffer));
m_MenuMusic->SetPosition({});
m_MenuMusic->SetVelocity({});
m_MenuMusic->SetPitch(1.0f);
m_MenuMusic->SetLooping(true);
}
void AudioManager::OnGameJoin() {
m_MenuMusic->Stop();
}
void AudioManager::OnGameLeave() {
m_MenuMusic->Play();
}
AudioManager::~AudioManager() {
m_Client->UnbindListener(this);
}
} // namespace audio
} // namespace blitz

View File

@@ -1,66 +0,0 @@
#include "client/audio/AudioSource.h"
#include <AL/al.h>
namespace blitz {
namespace audio {
AudioSource::AudioSource() {
alGenSources(1, &m_ID);
}
AudioSource::~AudioSource() {
alDeleteSources(1, &m_ID);
}
void AudioSource::SetGain(float a_Gain) {
alSourcef(m_ID, AL_GAIN, a_Gain);
}
void AudioSource::SetPitch(float a_Pitch) {
alSourcef(m_ID, AL_PITCH, a_Pitch);
}
void AudioSource::SetPosition(const Vec3f& a_Position) {
alSource3f(m_ID, AL_POSITION, a_Position.x, a_Position.y, a_Position.z);
}
void AudioSource::SetDirection(const Vec3f& a_Direction) {
alSource3f(m_ID, AL_DIRECTION, a_Direction.x, a_Direction.y, a_Direction.z);
}
void AudioSource::SetVelocity(const Vec3f& a_Velocity) {
alSource3f(m_ID, AL_VELOCITY, a_Velocity.x, a_Velocity.y, a_Velocity.z);
}
void AudioSource::SetLooping(bool a_Looping) {
alSourcei(m_ID, AL_LOOPING, a_Looping);
}
void AudioSource::SetBuffer(AudioBufferPtr&& a_Buffer) {
alSourcei(m_ID, AL_BUFFER, a_Buffer->GetID());
m_Buffer = std::move(a_Buffer);
}
AudioSource::SourceState AudioSource::GetSourceState() const {
int state;
alGetSourcei(m_ID, AL_SOURCE_STATE, &state);
return SourceState(state - AL_INITIAL);
}
void AudioSource::Play() {
alSourcePlay(m_ID);
}
void AudioSource::Pause() {
alSourcePause(m_ID);
}
void AudioSource::Stop() {
alSourceStop(m_ID);
}
} // namespace audio
} // namespace blitz

View File

@@ -53,7 +53,6 @@ void ClientGame::HandlePacket(const protocol::PlayerJoinPacket* packet) {
// Initialize camera // Initialize camera
if (packet->GetPlayerID() == m_Client->GetPlayerID()) { if (packet->GetPlayerID() == m_Client->GetPlayerID()) {
m_Client->NotifyListeners(&game::ClientListener::OnSpectatorChange, packet->GetPlayerID()); m_Client->NotifyListeners(&game::ClientListener::OnSpectatorChange, packet->GetPlayerID());
m_Client->NotifyListeners(&game::ClientListener::OnGameJoin);
} }
} }
@@ -69,9 +68,8 @@ void ClientGame::HandlePacket(const protocol::PlayerListPacket* packet) {
void ClientGame::HandlePacket(const protocol::PlayerStatsPacket* packet) { void ClientGame::HandlePacket(const protocol::PlayerStatsPacket* packet) {
game::Player* player = m_Client->GetGame()->GetPlayerById(packet->GetPlayerID()); game::Player* player = m_Client->GetGame()->GetPlayerById(packet->GetPlayerID());
if (!player) assert(player);
return; player->SetStats(packet->GetPlayerStats());
player->GetStats() = packet->GetPlayerStats();
m_LeaderBoard.Update(); m_LeaderBoard.Update();
} }

View File

@@ -15,7 +15,7 @@ LeaderBoardGui::LeaderBoardGui(GuiWidget* parent, Client* client) : GuiWidget(pa
LeaderBoardGui::~LeaderBoardGui() {} LeaderBoardGui::~LeaderBoardGui() {}
void LeaderBoardGui::Draw(const char* title, bool* p_open) { void LeaderBoardGui::Draw(const char* title, bool* p_open) {
static float leaderboard_width = 800.0f; static float leaderboard_width = 640.0f;
static float leaderboard_height = 450.0f; static float leaderboard_height = 450.0f;
ImGuiWindowFlags leaderboard_flags = ImGuiWindowFlags leaderboard_flags =

View File

@@ -2,7 +2,6 @@
#include "client/Client.h" #include "client/Client.h"
#include "client/display/InputManager.h" #include "client/display/InputManager.h"
#include "client/game/ClientGame.h"
#include "server/Server.h" #include "server/Server.h"
#include "server/game/ServerGame.h" #include "server/game/ServerGame.h"
#include <imgui.h> #include <imgui.h>
@@ -24,8 +23,8 @@ void ServerGui::Render() {
ImGuiWindowFlags servergui_flags = ImGuiWindowFlags servergui_flags =
ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar; ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar;
ImVec2 center = ImGui::GetMainViewport()->GetCenter(); ImVec2 center = ImGui::GetMainViewport()->GetCenter();
static float servergui_width = 1500.0f; static float servergui_width = 640.0f;
static float servergui_height = 800.0f; static float servergui_height = 640.0f;
const static ImVec2 buttonSize = {300, 60}; const static ImVec2 buttonSize = {300, 60};
@@ -34,47 +33,13 @@ void ServerGui::Render() {
if (ImGui::BeginPopupModal("FENETRE D'ADMIN", nullptr, servergui_flags)) { if (ImGui::BeginPopupModal("FENETRE D'ADMIN", nullptr, servergui_flags)) {
InputManager::GrabMouse(false); InputManager::GrabMouse(false);
ImGui::BeginChild("Mutateurs JOUEURS", ImVec2(servergui_width * (1.0f / 3.0f), 0.0f), true); ImGui::BeginChild("Mutateurs PARTIE", ImVec2(servergui_width * (5.0f / 10.0f), 0.0f), true);
{
ImGui::Text("JOUEURS");
ImGui::NewLine();
ImGui::Text("AJOUTER JOUEUR");
if (ImGui::Button("Ajouter Bot", buttonSize)) {
m_Client->GetServer()->AddBot();
}
ImGui::NewLine();
ImGui::Text("KICK JOUEURS");
bool hasOtherPlayers = false;
auto& players = m_Client->GetGame()->GetLeaderBoard().GetPlayers();
float kickButtonSizex = ImGui::CalcTextSize("Kick").x + 50.0f;
float kickButtonSizey = ImGui::CalcTextSize("Kick").y + 20.0f;
for (game::Player* player : players) {
if (player->GetID() == m_Client->GetPlayerID()) {
continue; // Skip the current player
}
hasOtherPlayers = true;
ImGui::Text("%s", player->GetName().c_str());
ImGui::SameLine();
ImGui::PushID(player->GetID());
if (ImGui::Button("Kick", {kickButtonSizex, kickButtonSizey})) {
m_Client->GetServer()->KickPlayer(player->GetID());
}
ImGui::PopID();
}
if (!hasOtherPlayers) {
ImGui::Text("Aucun autre joueur");
}
}
ImGui::EndChild();
ImGui::SameLine();
ImGui::BeginChild("Mutateurs PARTIE", ImVec2(servergui_width * (1.0f / 3.0f), 0.0f), true);
ImGui::Text("PARTIE"); ImGui::Text("PARTIE");
ImGui::NewLine();
if (ImGui::Button("Ajouter Bot", buttonSize)) {
m_Client->GetServer()->AddBot();
}
ImGui::NewLine(); ImGui::NewLine();
ImGui::Text("GRAVITE"); ImGui::Text("GRAVITE");
@@ -121,7 +86,7 @@ void ServerGui::Render() {
ImGui::SameLine(); ImGui::SameLine();
ImGui::BeginChild("MUTATEUR TEMPS", ImVec2(servergui_width * (0.9f / 3.0f), 0.0f), true); ImGui::BeginChild("MUTATEUR TEMPS", ImVec2(servergui_width * (4.5f / 10.0f), 0.0f), true);
static int gameDurMin = static_cast<int>(m_Client->GetServer()->GetGame().GetServerDuration().m_GameDuration / 1000) / 60; static int gameDurMin = static_cast<int>(m_Client->GetServer()->GetGame().GetServerDuration().m_GameDuration / 1000) / 60;
static int gameDurSec = static_cast<int>(m_Client->GetServer()->GetGame().GetServerDuration().m_GameDuration / 1000) % 60; static int gameDurSec = static_cast<int>(m_Client->GetServer()->GetGame().GetServerDuration().m_GameDuration / 1000) % 60;

View File

@@ -106,7 +106,7 @@ void Server::Accept() {
game::PlayerID newPlayerID = GetNewPlayerID(); game::PlayerID newPlayerID = GetNewPlayerID();
auto con = std::make_unique<ServerConnexion>(this, newSocket, newPlayerID); auto con = std::make_unique<ServerConnexion>(this, newSocket, newPlayerID);
m_Connections.insert(ConnexionMap::value_type{newPlayerID, std::move(con)}); m_Connections.insert(ConnexionMap::value_type{newPlayerID, std::move(con)});
m_Connections[newPlayerID]->Init(); m_Connections[newPlayerID]->Start();
newPlayerID++; newPlayerID++;
} }
} }
@@ -153,6 +153,9 @@ void Server::BroadcastChatMessage(const std::string& msg) {
void Server::RemoveConnexion(std::uint8_t connexionID) { void Server::RemoveConnexion(std::uint8_t connexionID) {
m_Connections.erase(connexionID); m_Connections.erase(connexionID);
protocol::PlayerLeavePacket packet(connexionID);
BroadcastPacket(&packet);
} }
std::uint16_t Server::GetListeningPort() { std::uint16_t Server::GetListeningPort() {
@@ -170,26 +173,5 @@ void Server::AddBot() {
botPlayer->SetBot(); botPlayer->SetBot();
} }
void Server::KickPlayer(game::PlayerID playerID) {
auto it = m_Connections.find(playerID);
if (it != m_Connections.end()) {
protocol::DisconnectPacket packet("Tu dois disparaître (in game) !");
m_Connections.at(playerID)->SendPacket(&packet);
}
game::Player* player = m_Game.GetPlayerById(playerID);
if (!player)
return;
m_Game.RemovePlayer(playerID);
if (player->IsBot()) {
} else {
RemoveConnexion(playerID);
}
}
} // namespace server } // namespace server
} // namespace blitz } // namespace blitz

View File

@@ -60,8 +60,8 @@ bool ServerConnexion::UpdateSocket() {
void ServerConnexion::CheckKeepAlive() { void ServerConnexion::CheckKeepAlive() {
std::uint64_t time = utils::GetTime(); std::uint64_t time = utils::GetTime();
if (time - m_KeepAlive.SendTime > KEEP_ALIVE_TIMEOUT) { if (time - m_KeepAlive.sendTime > KEEP_ALIVE_TIMEOUT) {
if (m_KeepAlive.RecievedResponse) { if (m_KeepAlive.recievedResponse) {
SendKeepAlive(); SendKeepAlive();
} else { } else {
protocol::DisconnectPacket packet("Time out"); protocol::DisconnectPacket packet("Time out");
@@ -72,14 +72,14 @@ void ServerConnexion::CheckKeepAlive() {
} }
void ServerConnexion::SendKeepAlive() { void ServerConnexion::SendKeepAlive() {
m_KeepAlive.KeepAliveID = utils::GetRandomInt<std::uint64_t>(0, RAND_MAX); m_KeepAlive.keepAliveID = utils::GetRandomInt<std::uint64_t>(0, RAND_MAX);
m_KeepAlive.RecievedResponse = false; m_KeepAlive.recievedResponse = false;
protocol::KeepAlivePacket keepAlivePacket(m_KeepAlive.KeepAliveID); protocol::KeepAlivePacket keepAlivePacket(m_KeepAlive.keepAliveID);
SendPacket(&keepAlivePacket); SendPacket(&keepAlivePacket);
std::uint64_t time = utils::GetTime(); std::uint64_t time = utils::GetTime();
m_KeepAlive.SendTime = time; m_KeepAlive.sendTime = time;
} }
void ServerConnexion::InitPlayerChatColor() { void ServerConnexion::InitPlayerChatColor() {
@@ -107,10 +107,10 @@ void ServerConnexion::HandlePacket(const protocol::PlayerLoginPacket* packet) {
} }
void ServerConnexion::HandlePacket(const protocol::KeepAlivePacket* packet) { void ServerConnexion::HandlePacket(const protocol::KeepAlivePacket* packet) {
if (packet->GetAliveID() != m_KeepAlive.KeepAliveID) if (packet->GetAliveID() != m_KeepAlive.keepAliveID)
return; return;
m_KeepAlive.RecievedResponse = true; m_KeepAlive.recievedResponse = true;
} }
void ServerConnexion::HandlePacket(const protocol::DisconnectPacket* packet) { void ServerConnexion::HandlePacket(const protocol::DisconnectPacket* packet) {
@@ -139,10 +139,10 @@ void ServerConnexion::HandlePacket(const protocol::PlayerShootPacket* packet) {
protocol::PlayerShootPacket broadcastShoot(packet->GetPosition(), packet->GetYaw(), packet->GetPitch(), m_Player->GetID()); protocol::PlayerShootPacket broadcastShoot(packet->GetPosition(), packet->GetYaw(), packet->GetPitch(), m_Player->GetID());
m_Server->BroadcastPacket(&broadcastShoot); m_Server->BroadcastPacket(&broadcastShoot);
m_Server->GetGame().ProcessShoot(m_Player->GetID(), packet->GetPosition(), packet->GetYaw(), packet->GetPitch()); m_Server->GetGame().CheckShoot(m_Player->GetID(), packet->GetPosition(), packet->GetYaw(), packet->GetPitch());
} }
void ServerConnexion::Init() { void ServerConnexion::Start() {
InitConnection(); InitConnection();
SendKeepAlive(); SendKeepAlive();
} }
@@ -179,7 +179,12 @@ ServerConnexion::~ServerConnexion() {
GetDispatcher()->UnregisterHandler(this); GetDispatcher()->UnregisterHandler(this);
m_Server->GetGame().RemovePlayer(m_ID); if (m_Player) {
std::string leaveMessage = utils::Format("%s a quitte la partie !", m_Player->GetName().c_str());
utils::LOG("[Server] " + leaveMessage);
m_Server->BroadcastChatMessage(protocol::ChatPacket::GetTextColor(protocol::YELLOW) + leaveMessage);
}
} }
} // namespace server } // namespace server

View File

@@ -6,7 +6,6 @@
#include "blitz/misc/Random.h" #include "blitz/misc/Random.h"
#include "blitz/protocol/packets/ChatPacket.h" #include "blitz/protocol/packets/ChatPacket.h"
#include "blitz/protocol/packets/PlayerJoinPacket.h" #include "blitz/protocol/packets/PlayerJoinPacket.h"
#include "blitz/protocol/packets/PlayerLeavePacket.h"
#include "blitz/protocol/packets/PlayerPositionAndRotationPacket.h" #include "blitz/protocol/packets/PlayerPositionAndRotationPacket.h"
#include "blitz/protocol/packets/PlayerStatsPacket.h" #include "blitz/protocol/packets/PlayerStatsPacket.h"
#include "blitz/protocol/packets/ServerConfigPacket.h" #include "blitz/protocol/packets/ServerConfigPacket.h"
@@ -37,7 +36,6 @@ void ServerGame::Tick(std::uint64_t delta) {
if (m_PositionTimer.Update(delta)) { if (m_PositionTimer.Update(delta)) {
SendPlayerPositions(); SendPlayerPositions();
} }
if (m_GameState != game::gsWaiting && m_GameTimer.Update(delta)) { if (m_GameState != game::gsWaiting && m_GameTimer.Update(delta)) {
switch (m_GameState) { switch (m_GameState) {
case game::gsPreparing: case game::gsPreparing:
@@ -70,7 +68,7 @@ void ServerGame::SendPlayerPositions() {
} }
} }
void ServerGame::ProcessShoot(game::PlayerID shooter, Vec3f position, float yaw, float pitch) { void ServerGame::CheckShoot(game::PlayerID shooter, Vec3f position, float yaw, float pitch) {
maths::Ray shootRay; maths::Ray shootRay;
shootRay.origin = position + Vec3f{0.0, 1.75, 0.0}; shootRay.origin = position + Vec3f{0.0, 1.75, 0.0};
shootRay.direction = { shootRay.direction = {
@@ -114,24 +112,10 @@ void ServerGame::AddPlayer(game::PlayerID player, const std::string& name) {
} }
} }
void ServerGame::RemovePlayer(game::PlayerID playerID) { void ServerGame::RemovePlayer(game::PlayerID player) {
Game::RemovePlayer(player);
game::Player* player = GetPlayerById(playerID); if (m_GameState == game::gsGame && m_Players.size() <= 1) {
if (!player)
return;
protocol::PlayerLeavePacket packet(playerID);
m_Server->BroadcastPacket(&packet);
std::string leaveMessage = utils::Format("%s a quitte la partie !", player->GetName().c_str());
utils::LOG("[Server] " + leaveMessage);
m_Server->BroadcastChatMessage(protocol::ChatPacket::GetTextColor(protocol::YELLOW) + leaveMessage);
Game::RemovePlayer(playerID);
if ((m_GameState == game::gsGame || m_GameState == game::gsPreparing) && m_Players.size() <= 1) {
CancelGame(); CancelGame();
} }
} }
@@ -160,10 +144,7 @@ void ServerGame::UpdateHP(game::Player& player, float newHP) {
return; return;
protocol::UpdateHealthPacket packet(player.GetHP()); protocol::UpdateHealthPacket packet(player.GetHP());
m_Server->GetConnexions().at(player.GetID())->SendPacket(&packet);
auto it = m_Server->GetConnexions().find(player.GetID());
if (it != m_Server->GetConnexions().end())
it->second->SendPacket(&packet);
} }
void ServerGame::UpdatePlayerStats() { void ServerGame::UpdatePlayerStats() {

View File

@@ -8,7 +8,7 @@ if is_plat("linux") and is_arch("arm64-v8a") then
end end
add_requires("libsdl 2.28.3", {configs = {sdlmain = false}}) add_requires("libsdl 2.28.3", {configs = {sdlmain = false}})
add_requires(opengl, "assimp 5.3.1", "nlohmann_json", "openal-soft") add_requires(opengl, "assimp 5.3.1", "nlohmann_json")
-- Client binary (default) -- Client binary (default)
@@ -26,7 +26,7 @@ target("BlitzClient")
-- Libraries -- Libraries
add_deps("Blitz") add_deps("Blitz")
add_packages("libsdl", opengl, "assimp", "nlohmann_json", "openal-soft") add_packages("libsdl", opengl, "assimp", "nlohmann_json")
add_includedirs("../libs", "../libs/imgui") add_includedirs("../libs", "../libs/imgui")
add_files("../libs/imgui/**.cpp") add_files("../libs/imgui/**.cpp")