Packet.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. #ifndef PACKET_H
  2. #define PACKET_H
  3. #include "math/Vector.h"
  4. #include "utils/Buffer.h"
  5. #include "utils/StringBuffer.h"
  6. #include "utils/Types.h"
  7. enum class PacketSendMode { RELIABLE, SEQUENCED, UNSEQUENCED };
  8. class InPacket {
  9. const char* data;
  10. int size;
  11. int index;
  12. public:
  13. InPacket(const void* data, int size);
  14. bool read(uint8& u);
  15. bool read(uint16& u);
  16. bool read(uint32& u);
  17. bool read(int8& s);
  18. bool read(int16& s);
  19. bool read(int32& s);
  20. bool read(float& f);
  21. template<int N>
  22. bool read(StringBuffer<N>& s) {
  23. uint16 end;
  24. if(read(end)) {
  25. return true;
  26. }
  27. s.clear();
  28. for(unsigned int i = 0; i < end; i++) {
  29. int8 c;
  30. if(read(c)) {
  31. return true;
  32. }
  33. s.append(c);
  34. }
  35. return false;
  36. }
  37. template<int N, typename T>
  38. bool read(Vector<N, T>& v) {
  39. for(int i = 0; i < N; i++) {
  40. if(read(v[i])) {
  41. return true;
  42. }
  43. }
  44. return false;
  45. }
  46. private:
  47. bool read(void* buffer, int length);
  48. };
  49. struct OutPacket {
  50. Buffer buffer;
  51. OutPacket(int initialSize);
  52. OutPacket& writeU8(uint8 u);
  53. OutPacket& writeU16(uint16 u);
  54. OutPacket& writeU32(uint32 u);
  55. OutPacket& writeS8(int8 s);
  56. OutPacket& writeS16(int16 s);
  57. OutPacket& writeS32(int32 s);
  58. OutPacket& writeFloat(float f);
  59. template<int N>
  60. OutPacket& writeString(const StringBuffer<N>& s) {
  61. int end = s.getLength() > 65535 ? 65535 : s.getLength();
  62. writeU16(static_cast<uint16>(end));
  63. for(int i = 0; i < end; i++) {
  64. writeS8(s[i]);
  65. }
  66. return *this;
  67. }
  68. template<int N>
  69. OutPacket& writeVector(const Vector<N, int>& v) {
  70. for(int i = 0; i < N; i++) {
  71. writeS32(v[i]);
  72. }
  73. return *this;
  74. }
  75. template<int N>
  76. OutPacket& writeVector(const Vector<N, float>& v) {
  77. for(int i = 0; i < N; i++) {
  78. writeFloat(v[i]);
  79. }
  80. return *this;
  81. }
  82. };
  83. #endif