TimeUtils.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // Copyright 2019 Google LLC
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef TimeUtils_DEFINED
  5. #define TimeUtils_DEFINED
  6. #include "include/core/SkTypes.h"
  7. #include <cmath>
  8. namespace TimeUtils {
  9. // Returns 0 if the timer is stopped. Behavior is undefined if the timer
  10. // has been running longer than SK_MSecMax.
  11. static inline SkMSec NanosToMSec(double nanos) {
  12. const double msec = nanos * 1e-6;
  13. SkASSERT(SK_MSecMax >= msec);
  14. return static_cast<SkMSec>(msec);
  15. }
  16. static inline double NanosToSeconds(double nanos) {
  17. return nanos * 1e-9;
  18. }
  19. // Return the time scaled by "speed" and (if not zero) mod by period.
  20. static inline float Scaled(float time, float speed, float period = 0) {
  21. double value = time * speed;
  22. if (period) {
  23. value = ::fmod(value, (double)(period));
  24. }
  25. return (float)value;
  26. }
  27. // Transitions from ends->mid->ends linearly over period time. The phase
  28. // specifies a phase shift in time units.
  29. static inline float PingPong(double time,
  30. float period,
  31. float phase,
  32. float ends,
  33. float mid) {
  34. double value = ::fmod(time + phase, period);
  35. double half = period / 2.0;
  36. double diff = ::fabs(value - half);
  37. return (float)(ends + (1.0 - diff / half) * (mid - ends));
  38. }
  39. } // namespace TimeUtils
  40. #endif