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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
use math::{Point2, Point3, Point4};
use modules::NoiseModule;
use num_traits::Float;
use std::cell::{Cell, RefCell};
#[derive(Clone, Debug)]
pub struct Cache<Source, T>
where T: Float,
{
pub source: Source,
value: Cell<Option<T>>,
point: RefCell<Vec<T>>,
}
impl<Source, T> Cache<Source, T>
where T: Float,
{
pub fn new(source: Source) -> Cache<Source, T> {
Cache {
source: source,
value: Cell::new(None),
point: RefCell::new(Vec::new()),
}
}
}
impl<Source, T> NoiseModule<Point2<T>> for Cache<Source, T>
where Source: NoiseModule<Point2<T>, Output = T>,
T: Float,
{
type Output = T;
fn get(&self, point: Point2<T>) -> Self::Output {
match self.value.get() {
Some(value) if *self.point.borrow() == point => value,
Some(_) | None => {
let value = self.source.get(point);
self.value.set(Some(value));
let mut cached_point = self.point.borrow_mut();
cached_point.clear();
cached_point.extend_from_slice(&point);
value
},
}
}
}
impl<Source, T> NoiseModule<Point3<T>> for Cache<Source, T>
where Source: NoiseModule<Point3<T>, Output = T>,
T: Float,
{
type Output = T;
fn get(&self, point: Point3<T>) -> Self::Output {
match self.value.get() {
Some(value) if *self.point.borrow() == point => value,
Some(_) | None => {
let value = self.source.get(point);
self.value.set(Some(value));
let mut cached_point = self.point.borrow_mut();
cached_point.clear();
cached_point.extend_from_slice(&point);
value
},
}
}
}
impl<Source, T> NoiseModule<Point4<T>> for Cache<Source, T>
where Source: NoiseModule<Point4<T>, Output = T>,
T: Float,
{
type Output = T;
fn get(&self, point: Point4<T>) -> Self::Output {
match self.value.get() {
Some(value) if *self.point.borrow() == point => value,
Some(_) | None => {
let value = self.source.get(point);
self.value.set(Some(value));
let mut cached_point = self.point.borrow_mut();
cached_point.clear();
cached_point.extend_from_slice(&point);
value
},
}
}
}