gameui

view src/boolanm.cc @ 2:e5b1525084f7

boolanim
author John Tsiombikas <nuclear@member.fsf.org>
date Thu, 20 Mar 2014 07:03:58 +0200
parents
children f1014234dece
line source
1 #include "boolanm.h"
3 static long default_get_msec();
5 BoolAnim::BoolAnim(bool st)
6 {
7 value = st ? 1.0 : 0.0;
8 trans_dir = 0.0;
9 trans_start = 0;
10 trans_dur = 1000;
11 get_msec = default_get_msec;
12 }
14 void BoolAnim::update(long tm) const
15 {
16 if(trans_dir == 0.0) return;
18 float dt = (tm - trans_start) / 1000.0;
19 float t = dt / (trans_dur / 1000.0);
21 if(trans_dir > 0.0) {
22 value = t;
23 } else {
24 value = 1.0 - t;
25 }
27 if(value < 0.0) {
28 value = 0.0;
29 trans_dir = 0.0;
30 } else if(value > 1.0) {
31 value = 1.0;
32 trans_dir = 0.0;
33 }
34 }
36 void BoolAnim::set_transition_duration(long dur)
37 {
38 trans_dur = dur;
39 }
41 void BoolAnim::set_time_callback(long (*time_func)())
42 {
43 get_msec = time_func;
44 }
46 void BoolAnim::change(bool st)
47 {
48 change(st, get_msec());
49 }
51 void BoolAnim::change(bool st, long tm)
52 {
53 trans_dir = st ? 1.0 : -1.0;
54 trans_start = tm;
55 }
57 bool BoolAnim::get_state() const
58 {
59 return get_state(get_msec());
60 }
62 bool BoolAnim::get_state(long tm) const
63 {
64 update(tm);
66 // if we're not in transition use the value (should be 0 or 1)
67 if(trans_dir == 0.0) {
68 return value > 0.5;
69 }
71 // if we're in transition base it on the direction of the transition
72 return trans_dir > 0.0;
73 }
75 float BoolAnim::get_value() const
76 {
77 return get_value(get_msec());
78 }
80 float BoolAnim::get_value(long tm) const
81 {
82 update(tm);
83 return value;
84 }
86 float BoolAnim::get_dir() const
87 {
88 return get_dir(get_msec());
89 }
91 float BoolAnim::get_dir(long tm) const
92 {
93 update(tm);
94 return trans_dir;
95 }
97 BoolAnim::operator bool() const
98 {
99 return get_state();
100 }
102 BoolAnim::operator float() const
103 {
104 return get_value();
105 }
107 #ifdef WIN32
108 #include <windows.h>
110 static long default_get_msec()
111 {
112 return GetTickCount();
113 }
114 #else
115 #include <sys/time.h>
117 static long default_get_msec()
118 {
119 static struct timeval tv0;
120 struct timeval tv;
122 gettimeofday(&tv, 0);
123 if(tv0.tv_sec == 0 && tv0.tv_usec == 0) {
124 tv0 = tv;
125 return 0;
126 }
127 return (tv.tv_sec - tv0.tv_sec) * 1000 + (tv.tv_usec - tv0.tv_usec) / 1000;
128 }
129 #endif