StateRecorderImpl.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <Jolt/Jolt.h>
  5. #include <Jolt/Physics/StateRecorderImpl.h>
  6. JPH_NAMESPACE_BEGIN
  7. void StateRecorderImpl::WriteBytes(const void *inData, size_t inNumBytes)
  8. {
  9. mStream.write((const char *)inData, inNumBytes);
  10. }
  11. void StateRecorderImpl::Rewind()
  12. {
  13. mStream.seekg(0, std::stringstream::beg);
  14. }
  15. void StateRecorderImpl::Clear()
  16. {
  17. mStream.clear();
  18. mStream.str({});
  19. }
  20. void StateRecorderImpl::ReadBytes(void *outData, size_t inNumBytes)
  21. {
  22. if (IsValidating())
  23. {
  24. // Read data in temporary buffer to compare with current value
  25. void *data = JPH_STACK_ALLOC(inNumBytes);
  26. mStream.read((char *)data, inNumBytes);
  27. if (memcmp(data, outData, inNumBytes) != 0)
  28. {
  29. // Mismatch, print error
  30. Trace("Mismatch reading %u bytes", (uint)inNumBytes);
  31. for (size_t i = 0; i < inNumBytes; ++i)
  32. {
  33. int b1 = reinterpret_cast<uint8 *>(outData)[i];
  34. int b2 = reinterpret_cast<uint8 *>(data)[i];
  35. if (b1 != b2)
  36. Trace("Offset %d: %02X -> %02X", i, b1, b2);
  37. }
  38. JPH_BREAKPOINT;
  39. }
  40. // Copy the temporary data to the final destination
  41. memcpy(outData, data, inNumBytes);
  42. return;
  43. }
  44. mStream.read((char *)outData, inNumBytes);
  45. }
  46. bool StateRecorderImpl::IsEqual(StateRecorderImpl &inReference)
  47. {
  48. // Get length of new state
  49. mStream.seekg(0, std::stringstream::end);
  50. std::streamoff this_len = mStream.tellg();
  51. mStream.seekg(0, std::stringstream::beg);
  52. // Get length of old state
  53. inReference.mStream.seekg(0, std::stringstream::end);
  54. std::streamoff reference_len = inReference.mStream.tellg();
  55. inReference.mStream.seekg(0, std::stringstream::beg);
  56. // Compare size
  57. bool fail = reference_len != this_len;
  58. if (fail)
  59. {
  60. Trace("Failed to properly recover state, different stream length!");
  61. return false;
  62. }
  63. // Compare byte by byte
  64. for (std::streamoff i = 0, l = this_len; !fail && i < l; ++i)
  65. {
  66. fail = inReference.mStream.get() != mStream.get();
  67. if (fail)
  68. {
  69. Trace("Failed to properly recover state, different at offset %d!", (int)i);
  70. return false;
  71. }
  72. }
  73. return true;
  74. }
  75. JPH_NAMESPACE_END