1 /*
2 Copyright (c) 2019 Timur Gafarov
3 
4 Boost Software License - Version 1.0 - August 17th, 2003
5 Permission is hereby granted, free of charge, to any person or organization
6 obtaining a copy of the software and accompanying documentation covered by
7 this license (the "Software") to use, reproduce, display, distribute,
8 execute, and transmit the Software, and to prepare derivative works of the
9 Software, and to permit third-parties to whom the Software is furnished to
10 do so, all subject to the following:
11 
12 The copyright notices in the Software and this entire statement, including
13 the above license grant, this restriction and the following disclaimer,
14 must be included in all copies of the Software, in whole or in part, and
15 all derivative works of the Software, unless such copies or derivative
16 works are solely in the form of machine-executable object code generated by
17 a source language processor.
18 
19 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
22 SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
23 FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
24 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25 DEALINGS IN THE SOFTWARE.
26 */
27 
28 module dagon.core.time;
29 
30 import dlib.core.ownership;
31 
32 struct Time
33 {
34     double delta;
35     double elapsed;
36 }
37 
38 class Cadencer: Owner
39 {
40     protected:
41     double elapsedTime = 0.0;
42     double timeStep = 0.0;
43     double fpsTimeCounter = 0.0;
44     int fpsCounter = 0;
45     void delegate(Time) callback;
46     
47     public:
48     int fps = 0;
49     
50     this(void delegate(Time) callback, uint freq, Owner owner)
51     {
52         super(owner);
53         this.callback = callback;
54         timeStep = 1.0 / cast(double)freq;
55     }
56     
57     void update(Time t)
58     {
59         elapsedTime += t.delta;
60         fpsTimeCounter += t.delta;
61         
62         if (elapsedTime >= timeStep)
63         {
64             callback(Time(timeStep, t.elapsed));
65             elapsedTime -= timeStep;
66             fpsCounter++;
67         }
68         
69         if (fpsTimeCounter >= 1.0) // 1 sec interval
70         {
71             fps = fpsCounter;
72             fpsCounter = 0;
73             fpsTimeCounter = 0;
74         }
75     }
76 }