summaryrefslogtreecommitdiff
path: root/core/time.hpp
blob: 827772b6002a804583f9b711725f1b9816b40033 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#ifndef yg0goL5EwkwiF99Qqt5ozzKAq9U
#define yg0goL5EwkwiF99Qqt5ozzKAq9U

#include <assert.h>
#include <math.h>
#include <iostream>
#include <limits>

struct Time {
  typedef double type;
  type time;

  Time() {}
  Time(type time) : time(time) {}
  
#define Op(op) \
  Time  operator op    (const Time & arg) const { return Time(time op arg.time); } \
  Time& operator op##= (const Time & arg) { time op##= arg.time; return *this; }
  Op(+);
  Op(-);
  Op(*);
  Op(/);
  //  Op(%);
#undef Op
  // WARN: wrong for time/t < epsilon
  inline unsigned long ceilDiv(const Time & t) const { return ceil(time / t.time); }

  
#define CmpOp(op)	inline bool operator op (const Time & arg) const \
  { return time op arg.time; }
  CmpOp(==);
  CmpOp(!=);
  CmpOp(<=);
  CmpOp(>=);
  CmpOp(<);
  CmpOp(>);
#undef CmpOp

  void operator= (type t) { time = t; }
  
  inline type operator() () const { return time; }

  // used as a hack in creating global events; see event_intent.hpp
  static inline Time never() {
    return Time(std::numeric_limits<type>::infinity());
  }

  static inline Time beforeAll() {
    return Time(- std::numeric_limits<type>::infinity());
  }

  // a small value, large enough that t + epsilon > t will always hold
  // during sane simulations
  static inline Time epsilon() {
    return Time(0.000001); // leaves approx. 10 digits for time
  }
};

namespace std {
  ostream& operator<< (ostream &os, Time val) {
    return os << val.time;
  }
}


struct TimeSpan {
  TimeSpan(Time start, Time end, Time delta) : start(start), end(end), delta(delta) {
    assert(start <= end);
    assert(delta > 0);
  };
  Time start, end, delta;
  
  struct iterator {
    const TimeSpan &timeSpan;
    Time current;
    
    iterator(TimeSpan &parent) : timeSpan(parent), current(timeSpan.start) {}
    
    bool hasNext() { return current < timeSpan.end; }
    Time & operator() () { return current; }
    iterator & operator++() { current = fmin(current.time + timeSpan.delta.time, timeSpan.end.time); return *this; }
  };
  
  iterator begin() { return iterator(*this); }
};

struct FakeTime {
  FakeTime() {}
  FakeTime(const Time) {};
};

namespace std {
  ostream& operator<< (ostream &os, FakeTime val) {
    return os << "(FakeTime)";
  }
}

#endif // yg0goL5EwkwiF99Qqt5ozzKAq9U
contact: Jan Huwald // Impressum