StreamIn.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #pragma once
  5. #include <Jolt/Core/NonCopyable.h>
  6. JPH_NAMESPACE_BEGIN
  7. /// Simple binary input stream
  8. class JPH_EXPORT StreamIn : public NonCopyable
  9. {
  10. public:
  11. /// Virtual destructor
  12. virtual ~StreamIn() = default;
  13. /// Read a string of bytes from the binary stream
  14. virtual void ReadBytes(void *outData, size_t inNumBytes) = 0;
  15. /// Returns true when an attempt has been made to read past the end of the file
  16. virtual bool IsEOF() const = 0;
  17. /// Returns true if there was an IO failure
  18. virtual bool IsFailed() const = 0;
  19. /// Read a primitive (e.g. float, int, etc.) from the binary stream
  20. template <class T>
  21. void Read(T &outT)
  22. {
  23. ReadBytes(&outT, sizeof(outT));
  24. }
  25. /// Read a vector of primitives from the binary stream
  26. template <class T, class A>
  27. void Read(std::vector<T, A> &outT)
  28. {
  29. typename Array<T>::size_type len = outT.size(); // Initialize to previous array size, this is used for validation in the StateRecorder class
  30. Read(len);
  31. if (!IsEOF() && !IsFailed())
  32. {
  33. outT.resize(len);
  34. for (typename Array<T>::size_type i = 0; i < len; ++i)
  35. Read(outT[i]);
  36. }
  37. else
  38. outT.clear();
  39. }
  40. /// Read a string from the binary stream (reads the number of characters and then the characters)
  41. template <class Type, class Traits, class Allocator>
  42. void Read(std::basic_string<Type, Traits, Allocator> &outString)
  43. {
  44. typename std::basic_string<Type, Traits, Allocator>::size_type len = 0;
  45. Read(len);
  46. if (!IsEOF() && !IsFailed())
  47. {
  48. outString.resize(len);
  49. ReadBytes(outString.data(), len * sizeof(Type));
  50. }
  51. else
  52. outString.clear();
  53. }
  54. /// Read a Vec3 (don't read W)
  55. void Read(Vec3 &outVec)
  56. {
  57. ReadBytes(&outVec, 3 * sizeof(float));
  58. outVec = Vec3::sFixW(outVec.mValue);
  59. }
  60. /// Read a DVec3 (don't read W)
  61. void Read(DVec3 &outVec)
  62. {
  63. ReadBytes(&outVec, 3 * sizeof(double));
  64. outVec = DVec3::sFixW(outVec.mValue);
  65. }
  66. /// Read a DMat44 (don't read W component of translation)
  67. void Read(DMat44 &outVec)
  68. {
  69. Vec4 x, y, z;
  70. Read(x);
  71. Read(y);
  72. Read(z);
  73. DVec3 t;
  74. Read(t);
  75. outVec = DMat44(x, y, z, t);
  76. }
  77. };
  78. JPH_NAMESPACE_END