morkovmap 0.2.0

A data-driven, Markov Chain-based tilemap generator library and app.
Documentation
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
use std::cmp::Ordering;
use std::collections::HashMap;
use std::fmt::Debug;
use std::hash::Hash;
use std::ops::Add;
use std::sync::{Arc, RwLock};
use crate::sampler::{MultinomialDistribution, DistributionKey};
use arrayvec::ArrayVec;
use serde::{Serialize, Deserialize};


pub trait PositionKey: Copy + Clone + Add<Output = Self> + PartialOrd + Ord + Eq + Hash + num::Num + num::ToPrimitive + num::Zero + num::One + num::Bounded {}
impl<P: Copy + Clone + Add<Output = P> + PartialOrd + Ord + Eq + Hash + num::Num + num::ToPrimitive + num::Zero + num::One + num::Bounded> PositionKey for P {}


#[derive(Hash, Eq, PartialEq, Copy, Clone, Ord, PartialOrd, Debug, Default, Serialize, Deserialize)]
pub struct Position2D<P: PositionKey> {
    pub x: P,
    pub y: P
}

impl<P: PositionKey> Position2D<P> {
    pub fn new(x: P, y: P) -> Self {
        Self {x, y}
    }
}

impl<P: PositionKey> From<(P, P)> for Position2D<P> {
    fn from(value: (P, P)) -> Self {
        Self {
            x: value.0,
            y: value.1
        }
    }
}

impl<P: PositionKey> Into<(P, P)> for Position2D<P> {
    fn into(self) -> (P, P) {
        (self.x, self.y)
    }
}

impl<PA: PositionKey + Add<Output = PA>> Add for Position2D<PA> {
    type Output = Position2D<PA>;

    fn add(self, rhs: Self) -> Self::Output {
        Position2D {
            x: self.x + rhs.x,
            y: self.y + rhs.y
        }
    }
}


impl<P: PositionKey> Position2D<P> {
    pub fn adjacents_cardinal(&self) -> ArrayVec<Position2D<P>, 8> {
        let mut adjacents: ArrayVec::<Position2D<P>, 8> = ArrayVec::new();
        let type_unity: P = num::one();
        let type_three: P = type_unity + type_unity + type_unity;

        for dim in 0..2 {

            let offset_range = num::range(
                 num::zero(),
                 type_three
            );

            for offset in offset_range {
                if offset == type_unity {
                    continue
                };
                let true_offset = offset - type_unity;

                let mut pos_buffer = [self.x, self.y];
                pos_buffer[dim] = pos_buffer[dim] + true_offset;

                let new_pos = Position2D {
                    x: pos_buffer[0].into(),
                    y: pos_buffer[1].into()
                };

                adjacents.push(new_pos);
            }
        }

        adjacents
    }

    pub fn adjacents_octile(&self) -> ArrayVec<Position2D<P>, 8> {
        let mut adjacents: ArrayVec<Position2D<P>, 8> = ArrayVec::new();

        let type_unity: P = P::one();
        let type_three = type_unity + type_unity + type_unity;

        let x_range = num::range(
            P::zero(),
            type_three
        );

        for raw_x_dim in x_range {
            let x_dim = raw_x_dim - type_unity;

            let y_range = num::range(
                P::zero(),
                type_three
            );

            for raw_y_dim in y_range {
                if raw_x_dim.is_one() && raw_y_dim.is_one() {
                    continue
                };
                let y_dim = raw_y_dim - type_unity;
                let new_pos = Position2D {
                    x: self.x + x_dim,
                    y: self.y + y_dim
                };
                adjacents.push(new_pos);
            }
        }

        adjacents
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum MapNodeState<K: DistributionKey> {
    Undecided(MultinomialDistribution<K>),
    Finalized(K)
}

impl<K: DistributionKey> MapNodeState<K> {
    pub fn undecided(possibilities: MultinomialDistribution<K>) -> Self {
        Self::Undecided(possibilities)
    }

    pub fn finalized(assignment: K) -> Self {
        Self::Finalized(assignment)
    }

    pub fn is_assigned(&self) -> bool {
        match self {
            Self::Undecided(_) => false,
            Self::Finalized(_) => true
        }
    }
}

impl<K: DistributionKey> From<MultinomialDistribution<K>> for MapNodeState<K> {
    fn from(value: MultinomialDistribution<K>) -> Self {
        Self::undecided(value)
    }
}

impl<K: DistributionKey> From<K> for MapNodeState<K> {
    fn from(value: K) -> Self {
        Self::finalized(value)
    }
}


#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Map2DNode<K: DistributionKey, P: PositionKey> {
    pub(crate) position: Position2D<P>,
    pub(crate) state: MapNodeState<K>,
}

impl<K: DistributionKey, P: PositionKey> Map2DNode<K, P> {
    pub fn with_possibilities(position: Position2D<P>, possibilities: MultinomialDistribution<K>) -> Self<> {
        Self {
            position,
            state: MapNodeState::undecided(possibilities)
        }
    }

    pub fn with_assignment(position: Position2D<P>, assignment: K) -> Self<> {
        Self {
            position,
            state: MapNodeState::finalized(assignment)
        }
    }

    pub fn entropy(&self) -> f32 {
        match &self.state {
            MapNodeState::Finalized(_) => f32::INFINITY,
            MapNodeState::Undecided(possibilities) => possibilities.entropy()
        }
    }
}

#[derive(Clone, Serialize, Deserialize)]
pub enum MapNodeWrapper<K: DistributionKey, P: PositionKey> {
    Raw(Map2DNode<K, P>),
    Arc(Arc<RwLock<Map2DNode<K, P>>>)
}

impl<K: DistributionKey, P: PositionKey> MapNodeWrapper<K, P> {
    pub fn position(&self) -> Position2D<P> {
        match self { 
            Self::Raw(node) => node.position,
            Self::Arc(arc_node) => arc_node.read().unwrap().position
        }
    }
}

#[derive(Serialize, Deserialize)]
pub struct MapNodeEntropyOrdering<K: DistributionKey, P: PositionKey> {
    pub node: MapNodeWrapper<K, P>
}

impl<K: DistributionKey, P: PositionKey> From<Map2DNode<K, P>> for MapNodeEntropyOrdering<K, P> {
    fn from(value: Map2DNode<K, P>) -> Self {
        Self {
            node: MapNodeWrapper::Raw(value.clone())
        }
    }
}

impl<K: DistributionKey, P: PositionKey> From<Arc<RwLock<Map2DNode<K, P>>>> for MapNodeEntropyOrdering<K, P> {
    fn from(value: Arc<RwLock<Map2DNode<K, P>>>) -> Self {
        Self {
            node: MapNodeWrapper::Arc(value.clone())
        }
    }
}

impl<K: DistributionKey, P: PositionKey> PartialEq<Self> for MapNodeEntropyOrdering<K, P> {
    fn eq(&self, other: &Self) -> bool {
        let my_entropy = match &self.node {
            MapNodeWrapper::Raw(node_data) => node_data.entropy(),
            MapNodeWrapper::Arc(node_data) => node_data.read().unwrap().entropy(),
        };

        let other_entropy = match &other.node {
            MapNodeWrapper::Raw(node_data) => node_data.entropy(),
            MapNodeWrapper::Arc(node_data) => node_data.read().unwrap().entropy(),
        };

        my_entropy == other_entropy
    }
}

impl<K: DistributionKey, P: PositionKey> Eq for MapNodeEntropyOrdering<K, P> {}

impl<K: DistributionKey, P: PositionKey> PartialOrd for MapNodeEntropyOrdering<K, P> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        let my_entropy = match &self.node {
            MapNodeWrapper::Raw(node_data) => node_data.entropy(),
            MapNodeWrapper::Arc(node_data) => node_data.read().unwrap().entropy(),
        };

        let other_entropy = match &other.node {
            MapNodeWrapper::Raw(node_data) => node_data.entropy(),
            MapNodeWrapper::Arc(node_data) => node_data.read().unwrap().entropy(),
        };

        match my_entropy == other_entropy {
            true => Some(Ordering::Equal),
            false => match my_entropy > other_entropy {
                true => Some(Ordering::Less),
                false => Some(Ordering::Greater)
            }
        }
    }
}

impl<K: DistributionKey, P: PositionKey> Ord for MapNodeEntropyOrdering<K, P> {
    fn cmp(&self, other: &Self) -> Ordering {
        self.partial_cmp(other).unwrap()
    }
}

pub type ThreadsafeNodeRef<K, P> = Arc<RwLock<Map2DNode<K, P>>>;

#[derive(Serialize, Deserialize, Clone)]
pub struct Map2D<K: DistributionKey, P: PositionKey> {
    pub tiles: Vec<ThreadsafeNodeRef<K, P>>,
    position_index: HashMap<Position2D<P>, ThreadsafeNodeRef<K, P>>,
    pub undecided_tiles: HashMap<Position2D<P>, ThreadsafeNodeRef<K, P>>,
    pub(crate) min_pos: Position2D<P>,
    pub(crate) max_pos: Position2D<P>,
}

impl<K: DistributionKey, P: PositionKey> Map2D<K, P> {
    pub fn from_tiles<I: IntoIterator<Item=Map2DNode<K, P>>>(tiles: I) -> Map2D<K, P> {
        let iterator = tiles.into_iter();
        let size_estimate = iterator.size_hint().0;

        let mut tile_vec: Vec<ThreadsafeNodeRef<K, P>> = Vec::with_capacity(size_estimate);
        let mut position_hashmap: HashMap<Position2D<P>, ThreadsafeNodeRef<K, P>> = HashMap::with_capacity(size_estimate);
        let mut undecided_hashmap: HashMap<Position2D<P>, ThreadsafeNodeRef<K, P>> = HashMap::with_capacity(size_estimate);
        let mut minx = None;
        let mut miny = None;
        let mut maxx = None;
        let mut maxy = None;

        for tile in iterator {
            let tile_arc = Arc::new(RwLock::new(tile));
            let tile_arc_reader = tile_arc.read().unwrap();
            let tile_pos = tile_arc_reader.position;

            if tile_pos.x < minx.unwrap_or(P::max_value()) { minx = Some(tile_pos.x) };
            if tile_pos.y < miny.unwrap_or(P::max_value()) { miny = Some(tile_pos.y) };
            if tile_pos.x > maxx.unwrap_or(P::min_value()) { maxx = Some(tile_pos.x) };
            if tile_pos.y > maxy.unwrap_or(P::min_value()) { maxy = Some(tile_pos.y) };

            tile_vec.push(tile_arc.to_owned());
            position_hashmap.insert(tile_pos, tile_arc.to_owned());

            if !tile_arc_reader.state.is_assigned() {
                undecided_hashmap.insert(tile_pos, tile_arc.to_owned());
            }
        }

        Self {
            tiles: tile_vec,
            position_index: position_hashmap,
            undecided_tiles: undecided_hashmap,
            min_pos: Position2D::new(
                minx.unwrap_or(maxx.unwrap_or(P::zero())),
                miny.unwrap_or(maxy.unwrap_or(P::zero()))
            ),
            max_pos: Position2D::new(
                maxx.unwrap_or(minx.unwrap_or(P::zero())),
                maxy.unwrap_or(miny.unwrap_or(P::zero()))
            )
        }
    }

    pub fn adjacent_cardinal_from_pos(&self, pos: Position2D<P>) -> ArrayVec<ThreadsafeNodeRef<K, P>, 4> {
        pos
        .adjacents_cardinal()
        .into_iter()
        .filter_map(
            |cand| {
                self.position_index
                    .get(&cand)
                    .map(|x| x.to_owned())
            }
        ).collect()
    }

    pub fn adjacent_cardinal(&self, node: &Map2DNode<K, P>) -> ArrayVec<ThreadsafeNodeRef<K, P>, 4> {
        self.adjacent_cardinal_from_pos(node.position)
    }

    pub fn adjacent_octile_from_pos(&self, pos: Position2D<P>) -> ArrayVec<ThreadsafeNodeRef<K, P>, 8> {
        pos
        .adjacents_octile()
        .into_iter()
        .filter_map(
            |cand| {
                self.position_index
                    .get(&cand)
                    .map(|x| x.to_owned())
            }
        ).collect()
    }

    pub fn adjacent_octile(&self, node: &Map2DNode<K, P>) -> ArrayVec<ThreadsafeNodeRef<K, P>, 8> {
        self.adjacent_octile_from_pos(node.position)
    }

    pub fn get(&self, key: Position2D<P>) -> Option<&ThreadsafeNodeRef<K, P>> {
        self.position_index.get(&key)
    }

    pub fn finalize_tile<'n>(&'n mut self, tile: &'n ThreadsafeNodeRef<K, P>, assignment: K) -> Option<&ThreadsafeNodeRef<K, P>> {
        let tile_writer = tile.write();
        match tile_writer {
            Ok(mut writeable) => {
                writeable.state = MapNodeState::finalized(assignment);
                let removed = self.undecided_tiles.remove(&writeable.position);
                match removed {
                    Some(_) => Some(tile),
                    None => None
                }
            },
            Err(_) => None
        }
    }
}


#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn position_vector_addition_works_positives() {
        let pos_a = Position2D { x: 5, y: 3 };
        let pos_b = Position2D { x: 2, y: 6 };
        let result_pos = pos_a + pos_b;
        assert_eq!(result_pos.x, 7);
        assert_eq!(result_pos.y, 9);
    }

    #[test]
    fn position_vector_addition_works_one_negative() {
        let pos_a = Position2D { x: -5, y: -3 };
        let pos_b = Position2D { x: 2, y: 6 };
        let result_pos = pos_a + pos_b;
        assert_eq!(result_pos.x, -3);
        assert_eq!(result_pos.y, 3);
    }

    #[test]
    fn adjacents_cardinal_sane() {
        let pos = Position2D { x: 2, y: 6 };
        let results = pos.adjacents_cardinal();
        assert_eq!(results[0], Position2D { x: 1, y: 6 });
        assert_eq!(results[1], Position2D { x: 3, y: 6 });
        assert_eq!(results[2], Position2D { x: 2, y: 5 });
        assert_eq!(results[2], Position2D { x: 2, y: 7 });
    }

    #[test]
    fn serde_pos() {
        let pos = Position2D { x: 2, y: 6 };
        let results = serde_json::to_string(&pos).unwrap();
        assert!(results.len() > 0)
    }
}