Nazara Engine  0.4
A fast, complete, cross-platform API designed for game development
NetPacket.hpp
1 // Copyright (C) 2017 Jérôme Leclercq
2 // This file is part of the "Nazara Engine - Core module"
3 // For conditions of distribution and use, see copyright notice in Config.hpp
4 
5 #pragma once
6 
7 #ifndef NAZARA_NETPACKET_HPP
8 #define NAZARA_NETPACKET_HPP
9 
10 #include <Nazara/Prerequesites.hpp>
11 #include <Nazara/Core/ByteStream.hpp>
12 #include <Nazara/Core/MemoryStream.hpp>
13 #include <Nazara/Core/Mutex.hpp>
14 #include <Nazara/Network/Config.hpp>
15 
16 namespace Nz
17 {
18  class NAZARA_NETWORK_API NetPacket : public ByteStream
19  {
20  friend class Network;
21 
22  public:
23  inline NetPacket();
24  inline NetPacket(UInt16 netCode, std::size_t minCapacity = 0);
25  inline NetPacket(UInt16 netCode, const void* ptr, std::size_t size);
26  NetPacket(const NetPacket&) = delete;
27  NetPacket(NetPacket&& packet);
28  inline ~NetPacket();
29 
30  inline const UInt8* GetConstData() const;
31  inline UInt8* GetData() const;
32  inline size_t GetDataSize() const;
33  inline UInt16 GetNetCode() const;
34 
35  virtual void OnReceive(UInt16 netCode, const void* data, std::size_t size);
36  virtual const void* OnSend(std::size_t* newSize) const;
37 
38  inline void Reset();
39  inline void Reset(UInt16 netCode, std::size_t minCapacity = 0);
40  inline void Reset(UInt16 netCode, const void* ptr, std::size_t size);
41 
42  inline void Resize(std::size_t newSize);
43 
44  inline void SetNetCode(UInt16 netCode);
45 
46  NetPacket& operator=(const NetPacket&) = delete;
47  NetPacket& operator=(NetPacket&& packet);
48 
49  static bool DecodeHeader(const void* data, UInt16* packetSize, UInt16* netCode);
50  static bool EncodeHeader(void* data, UInt16 packetSize, UInt16 netCode);
51 
52  static constexpr std::size_t HeaderSize = sizeof(UInt16) + sizeof(UInt16); //< PacketSize + NetCode
53 
54  private:
55  void OnEmptyStream() override;
56 
57  void FreeStream();
58  void InitStream(std::size_t minCapacity, UInt64 cursorPos, OpenModeFlags openMode);
59 
60  static bool Initialize();
61  static void Uninitialize();
62 
63  std::unique_ptr<ByteArray> m_buffer;
64  MemoryStream m_memoryStream;
65  UInt16 m_netCode;
66 
67  static std::unique_ptr<Mutex> s_availableBuffersMutex;
68  static std::vector<std::pair<std::size_t, std::unique_ptr<ByteArray>>> s_availableBuffers;
69  };
70 }
71 
72 #include <Nazara/Network/NetPacket.inl>
73 
74 #endif // NAZARA_NETPACKET_HPP
TODO: Inherit SoundEmitter from Node.
Definition: Algorithm.hpp:12
Network class that represents a packet.
Definition: NetPacket.hpp:18
Core class that represents a stream of bytes.
Definition: ByteStream.hpp:19
Network class that represents the module initializer of Network.
Definition: Network.hpp:15
Constructs a MemoryStream object by default.
Definition: MemoryStream.hpp:17