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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
use crate::{
    terrain::MapSizeLg,
    util::GridHasher,
    vol::{BaseVol, ReadVol, RectRasterableVol, SampleVol, WriteVol},
    volumes::dyna::DynaError,
};
use hashbrown::{hash_map, HashMap};
use std::{fmt::Debug, ops::Deref, sync::Arc};
use vek::*;

#[derive(Debug, Clone)]
pub enum VolGrid2dError<V: RectRasterableVol> {
    NoSuchChunk,
    ChunkError(V::Error),
    DynaError(DynaError),
    InvalidChunkSize,
}

// V = Voxel
// S = Size (replace with a const when const generics is a thing)
// M = Chunk metadata
#[derive(Clone)]
pub struct VolGrid2d<V: RectRasterableVol> {
    /// Size of the entire (not just loaded) map.
    map_size_lg: MapSizeLg,
    /// Default voxel for use outside of max map bounds.
    default: Arc<V>,
    chunks: HashMap<Vec2<i32>, Arc<V>, GridHasher>,
}

impl<V: RectRasterableVol> VolGrid2d<V> {
    #[inline(always)]
    pub fn chunk_key<P: Into<Vec2<i32>>>(pos: P) -> Vec2<i32> {
        pos.into()
            .map2(V::RECT_SIZE, |e, sz: u32| e.div_euclid(sz as i32))
    }

    #[inline(always)]
    pub fn key_chunk<K: Into<Vec2<i32>>>(key: K) -> Vec2<i32> {
        key.into() * V::RECT_SIZE.map(|e| e as i32)
    }

    #[inline(always)]
    pub fn par_keys(&self) -> hashbrown::hash_map::rayon::ParKeys<Vec2<i32>, Arc<V>>
    where
        V: Send + Sync,
    {
        self.chunks.par_keys()
    }

    #[inline(always)]
    pub fn chunk_offs(pos: Vec3<i32>) -> Vec3<i32> {
        let offs = Vec2::<i32>::from(pos).map2(V::RECT_SIZE, |e, sz| e & (sz - 1) as i32);
        Vec3::new(offs.x, offs.y, pos.z)
    }
}

impl<V: RectRasterableVol + Debug> BaseVol for VolGrid2d<V> {
    type Error = VolGrid2dError<V>;
    type Vox = V::Vox;
}

impl<V: RectRasterableVol + ReadVol + Debug> ReadVol for VolGrid2d<V> {
    #[inline(always)]
    fn get(&self, pos: Vec3<i32>) -> Result<&V::Vox, VolGrid2dError<V>> {
        let ck = Self::chunk_key(pos);
        self.get_key(ck)
            .ok_or(VolGrid2dError::NoSuchChunk)
            .map(|chunk| {
                let co = Self::chunk_offs(pos);
                // Always within bounds of the chunk, so we can use the get_unchecked form
                chunk.get_unchecked(co)
            })
    }

    /// Call provided closure with each block in the supplied Aabb
    /// Areas outside loaded chunks are ignored
    fn for_each_in(&self, aabb: Aabb<i32>, mut f: impl FnMut(Vec3<i32>, Self::Vox))
    where
        Self::Vox: Copy,
    {
        let min_chunk_key = self.pos_key(aabb.min);
        let max_chunk_key = self.pos_key(aabb.max);
        for key_x in min_chunk_key.x..max_chunk_key.x + 1 {
            for key_y in min_chunk_key.y..max_chunk_key.y + 1 {
                let key = Vec2::new(key_x, key_y);
                let pos = self.key_pos(key);
                // Calculate intersection of Aabb and this chunk
                // TODO: should we do this more implicitly as part of the loop
                // TODO: this probably has to be computed in the chunk.for_each_in() as well
                // maybe remove here?
                let intersection = aabb.intersection(Aabb {
                    min: pos.with_z(i32::MIN),
                    // -1 here since the Aabb is inclusive and chunk_offs below will wrap it if
                    // it's outside the range of the chunk
                    max: (pos + Self::chunk_size().map(|e| e as i32) - 1).with_z(i32::MAX),
                });
                // Map intersection into chunk coordinates
                let intersection = Aabb {
                    min: Self::chunk_offs(intersection.min),
                    max: Self::chunk_offs(intersection.max),
                };
                if let Some(chonk) = self.get_key(key) {
                    chonk.for_each_in(intersection, |pos_offset, block| f(pos_offset + pos, block));
                }
            }
        }
    }
}

// TODO: This actually breaks the API: samples are supposed to have an offset of
// zero! TODO: Should this be changed, perhaps?
impl<I: Into<Aabr<i32>>, V: RectRasterableVol + ReadVol + Debug> SampleVol<I> for VolGrid2d<V> {
    type Sample = VolGrid2d<V>;

    /// Take a sample of the terrain by cloning the voxels within the provided
    /// range.
    ///
    /// Note that the resultant volume does not carry forward metadata from the
    /// original chunks.
    fn sample(&self, range: I) -> Result<Self::Sample, VolGrid2dError<V>> {
        let range = range.into();

        let mut sample = VolGrid2d::new(self.map_size_lg, Arc::clone(&self.default))?;
        let chunk_min = Self::chunk_key(range.min);
        let chunk_max = Self::chunk_key(range.max);
        for x in chunk_min.x..chunk_max.x + 1 {
            for y in chunk_min.y..chunk_max.y + 1 {
                let chunk_key = Vec2::new(x, y);

                let chunk = self.get_key_arc_real(chunk_key).cloned();

                if let Some(chunk) = chunk {
                    sample.insert(chunk_key, chunk);
                }
            }
        }

        Ok(sample)
    }
}

impl<V: RectRasterableVol + WriteVol + Clone + Debug> WriteVol for VolGrid2d<V> {
    #[inline(always)]
    fn set(&mut self, pos: Vec3<i32>, vox: V::Vox) -> Result<V::Vox, VolGrid2dError<V>> {
        let ck = Self::chunk_key(pos);
        self.chunks
            .get_mut(&ck)
            .ok_or(VolGrid2dError::NoSuchChunk)
            .and_then(|chunk| {
                let co = Self::chunk_offs(pos);
                Arc::make_mut(chunk)
                    .set(co, vox)
                    .map_err(VolGrid2dError::ChunkError)
            })
    }
}

impl<V: RectRasterableVol> VolGrid2d<V> {
    pub fn new(map_size_lg: MapSizeLg, default: Arc<V>) -> Result<Self, VolGrid2dError<V>> {
        if Self::chunk_size()
            .map(|e| e.is_power_of_two() && e > 0)
            .reduce_and()
        {
            Ok(Self {
                map_size_lg,
                default,
                chunks: HashMap::default(),
            })
        } else {
            Err(VolGrid2dError::InvalidChunkSize)
        }
    }

    #[inline(always)]
    pub fn chunk_size() -> Vec2<u32> { V::RECT_SIZE }

    pub fn insert(&mut self, key: Vec2<i32>, chunk: Arc<V>) -> Option<Arc<V>> {
        self.chunks.insert(key, chunk)
    }

    #[inline(always)]
    pub fn get_key(&self, key: Vec2<i32>) -> Option<&V> {
        self.get_key_arc(key).map(|arc_chunk| arc_chunk.as_ref())
    }

    #[inline(always)]
    pub fn get_key_real(&self, key: Vec2<i32>) -> Option<&V> {
        self.get_key_arc_real(key)
            .map(|arc_chunk| arc_chunk.as_ref())
    }

    #[inline(always)]
    pub fn contains_key(&self, key: Vec2<i32>) -> bool {
        self.contains_key_real(key) ||
            // Counterintuitively, areas outside the map are *always* considered to be in it, since
            // they're assigned the default chunk.
            !self.map_size_lg.contains_chunk(key)
    }

    #[inline(always)]
    pub fn contains_key_real(&self, key: Vec2<i32>) -> bool { self.chunks.contains_key(&key) }

    #[inline(always)]
    pub fn get_key_arc(&self, key: Vec2<i32>) -> Option<&Arc<V>> {
        self.get_key_arc_real(key).or_else(|| {
            if !self.map_size_lg.contains_chunk(key) {
                Some(&self.default)
            } else {
                None
            }
        })
    }

    #[inline(always)]
    pub fn get_key_arc_real(&self, key: Vec2<i32>) -> Option<&Arc<V>> { self.chunks.get(&key) }

    pub fn clear(&mut self) { self.chunks.clear(); }

    pub fn drain(&mut self) -> hash_map::Drain<Vec2<i32>, Arc<V>> { self.chunks.drain() }

    pub fn remove(&mut self, key: Vec2<i32>) -> Option<Arc<V>> { self.chunks.remove(&key) }

    /// Converts a chunk key (i.e. coordinates in terms of chunks) into a
    /// position in the world (aka "wpos").
    ///
    /// The returned position will be in the corner of the chunk.
    #[inline(always)]
    pub fn key_pos(&self, key: Vec2<i32>) -> Vec2<i32> { Self::key_chunk(key) }

    /// Converts a position in the world into a chunk key (i.e. coordinates in
    /// terms of chunks).
    #[inline(always)]
    pub fn pos_key(&self, pos: Vec3<i32>) -> Vec2<i32> { Self::chunk_key(pos) }

    /// Gets the chunk that contains the provided world position.
    #[inline(always)]
    pub fn pos_chunk(&self, pos: Vec3<i32>) -> Option<&V> { self.get_key(self.pos_key(pos)) }

    pub fn iter(&self) -> ChunkIter<V> {
        ChunkIter {
            iter: self.chunks.iter(),
        }
    }

    pub fn cached(&self) -> CachedVolGrid2d<V> { CachedVolGrid2d::new(self) }
}

pub struct CachedVolGrid2d<'a, V: RectRasterableVol> {
    vol_grid_2d: &'a VolGrid2d<V>,
    // This can't be invalidated by mutations of the chunks hashmap since we hold an immutable
    // reference to the `VolGrid2d`
    cache: Option<(Vec2<i32>, Arc<V>)>,
}

impl<'a, V: RectRasterableVol> CachedVolGrid2d<'a, V> {
    fn new(vol_grid_2d: &'a VolGrid2d<V>) -> Self {
        Self {
            vol_grid_2d,
            cache: None,
        }
    }
}

impl<'a, V: RectRasterableVol + ReadVol> CachedVolGrid2d<'a, V> {
    #[inline(always)]
    pub fn get(&mut self, pos: Vec3<i32>) -> Result<&V::Vox, VolGrid2dError<V>> {
        // Calculate chunk key from block pos
        let ck = VolGrid2d::<V>::chunk_key(pos);
        let chunk = if self
            .cache
            .as_ref()
            .map(|(key, _)| *key == ck)
            .unwrap_or(false)
        {
            // If the chunk with that key is in the cache use that
            &self.cache.as_ref().unwrap().1
        } else {
            // Otherwise retrieve from the hashmap
            let chunk = self
                .vol_grid_2d
                .get_key_arc(ck)
                .ok_or(VolGrid2dError::NoSuchChunk)?;
            // Store most recently looked up chunk in the cache
            self.cache = Some((ck, Arc::clone(chunk)));
            chunk
        };
        let co = VolGrid2d::<V>::chunk_offs(pos);
        Ok(chunk.get_unchecked(co))
    }
}

impl<'a, V: RectRasterableVol> Deref for CachedVolGrid2d<'a, V> {
    type Target = VolGrid2d<V>;

    fn deref(&self) -> &Self::Target { self.vol_grid_2d }
}

pub struct ChunkIter<'a, V: RectRasterableVol> {
    iter: hash_map::Iter<'a, Vec2<i32>, Arc<V>>,
}

impl<'a, V: RectRasterableVol> Iterator for ChunkIter<'a, V> {
    type Item = (Vec2<i32>, &'a Arc<V>);

    fn next(&mut self) -> Option<Self::Item> { self.iter.next().map(|(k, c)| (*k, c)) }
}