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
/*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can
* obtain one at http://mozilla.org/MPL/2.0/.
*/
mod render;
use crate::{
node::{Level, NodeId, Store},
parse::rle::Rle,
BoundingBox, Position,
};
const INITIAL_LEVEL: Level = Level(7);
/// Conway's Game of Life.
#[derive(Clone, Debug)]
pub struct Life {
/// The root node of the Life grid.
root: NodeId,
/// The store.
store: Store,
/// How many generations the Life grid has been advanced.
generation: u128,
/// A bounding box containing all alive cells.
bounding_box: Option<BoundingBox>,
}
impl Life {
/// Creates a new empty Life grid.
///
/// # Examples
///
/// ```
/// let mut life = smeagol::Life::new();
/// assert_eq!(life.population(), 0);
/// ```
pub fn new() -> Self {
let mut store = Store::new();
let root = store.create_empty(INITIAL_LEVEL);
Self {
root,
store,
generation: 0,
bounding_box: None,
}
}
/// Creates a Life grid from the given RLE file.
///
/// # Examples
///
/// ```
/// let mut life = smeagol::Life::from_rle_file("./assets/glider.rle").unwrap();
/// assert_eq!(life.population(), 5);
/// ```
pub fn from_rle_file<P>(path: P) -> Result<Self, failure::Error>
where
P: AsRef<std::path::Path>,
{
let rle = Rle::from_file(path)?;
Ok(Self::from_rle(&rle))
}
pub fn from_rle_file_contents(contents: &[u8]) -> Result<Self, failure::Error> {
let rle = Rle::from_file_contents(contents)?;
Ok(Self::from_rle(&rle))
}
/// Creates a Life grid from the given RLE pattern.
///
/// # Examples
///
/// ```
/// // integral sign
/// let mut life = smeagol::Life::from_rle_pattern(b"3b2o$2bobo$2bo2b$obo2b$2o!").unwrap();
/// assert_eq!(life.population(), 9);
/// ```
pub fn from_rle_pattern(pattern: &[u8]) -> Result<Self, failure::Error> {
let rle = Rle::from_pattern(pattern)?;
Ok(Self::from_rle(&rle))
}
/// Creates a Life grid from the given RLE struct.
pub fn from_rle(rle: &Rle) -> Self {
let alive_cells = rle
.alive_cells()
.into_iter()
.map(|(x, y)| Position::new(i64::from(x), i64::from(y)))
.collect::<Vec<_>>();
let mut store = Store::new();
let mut root = store.create_empty(INITIAL_LEVEL);
if !alive_cells.is_empty() {
let x_min = alive_cells.iter().min_by_key(|pos| pos.x).unwrap().x;
let x_max = alive_cells.iter().max_by_key(|pos| pos.x).unwrap().x;
let y_min = alive_cells.iter().min_by_key(|pos| pos.y).unwrap().y;
let y_max = alive_cells.iter().max_by_key(|pos| pos.y).unwrap().y;
while x_min < root.min_coord(&store)
|| x_max > root.max_coord(&store)
|| y_min < root.min_coord(&store)
|| y_max > root.max_coord(&store)
{
root = root.expand(&mut store);
}
root = root.set_cells_alive(&mut store, alive_cells);
}
Self {
bounding_box: root.bounding_box(&store),
root,
store,
generation: 0,
}
}
/// Sets the cell at the given position in the Life grid to be an alive cell.
///
/// # Examples
///
/// ```
/// let mut life = smeagol::Life::new();
///
/// // create a block
/// life.set_cell_alive(smeagol::Position::new(0, 0));
/// life.set_cell_alive(smeagol::Position::new(1, 0));
/// life.set_cell_alive(smeagol::Position::new(0, 1));
/// life.set_cell_alive(smeagol::Position::new(1, 1));
///
/// assert_eq!(life.population(), 4);
/// ```
pub fn set_cell_alive(&mut self, position: Position) {
while position.x < self.root.min_coord(&self.store)
|| position.y < self.root.min_coord(&self.store)
|| position.x > self.root.max_coord(&self.store)
|| position.y > self.root.max_coord(&self.store)
{
self.root = self.root.expand(&mut self.store);
}
self.root = self.root.set_cell_alive(&mut self.store, position);
self.bounding_box = self.root.bounding_box(&self.store);
}
/// Returns a list of the positions of the alive cells in the Life grid.
///
/// ```
/// # fn main() -> Result<(), failure::Error> {
/// // glider
/// let life = smeagol::Life::from_rle_pattern(b"bob$2bo$3o!")?;
///
/// for pos in life.get_alive_cells() {
/// // do something
/// }
/// # Ok(())
/// # }
/// ```
pub fn get_alive_cells(&self) -> Vec<Position> {
self.root.get_alive_cells(&self.store)
}
/// Returns true if the given bounding box contains any alive cells.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), failure::Error> {
/// // glider
/// let life = smeagol::Life::from_rle_pattern(b"bob$2bo$3o!")?;
///
/// assert!(life.contains_alive_cells(life.bounding_box().unwrap()));
/// # Ok(())
/// # }
/// ```
pub fn contains_alive_cells(&self, bounding_box: BoundingBox) -> bool {
if let Some(self_bbox) = self.bounding_box {
if let Some(intersect) = self_bbox.intersect(bounding_box) {
self.root.contains_alive_cells(&self.store, intersect)
} else {
false
}
} else {
false
}
}
/// Returns a bounding box containing all the alive cells in the Life grid.
///
/// Returns `None` if there are no alive cells in the grid.
///
/// # Examples
///
/// ```
/// let mut life = smeagol::Life::new();
/// assert!(life.bounding_box().is_none());
///
/// life.set_cell_alive(smeagol::Position::new(0, 0));
/// assert!(life.bounding_box().is_some());
/// ```
pub fn bounding_box(&self) -> Option<BoundingBox> {
self.bounding_box
}
/// Returns the number of generations that have been advanced in the Life grid.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), failure::Error> {
/// let mut life = smeagol::Life::from_rle_pattern(b"bob$2bo$3o!")?;
/// assert_eq!(life.generation(), 0);
///
/// life.step();
/// assert_eq!(life.generation(), 1);
/// # Ok(())
/// # }
/// ```
pub fn generation(&self) -> u128 {
self.generation
}
/// Returns the number of alive cells in the grid.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), failure::Error> {
/// let mut life = smeagol::Life::from_rle_pattern(b"bob$2bo$3o!")?;
/// assert_eq!(life.population(), 5);
/// # Ok(())
/// # }
/// ```
pub fn population(&self) -> u128 {
self.root.population(&self.store)
}
/// Returns the current step size.
///
/// The default step size is 1.
pub fn step_size(&self) -> u64 {
1 << self.store.step_log_2()
}
/// Returns the step size log 2.
pub fn step_log_2(&self) -> u8 {
self.store.step_log_2()
}
/// Sets the step size to be `2^step_log_2`.
///
/// This clears the cache of previously computed steps.
pub fn set_step_log_2(&mut self, step_log_2: u8) {
self.store.set_step_log_2(step_log_2);
}
/// Pads the Life grid such that it can be advanced into the future without the edges of the
/// node interfering.
fn pad(&mut self) {
while self.root.level(&self.store) < INITIAL_LEVEL
|| self.store.step_log_2() > self.root.level(&self.store).0 - 2
|| self.root.ne(&self.store).population(&self.store)
!= self
.root
.ne(&self.store)
.sw(&self.store)
.sw(&self.store)
.population(&self.store)
|| self.root.nw(&self.store).population(&self.store)
!= self
.root
.nw(&self.store)
.se(&self.store)
.se(&self.store)
.population(&self.store)
|| self.root.se(&self.store).population(&self.store)
!= self
.root
.se(&self.store)
.nw(&self.store)
.nw(&self.store)
.population(&self.store)
|| self.root.sw(&self.store).population(&self.store)
!= self
.root
.sw(&self.store)
.ne(&self.store)
.ne(&self.store)
.population(&self.store)
{
self.root = self.root.expand(&mut self.store);
}
}
/// Advances the Life grid into the future.
///
/// The number of generations advanced is determined by the step size.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), failure::Error> {
/// let mut life = smeagol::Life::from_rle_pattern(b"bob$2bo$3o!")?;
///
/// // step size of 32
/// life.set_step_log_2(5);
///
/// life.step();
/// assert_eq!(life.generation(), 32);
/// # Ok(())
/// # }
/// ```
pub fn step(&mut self) {
self.pad();
self.root = self.root.step(&mut self.store);
self.generation += u128::from(self.step_size());
self.bounding_box = self.root.bounding_box(&self.store);
}
}
impl Default for Life {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default() {
let life = Life::default();
assert_eq!(life.generation(), 0);
assert_eq!(life.population(), 0);
}
#[test]
fn get_set_step_size() {
let mut life = Life::new();
assert_eq!(life.step_log_2(), 0);
assert_eq!(life.step_size(), 1);
life.set_step_log_2(10);
assert_eq!(life.step_log_2(), 10);
assert_eq!(life.step_size(), 1024);
}
#[test]
fn empty() {
let min = i64::min_value();
let max = i64::max_value();
let life = Life::new();
assert_eq!(life.bounding_box(), None);
assert!(!life.contains_alive_cells(BoundingBox::new(
Position::new(min, min),
Position::new(max, max)
)));
}
#[test]
fn from_rle_file_contents() {
let life = Life::from_rle_file_contents(b"x = 2, y = 2\n2o$2o!").unwrap();
assert_eq!(life.population(), 4);
}
#[test]
fn from_rle_pattern() {
let life = Life::from_rle_pattern(b"bob$2bo$3o!").unwrap();
assert_eq!(life.population(), 5);
}
#[test]
fn position_extremes() {
let mut life = Life::new();
let min = i64::min_value();
let max = i64::max_value();
life.set_cell_alive(Position::new(min, min));
life.set_cell_alive(Position::new(min, max));
life.set_cell_alive(Position::new(max, min));
life.set_cell_alive(Position::new(max, max));
assert_eq!(life.population(), 4);
let bbox = life.bounding_box().unwrap();
assert_eq!(bbox.upper_left(), Position::new(min, min),);
assert_eq!(bbox.lower_right(), Position::new(max, max),);
}
}