LinearCurve.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. #include <Jolt/ObjectStream/SerializableObject.h>
  5. namespace JPH {
  6. class StreamOut;
  7. class StreamIn;
  8. // A set of points (x, y) that form a linear curve
  9. class LinearCurve
  10. {
  11. public:
  12. JPH_DECLARE_SERIALIZABLE_NON_VIRTUAL(LinearCurve)
  13. /// A point on the curve
  14. class Point
  15. {
  16. public:
  17. JPH_DECLARE_SERIALIZABLE_NON_VIRTUAL(Point)
  18. float mX = 0.0f;
  19. float mY = 0.0f;
  20. };
  21. /// Remove all points
  22. void Clear() { mPoints.clear(); }
  23. /// Reserve memory for inNumPoints points
  24. void Reserve(uint inNumPoints) { mPoints.reserve(inNumPoints); }
  25. /// Add a point to the curve. Points must be inserted in ascending X or Sort() needs to be called when all points have been added.
  26. /// @param inX X value
  27. /// @param inY Y value
  28. void AddPoint(float inX, float inY) { mPoints.push_back({ inX, inY }); }
  29. /// Sort the points on X ascending
  30. void Sort() { sort(mPoints.begin(), mPoints.end(), [](const Point &inLHS, const Point &inRHS) { return inLHS.mX < inRHS.mX; }); }
  31. /// Get the lowest X value
  32. float GetMinX() const { return mPoints.empty()? 0.0f : mPoints.front().mX; }
  33. /// Get the highest X value
  34. float GetMaxX() const { return mPoints.empty()? 0.0f : mPoints.back().mX; }
  35. /// Sample value on the curve
  36. /// @param inX X value to sample at
  37. /// @return Interpolated Y value
  38. float GetValue(float inX) const;
  39. /// Saves the state of this object in binary form to inStream.
  40. void SaveBinaryState(StreamOut &inStream) const;
  41. /// Restore the state of this object from inStream.
  42. void RestoreBinaryState(StreamIn &inStream);
  43. /// The points on the curve, should be sorted ascending by x
  44. using Points = vector<Point>;
  45. Points mPoints;
  46. };
  47. } // JPH