StateRecorderImpl.cpp 2.0 KB

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