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 5 #ifndef TimeUtils_DEFINED 6 #define TimeUtils_DEFINED 7 8 #include "include/core/SkTypes.h" 9 10 #include <cmath> 11 12 namespace TimeUtils { 13 // Returns 0 if the timer is stopped. Behavior is undefined if the timer 14 // has been running longer than SK_MSecMax. NanosToMSec(double nanos)15 static inline SkMSec NanosToMSec(double nanos) { 16 const double msec = nanos * 1e-6; 17 SkASSERT(SK_MSecMax >= msec); 18 return static_cast<SkMSec>(msec); 19 } 20 NanosToSeconds(double nanos)21 static inline double NanosToSeconds(double nanos) { 22 return nanos * 1e-9; 23 } 24 25 // Return the time scaled by "speed" and (if not zero) mod by period. 26 static inline float Scaled(float time, float speed, float period = 0) { 27 double value = time * speed; 28 if (period) { 29 value = ::fmod(value, (double)(period)); 30 } 31 return (float)value; 32 } 33 34 // Transitions from ends->mid->ends linearly over period time. The phase 35 // specifies a phase shift in time units. PingPong(double time,float period,float phase,float ends,float mid)36 static inline float PingPong(double time, 37 float period, 38 float phase, 39 float ends, 40 float mid) { 41 double value = ::fmod(time + phase, period); 42 double half = period / 2.0; 43 double diff = ::fabs(value - half); 44 return (float)(ends + (1.0 - diff / half) * (mid - ends)); 45 } 46 } // namespace TimeUtils 47 #endif 48