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
use rand::prelude::*;
use crate::MapFilter;
use crate::geometry::{Point, Rect};
use crate::random::Rng;
use crate::Map;
pub struct BspInterior {
min_room_size: usize,
}
impl MapFilter for BspInterior {
fn modify_map(&self, rng: &mut StdRng, map: &Map) -> Map {
self.build(rng, map)
}
}
impl BspInterior {
pub fn new() -> Box<BspInterior> {
Box::new(BspInterior{
min_room_size: 8,
})
}
fn build(&self, rng: &mut StdRng, map: &Map) -> Map {
let mut new_map = map.clone();
let mut rects: Vec<Rect> = Vec::new();
rects.push( Rect::new(1, 1, new_map.width-2, new_map.height-2) );
let first_room = rects[0];
self.add_subrects(first_room, rng, &mut rects);
let rooms_copy = rects.clone();
for r in rooms_copy.iter() {
let room = *r;
new_map.add_room(room);
}
for i in 0..new_map.rooms.len()-1 {
let room = new_map.rooms[i];
let next_room = new_map.rooms[i+1];
let start_x = rng.random_range(room.x1, room.x2);
let start_y = rng.random_range(room.y1, room.y2);
let end_x = rng.random_range(next_room.x1, next_room.x2);
let end_y = rng.random_range(next_room.y1, next_room.y2);
new_map.add_corridor(Point::new(start_x, start_y), Point::new(end_x, end_y));
}
new_map
}
fn add_subrects(&self, rect: Rect, rng: &mut StdRng, rects: &mut Vec<Rect>) {
if !rects.is_empty() {
rects.remove(rects.len() - 1);
}
let width = rect.x2 - rect.x1;
let height = rect.y2 - rect.y1;
let half_width = width / 2;
let half_height = height / 2;
let split = rng.roll_dice(1, 4);
if split <= 2 {
let h1 = Rect::new( rect.x1, rect.y1, half_width-1, height );
rects.push( h1 );
if half_width > self.min_room_size { self.add_subrects(h1, rng, rects); }
let h2 = Rect::new( rect.x1 + half_width, rect.y1, half_width, height );
rects.push( h2 );
if half_width > self.min_room_size { self.add_subrects(h2, rng, rects); }
} else {
let v1 = Rect::new( rect.x1, rect.y1, width, half_height-1 );
rects.push(v1);
if half_height > self.min_room_size { self.add_subrects(v1, rng, rects); }
let v2 = Rect::new( rect.x1, rect.y1 + half_height, width, half_height );
rects.push(v2);
if half_height > self.min_room_size { self.add_subrects(v2, rng, rects); }
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{TileType, Map};
#[test]
fn no_corridors_on_borders() {
let mut rng = StdRng::seed_from_u64(907647352);
let gen = BspInterior::new();
let map = gen.modify_map(&mut rng, &Map::new(80, 50));
for i in 0..80 {
assert_eq!(map.at(i, 0), TileType::Wall);
assert_eq!(map.at(i, 49), TileType::Wall);
}
for j in 0..50 {
assert_eq!(map.at(0, j), TileType::Wall);
assert_eq!(map.at(79, j), TileType::Wall);
}
}
}