-
Notifications
You must be signed in to change notification settings - Fork 0
/
interval.h
82 lines (56 loc) · 2.12 KB
/
interval.h
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
#ifndef INTERVAL_H
#define INTERVAL_H
#include <cmath>
#include <limits>
class Interval {
public:
double min, max;
Interval();
Interval(double mn, double mx);
Interval(Interval const & intervalA, Interval const & intervalB);
bool contains(double x) const;
bool surrounds(double x) const;
double clamp(double x) const;
double size() const;
// returns a new interval that's been expanded by a certain amount overall
// (i.e half of whats provided in each direction)
Interval expand(double amount) const;
Interval operator+(double right);
static Interval const empty, universe;
};
Interval operator+(double left, Interval const & right);
// ------
Interval const Interval::empty = Interval(std::numeric_limits<double>::infinity(),
-std::numeric_limits<double>::infinity());
Interval const Interval::universe = Interval(-std::numeric_limits<double>::infinity(),
std::numeric_limits<double>::infinity());
Interval::Interval() : min(empty.min), max(empty.max) { }
Interval::Interval(double mn, double mx) : min(mn), max(mx) { }
Interval::Interval(Interval const & intervalA, Interval const & intervalB)
: min(fmin(intervalA.min, intervalB.min)), max(fmax(intervalA.max, intervalB.max)) { }
bool Interval::contains(double x) const {
return (this->min <= x) && (x <= this->max);
}
// same as contains but exclusive
bool Interval::surrounds(double x) const {
return (this->min < x) && (x < this->max);
}
double Interval::clamp(double x) const {
if (x < min) return min;
if (x > max) return max;
return x;
}
double Interval::size() const {
return this->max - this->min;
}
Interval Interval::expand(double amount) const {
auto halfAmount = amount / 2;
return Interval(this->min - halfAmount, this->max + halfAmount);
}
Interval Interval::operator+(double right) {
return Interval(this->min + right, this->max + right);
}
Interval operator+(double left, Interval & right) {
return right + left;
}
#endif